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 17KB

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