You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

oauth2_application.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "fmt"
  9. "net/url"
  10. "time"
  11. "code.gitea.io/gitea/modules/secret"
  12. "code.gitea.io/gitea/modules/setting"
  13. "code.gitea.io/gitea/modules/timeutil"
  14. "github.com/dgrijalva/jwt-go"
  15. uuid "github.com/satori/go.uuid"
  16. "github.com/unknwon/com"
  17. "golang.org/x/crypto/bcrypt"
  18. "xorm.io/xorm"
  19. )
  20. // OAuth2Application represents an OAuth2 client (RFC 6749)
  21. type OAuth2Application struct {
  22. ID int64 `xorm:"pk autoincr"`
  23. UID int64 `xorm:"INDEX"`
  24. User *User `xorm:"-"`
  25. Name string
  26. ClientID string `xorm:"unique"`
  27. ClientSecret string
  28. RedirectURIs []string `xorm:"redirect_uris JSON TEXT"`
  29. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  30. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  31. }
  32. // TableName sets the table name to `oauth2_application`
  33. func (app *OAuth2Application) TableName() string {
  34. return "oauth2_application"
  35. }
  36. // PrimaryRedirectURI returns the first redirect uri or an empty string if empty
  37. func (app *OAuth2Application) PrimaryRedirectURI() string {
  38. if len(app.RedirectURIs) == 0 {
  39. return ""
  40. }
  41. return app.RedirectURIs[0]
  42. }
  43. // LoadUser will load User by UID
  44. func (app *OAuth2Application) LoadUser() (err error) {
  45. if app.User == nil {
  46. app.User, err = GetUserByID(app.UID)
  47. }
  48. return
  49. }
  50. // ContainsRedirectURI checks if redirectURI is allowed for app
  51. func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool {
  52. return com.IsSliceContainsStr(app.RedirectURIs, redirectURI)
  53. }
  54. // GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
  55. func (app *OAuth2Application) GenerateClientSecret() (string, error) {
  56. clientSecret, err := secret.New()
  57. if err != nil {
  58. return "", err
  59. }
  60. hashedSecret, err := bcrypt.GenerateFromPassword([]byte(clientSecret), bcrypt.DefaultCost)
  61. if err != nil {
  62. return "", err
  63. }
  64. app.ClientSecret = string(hashedSecret)
  65. if _, err := x.ID(app.ID).Cols("client_secret").Update(app); err != nil {
  66. return "", err
  67. }
  68. return clientSecret, nil
  69. }
  70. // ValidateClientSecret validates the given secret by the hash saved in database
  71. func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool {
  72. return bcrypt.CompareHashAndPassword([]byte(app.ClientSecret), secret) == nil
  73. }
  74. // GetGrantByUserID returns a OAuth2Grant by its user and application ID
  75. func (app *OAuth2Application) GetGrantByUserID(userID int64) (*OAuth2Grant, error) {
  76. return app.getGrantByUserID(x, userID)
  77. }
  78. func (app *OAuth2Application) getGrantByUserID(e Engine, userID int64) (grant *OAuth2Grant, err error) {
  79. grant = new(OAuth2Grant)
  80. if has, err := e.Where("user_id = ? AND application_id = ?", userID, app.ID).Get(grant); err != nil {
  81. return nil, err
  82. } else if !has {
  83. return nil, nil
  84. }
  85. return grant, nil
  86. }
  87. // CreateGrant generates a grant for an user
  88. func (app *OAuth2Application) CreateGrant(userID int64) (*OAuth2Grant, error) {
  89. return app.createGrant(x, userID)
  90. }
  91. func (app *OAuth2Application) createGrant(e Engine, userID int64) (*OAuth2Grant, error) {
  92. grant := &OAuth2Grant{
  93. ApplicationID: app.ID,
  94. UserID: userID,
  95. }
  96. _, err := e.Insert(grant)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return grant, nil
  101. }
  102. // GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found.
  103. func GetOAuth2ApplicationByClientID(clientID string) (app *OAuth2Application, err error) {
  104. return getOAuth2ApplicationByClientID(x, clientID)
  105. }
  106. func getOAuth2ApplicationByClientID(e Engine, clientID string) (app *OAuth2Application, err error) {
  107. app = new(OAuth2Application)
  108. has, err := e.Where("client_id = ?", clientID).Get(app)
  109. if !has {
  110. return nil, ErrOAuthClientIDInvalid{ClientID: clientID}
  111. }
  112. return
  113. }
  114. // GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
  115. func GetOAuth2ApplicationByID(id int64) (app *OAuth2Application, err error) {
  116. return getOAuth2ApplicationByID(x, id)
  117. }
  118. func getOAuth2ApplicationByID(e Engine, id int64) (app *OAuth2Application, err error) {
  119. app = new(OAuth2Application)
  120. has, err := e.ID(id).Get(app)
  121. if err != nil {
  122. return nil, err
  123. }
  124. if !has {
  125. return nil, ErrOAuthApplicationNotFound{ID: id}
  126. }
  127. return app, nil
  128. }
  129. // GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user
  130. func GetOAuth2ApplicationsByUserID(userID int64) (apps []*OAuth2Application, err error) {
  131. return getOAuth2ApplicationsByUserID(x, userID)
  132. }
  133. func getOAuth2ApplicationsByUserID(e Engine, userID int64) (apps []*OAuth2Application, err error) {
  134. apps = make([]*OAuth2Application, 0)
  135. err = e.Where("uid = ?", userID).Find(&apps)
  136. return
  137. }
  138. // CreateOAuth2ApplicationOptions holds options to create an oauth2 application
  139. type CreateOAuth2ApplicationOptions struct {
  140. Name string
  141. UserID int64
  142. RedirectURIs []string
  143. }
  144. // CreateOAuth2Application inserts a new oauth2 application
  145. func CreateOAuth2Application(opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  146. return createOAuth2Application(x, opts)
  147. }
  148. func createOAuth2Application(e Engine, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  149. clientID := uuid.NewV4().String()
  150. app := &OAuth2Application{
  151. UID: opts.UserID,
  152. Name: opts.Name,
  153. ClientID: clientID,
  154. RedirectURIs: opts.RedirectURIs,
  155. }
  156. if _, err := e.Insert(app); err != nil {
  157. return nil, err
  158. }
  159. return app, nil
  160. }
  161. // UpdateOAuth2ApplicationOptions holds options to update an oauth2 application
  162. type UpdateOAuth2ApplicationOptions struct {
  163. ID int64
  164. Name string
  165. UserID int64
  166. RedirectURIs []string
  167. }
  168. // UpdateOAuth2Application updates an oauth2 application
  169. func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) error {
  170. return updateOAuth2Application(x, opts)
  171. }
  172. func updateOAuth2Application(e Engine, opts UpdateOAuth2ApplicationOptions) error {
  173. app := &OAuth2Application{
  174. ID: opts.ID,
  175. UID: opts.UserID,
  176. Name: opts.Name,
  177. RedirectURIs: opts.RedirectURIs,
  178. }
  179. if _, err := e.ID(opts.ID).Update(app); err != nil {
  180. return err
  181. }
  182. return nil
  183. }
  184. func deleteOAuth2Application(sess *xorm.Session, id, userid int64) error {
  185. if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil {
  186. return err
  187. } else if deleted == 0 {
  188. return fmt.Errorf("cannot find oauth2 application")
  189. }
  190. codes := make([]*OAuth2AuthorizationCode, 0)
  191. // delete correlating auth codes
  192. if err := sess.Join("INNER", "oauth2_grant",
  193. "oauth2_authorization_code.grant_id = oauth2_grant.id AND oauth2_grant.application_id = ?", id).Find(&codes); err != nil {
  194. return err
  195. }
  196. codeIDs := make([]int64, 0)
  197. for _, grant := range codes {
  198. codeIDs = append(codeIDs, grant.ID)
  199. }
  200. if _, err := sess.In("id", codeIDs).Delete(new(OAuth2AuthorizationCode)); err != nil {
  201. return err
  202. }
  203. if _, err := sess.Where("application_id = ?", id).Delete(new(OAuth2Grant)); err != nil {
  204. return err
  205. }
  206. return nil
  207. }
  208. // DeleteOAuth2Application deletes the application with the given id and the grants and auth codes related to it. It checks if the userid was the creator of the app.
  209. func DeleteOAuth2Application(id, userid int64) error {
  210. sess := x.NewSession()
  211. if err := sess.Begin(); err != nil {
  212. return err
  213. }
  214. if err := deleteOAuth2Application(sess, id, userid); err != nil {
  215. return err
  216. }
  217. return sess.Commit()
  218. }
  219. // ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
  220. func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, error) {
  221. sess := x.
  222. Where("uid=?", uid).
  223. Desc("id")
  224. if listOptions.Page != 0 {
  225. sess = listOptions.setSessionPagination(sess)
  226. apps := make([]*OAuth2Application, 0, listOptions.PageSize)
  227. return apps, sess.Find(&apps)
  228. }
  229. apps := make([]*OAuth2Application, 0, 5)
  230. return apps, sess.Find(&apps)
  231. }
  232. //////////////////////////////////////////////////////
  233. // OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.
  234. type OAuth2AuthorizationCode struct {
  235. ID int64 `xorm:"pk autoincr"`
  236. Grant *OAuth2Grant `xorm:"-"`
  237. GrantID int64
  238. Code string `xorm:"INDEX unique"`
  239. CodeChallenge string
  240. CodeChallengeMethod string
  241. RedirectURI string
  242. ValidUntil timeutil.TimeStamp `xorm:"index"`
  243. }
  244. // TableName sets the table name to `oauth2_authorization_code`
  245. func (code *OAuth2AuthorizationCode) TableName() string {
  246. return "oauth2_authorization_code"
  247. }
  248. // GenerateRedirectURI generates a redirect URI for a successful authorization request. State will be used if not empty.
  249. func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect *url.URL, err error) {
  250. if redirect, err = url.Parse(code.RedirectURI); err != nil {
  251. return
  252. }
  253. q := redirect.Query()
  254. if state != "" {
  255. q.Set("state", state)
  256. }
  257. q.Set("code", code.Code)
  258. redirect.RawQuery = q.Encode()
  259. return
  260. }
  261. // Invalidate deletes the auth code from the database to invalidate this code
  262. func (code *OAuth2AuthorizationCode) Invalidate() error {
  263. return code.invalidate(x)
  264. }
  265. func (code *OAuth2AuthorizationCode) invalidate(e Engine) error {
  266. _, err := e.Delete(code)
  267. return err
  268. }
  269. // ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation.
  270. func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool {
  271. return code.validateCodeChallenge(verifier)
  272. }
  273. func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool {
  274. switch code.CodeChallengeMethod {
  275. case "S256":
  276. // base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6
  277. h := sha256.Sum256([]byte(verifier))
  278. hashedVerifier := base64.RawURLEncoding.EncodeToString(h[:])
  279. return hashedVerifier == code.CodeChallenge
  280. case "plain":
  281. return verifier == code.CodeChallenge
  282. case "":
  283. return true
  284. default:
  285. // unsupported method -> return false
  286. return false
  287. }
  288. }
  289. // GetOAuth2AuthorizationByCode returns an authorization by its code
  290. func GetOAuth2AuthorizationByCode(code string) (*OAuth2AuthorizationCode, error) {
  291. return getOAuth2AuthorizationByCode(x, code)
  292. }
  293. func getOAuth2AuthorizationByCode(e Engine, code string) (auth *OAuth2AuthorizationCode, err error) {
  294. auth = new(OAuth2AuthorizationCode)
  295. if has, err := e.Where("code = ?", code).Get(auth); err != nil {
  296. return nil, err
  297. } else if !has {
  298. return nil, nil
  299. }
  300. auth.Grant = new(OAuth2Grant)
  301. if has, err := e.ID(auth.GrantID).Get(auth.Grant); err != nil {
  302. return nil, err
  303. } else if !has {
  304. return nil, nil
  305. }
  306. return auth, nil
  307. }
  308. //////////////////////////////////////////////////////
  309. // OAuth2Grant represents the permission of an user for a specifc application to access resources
  310. type OAuth2Grant struct {
  311. ID int64 `xorm:"pk autoincr"`
  312. UserID int64 `xorm:"INDEX unique(user_application)"`
  313. Application *OAuth2Application `xorm:"-"`
  314. ApplicationID int64 `xorm:"INDEX unique(user_application)"`
  315. Counter int64 `xorm:"NOT NULL DEFAULT 1"`
  316. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  317. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  318. }
  319. // TableName sets the table name to `oauth2_grant`
  320. func (grant *OAuth2Grant) TableName() string {
  321. return "oauth2_grant"
  322. }
  323. // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the databse
  324. func (grant *OAuth2Grant) GenerateNewAuthorizationCode(redirectURI, codeChallenge, codeChallengeMethod string) (*OAuth2AuthorizationCode, error) {
  325. return grant.generateNewAuthorizationCode(x, redirectURI, codeChallenge, codeChallengeMethod)
  326. }
  327. func (grant *OAuth2Grant) generateNewAuthorizationCode(e Engine, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
  328. var codeSecret string
  329. if codeSecret, err = secret.New(); err != nil {
  330. return &OAuth2AuthorizationCode{}, err
  331. }
  332. code = &OAuth2AuthorizationCode{
  333. Grant: grant,
  334. GrantID: grant.ID,
  335. RedirectURI: redirectURI,
  336. Code: codeSecret,
  337. CodeChallenge: codeChallenge,
  338. CodeChallengeMethod: codeChallengeMethod,
  339. }
  340. if _, err := e.Insert(code); err != nil {
  341. return nil, err
  342. }
  343. return code, nil
  344. }
  345. // IncreaseCounter increases the counter and updates the grant
  346. func (grant *OAuth2Grant) IncreaseCounter() error {
  347. return grant.increaseCount(x)
  348. }
  349. func (grant *OAuth2Grant) increaseCount(e Engine) error {
  350. _, err := e.ID(grant.ID).Incr("counter").Update(new(OAuth2Grant))
  351. if err != nil {
  352. return err
  353. }
  354. updatedGrant, err := getOAuth2GrantByID(e, grant.ID)
  355. if err != nil {
  356. return err
  357. }
  358. grant.Counter = updatedGrant.Counter
  359. return nil
  360. }
  361. // GetOAuth2GrantByID returns the grant with the given ID
  362. func GetOAuth2GrantByID(id int64) (*OAuth2Grant, error) {
  363. return getOAuth2GrantByID(x, id)
  364. }
  365. func getOAuth2GrantByID(e Engine, id int64) (grant *OAuth2Grant, err error) {
  366. grant = new(OAuth2Grant)
  367. if has, err := e.ID(id).Get(grant); err != nil {
  368. return nil, err
  369. } else if !has {
  370. return nil, nil
  371. }
  372. return
  373. }
  374. // GetOAuth2GrantsByUserID lists all grants of a certain user
  375. func GetOAuth2GrantsByUserID(uid int64) ([]*OAuth2Grant, error) {
  376. return getOAuth2GrantsByUserID(x, uid)
  377. }
  378. func getOAuth2GrantsByUserID(e Engine, uid int64) ([]*OAuth2Grant, error) {
  379. type joinedOAuth2Grant struct {
  380. Grant *OAuth2Grant `xorm:"extends"`
  381. Application *OAuth2Application `xorm:"extends"`
  382. }
  383. var results *xorm.Rows
  384. var err error
  385. if results, err = e.
  386. Table("oauth2_grant").
  387. Where("user_id = ?", uid).
  388. Join("INNER", "oauth2_application", "application_id = oauth2_application.id").
  389. Rows(new(joinedOAuth2Grant)); err != nil {
  390. return nil, err
  391. }
  392. defer results.Close()
  393. grants := make([]*OAuth2Grant, 0)
  394. for results.Next() {
  395. joinedGrant := new(joinedOAuth2Grant)
  396. if err := results.Scan(joinedGrant); err != nil {
  397. return nil, err
  398. }
  399. joinedGrant.Grant.Application = joinedGrant.Application
  400. grants = append(grants, joinedGrant.Grant)
  401. }
  402. return grants, nil
  403. }
  404. // RevokeOAuth2Grant deletes the grant with grantID and userID
  405. func RevokeOAuth2Grant(grantID, userID int64) error {
  406. return revokeOAuth2Grant(x, grantID, userID)
  407. }
  408. func revokeOAuth2Grant(e Engine, grantID, userID int64) error {
  409. _, err := e.Delete(&OAuth2Grant{ID: grantID, UserID: userID})
  410. return err
  411. }
  412. //////////////////////////////////////////////////////////////
  413. // OAuth2TokenType represents the type of token for an oauth application
  414. type OAuth2TokenType int
  415. const (
  416. // TypeAccessToken is a token with short lifetime to access the api
  417. TypeAccessToken OAuth2TokenType = 0
  418. // TypeRefreshToken is token with long lifetime to refresh access tokens obtained by the client
  419. TypeRefreshToken = iota
  420. )
  421. // OAuth2Token represents a JWT token used to authenticate a client
  422. type OAuth2Token struct {
  423. GrantID int64 `json:"gnt"`
  424. Type OAuth2TokenType `json:"tt"`
  425. Counter int64 `json:"cnt,omitempty"`
  426. jwt.StandardClaims
  427. }
  428. // ParseOAuth2Token parses a singed jwt string
  429. func ParseOAuth2Token(jwtToken string) (*OAuth2Token, error) {
  430. parsedToken, err := jwt.ParseWithClaims(jwtToken, &OAuth2Token{}, func(token *jwt.Token) (interface{}, error) {
  431. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  432. return nil, fmt.Errorf("unexpected signing algo: %v", token.Header["alg"])
  433. }
  434. return setting.OAuth2.JWTSecretBytes, nil
  435. })
  436. if err != nil {
  437. return nil, err
  438. }
  439. var token *OAuth2Token
  440. var ok bool
  441. if token, ok = parsedToken.Claims.(*OAuth2Token); !ok || !parsedToken.Valid {
  442. return nil, fmt.Errorf("invalid token")
  443. }
  444. return token, nil
  445. }
  446. // SignToken signs the token with the JWT secret
  447. func (token *OAuth2Token) SignToken() (string, error) {
  448. token.IssuedAt = time.Now().Unix()
  449. jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS512, token)
  450. return jwtToken.SignedString(setting.OAuth2.JWTSecretBytes)
  451. }