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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  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 fmt.Errorf("cannot find oauth2 application")
  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. if err := sess.Begin(); err != nil {
  226. return err
  227. }
  228. if err := deleteOAuth2Application(sess, id, userid); err != nil {
  229. return err
  230. }
  231. return sess.Commit()
  232. }
  233. // ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
  234. func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, error) {
  235. sess := x.
  236. Where("uid=?", uid).
  237. Desc("id")
  238. if listOptions.Page != 0 {
  239. sess = listOptions.setSessionPagination(sess)
  240. apps := make([]*OAuth2Application, 0, listOptions.PageSize)
  241. return apps, sess.Find(&apps)
  242. }
  243. apps := make([]*OAuth2Application, 0, 5)
  244. return apps, sess.Find(&apps)
  245. }
  246. //////////////////////////////////////////////////////
  247. // OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.
  248. type OAuth2AuthorizationCode struct {
  249. ID int64 `xorm:"pk autoincr"`
  250. Grant *OAuth2Grant `xorm:"-"`
  251. GrantID int64
  252. Code string `xorm:"INDEX unique"`
  253. CodeChallenge string
  254. CodeChallengeMethod string
  255. RedirectURI string
  256. ValidUntil timeutil.TimeStamp `xorm:"index"`
  257. }
  258. // TableName sets the table name to `oauth2_authorization_code`
  259. func (code *OAuth2AuthorizationCode) TableName() string {
  260. return "oauth2_authorization_code"
  261. }
  262. // GenerateRedirectURI generates a redirect URI for a successful authorization request. State will be used if not empty.
  263. func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect *url.URL, err error) {
  264. if redirect, err = url.Parse(code.RedirectURI); err != nil {
  265. return
  266. }
  267. q := redirect.Query()
  268. if state != "" {
  269. q.Set("state", state)
  270. }
  271. q.Set("code", code.Code)
  272. redirect.RawQuery = q.Encode()
  273. return
  274. }
  275. // Invalidate deletes the auth code from the database to invalidate this code
  276. func (code *OAuth2AuthorizationCode) Invalidate() error {
  277. return code.invalidate(x)
  278. }
  279. func (code *OAuth2AuthorizationCode) invalidate(e Engine) error {
  280. _, err := e.Delete(code)
  281. return err
  282. }
  283. // ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation.
  284. func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool {
  285. return code.validateCodeChallenge(verifier)
  286. }
  287. func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool {
  288. switch code.CodeChallengeMethod {
  289. case "S256":
  290. // base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6
  291. h := sha256.Sum256([]byte(verifier))
  292. hashedVerifier := base64.RawURLEncoding.EncodeToString(h[:])
  293. return hashedVerifier == code.CodeChallenge
  294. case "plain":
  295. return verifier == code.CodeChallenge
  296. case "":
  297. return true
  298. default:
  299. // unsupported method -> return false
  300. return false
  301. }
  302. }
  303. // GetOAuth2AuthorizationByCode returns an authorization by its code
  304. func GetOAuth2AuthorizationByCode(code string) (*OAuth2AuthorizationCode, error) {
  305. return getOAuth2AuthorizationByCode(x, code)
  306. }
  307. func getOAuth2AuthorizationByCode(e Engine, code string) (auth *OAuth2AuthorizationCode, err error) {
  308. auth = new(OAuth2AuthorizationCode)
  309. if has, err := e.Where("code = ?", code).Get(auth); err != nil {
  310. return nil, err
  311. } else if !has {
  312. return nil, nil
  313. }
  314. auth.Grant = new(OAuth2Grant)
  315. if has, err := e.ID(auth.GrantID).Get(auth.Grant); err != nil {
  316. return nil, err
  317. } else if !has {
  318. return nil, nil
  319. }
  320. return auth, nil
  321. }
  322. //////////////////////////////////////////////////////
  323. // OAuth2Grant represents the permission of an user for a specifc application to access resources
  324. type OAuth2Grant struct {
  325. ID int64 `xorm:"pk autoincr"`
  326. UserID int64 `xorm:"INDEX unique(user_application)"`
  327. Application *OAuth2Application `xorm:"-"`
  328. ApplicationID int64 `xorm:"INDEX unique(user_application)"`
  329. Counter int64 `xorm:"NOT NULL DEFAULT 1"`
  330. Scope string `xorm:"TEXT"`
  331. Nonce string `xorm:"TEXT"`
  332. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  333. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  334. }
  335. // TableName sets the table name to `oauth2_grant`
  336. func (grant *OAuth2Grant) TableName() string {
  337. return "oauth2_grant"
  338. }
  339. // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the databse
  340. func (grant *OAuth2Grant) GenerateNewAuthorizationCode(redirectURI, codeChallenge, codeChallengeMethod string) (*OAuth2AuthorizationCode, error) {
  341. return grant.generateNewAuthorizationCode(x, redirectURI, codeChallenge, codeChallengeMethod)
  342. }
  343. func (grant *OAuth2Grant) generateNewAuthorizationCode(e Engine, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
  344. var codeSecret string
  345. if codeSecret, err = secret.New(); err != nil {
  346. return &OAuth2AuthorizationCode{}, err
  347. }
  348. code = &OAuth2AuthorizationCode{
  349. Grant: grant,
  350. GrantID: grant.ID,
  351. RedirectURI: redirectURI,
  352. Code: codeSecret,
  353. CodeChallenge: codeChallenge,
  354. CodeChallengeMethod: codeChallengeMethod,
  355. }
  356. if _, err := e.Insert(code); err != nil {
  357. return nil, err
  358. }
  359. return code, nil
  360. }
  361. // IncreaseCounter increases the counter and updates the grant
  362. func (grant *OAuth2Grant) IncreaseCounter() error {
  363. return grant.increaseCount(x)
  364. }
  365. func (grant *OAuth2Grant) increaseCount(e Engine) error {
  366. _, err := e.ID(grant.ID).Incr("counter").Update(new(OAuth2Grant))
  367. if err != nil {
  368. return err
  369. }
  370. updatedGrant, err := getOAuth2GrantByID(e, grant.ID)
  371. if err != nil {
  372. return err
  373. }
  374. grant.Counter = updatedGrant.Counter
  375. return nil
  376. }
  377. // ScopeContains returns true if the grant scope contains the specified scope
  378. func (grant *OAuth2Grant) ScopeContains(scope string) bool {
  379. for _, currentScope := range strings.Split(grant.Scope, " ") {
  380. if scope == currentScope {
  381. return true
  382. }
  383. }
  384. return false
  385. }
  386. // SetNonce updates the current nonce value of a grant
  387. func (grant *OAuth2Grant) SetNonce(nonce string) error {
  388. return grant.setNonce(x, nonce)
  389. }
  390. func (grant *OAuth2Grant) setNonce(e Engine, nonce string) error {
  391. grant.Nonce = nonce
  392. _, err := e.ID(grant.ID).Cols("nonce").Update(grant)
  393. if err != nil {
  394. return err
  395. }
  396. return nil
  397. }
  398. // GetOAuth2GrantByID returns the grant with the given ID
  399. func GetOAuth2GrantByID(id int64) (*OAuth2Grant, error) {
  400. return getOAuth2GrantByID(x, id)
  401. }
  402. func getOAuth2GrantByID(e Engine, id int64) (grant *OAuth2Grant, err error) {
  403. grant = new(OAuth2Grant)
  404. if has, err := e.ID(id).Get(grant); err != nil {
  405. return nil, err
  406. } else if !has {
  407. return nil, nil
  408. }
  409. return
  410. }
  411. // GetOAuth2GrantsByUserID lists all grants of a certain user
  412. func GetOAuth2GrantsByUserID(uid int64) ([]*OAuth2Grant, error) {
  413. return getOAuth2GrantsByUserID(x, uid)
  414. }
  415. func getOAuth2GrantsByUserID(e Engine, uid int64) ([]*OAuth2Grant, error) {
  416. type joinedOAuth2Grant struct {
  417. Grant *OAuth2Grant `xorm:"extends"`
  418. Application *OAuth2Application `xorm:"extends"`
  419. }
  420. var results *xorm.Rows
  421. var err error
  422. if results, err = e.
  423. Table("oauth2_grant").
  424. Where("user_id = ?", uid).
  425. Join("INNER", "oauth2_application", "application_id = oauth2_application.id").
  426. Rows(new(joinedOAuth2Grant)); err != nil {
  427. return nil, err
  428. }
  429. defer results.Close()
  430. grants := make([]*OAuth2Grant, 0)
  431. for results.Next() {
  432. joinedGrant := new(joinedOAuth2Grant)
  433. if err := results.Scan(joinedGrant); err != nil {
  434. return nil, err
  435. }
  436. joinedGrant.Grant.Application = joinedGrant.Application
  437. grants = append(grants, joinedGrant.Grant)
  438. }
  439. return grants, nil
  440. }
  441. // RevokeOAuth2Grant deletes the grant with grantID and userID
  442. func RevokeOAuth2Grant(grantID, userID int64) error {
  443. return revokeOAuth2Grant(x, grantID, userID)
  444. }
  445. func revokeOAuth2Grant(e Engine, grantID, userID int64) error {
  446. _, err := e.Delete(&OAuth2Grant{ID: grantID, UserID: userID})
  447. return err
  448. }
  449. //////////////////////////////////////////////////////////////
  450. // OAuth2TokenType represents the type of token for an oauth application
  451. type OAuth2TokenType int
  452. const (
  453. // TypeAccessToken is a token with short lifetime to access the api
  454. TypeAccessToken OAuth2TokenType = 0
  455. // TypeRefreshToken is token with long lifetime to refresh access tokens obtained by the client
  456. TypeRefreshToken = iota
  457. )
  458. // OAuth2Token represents a JWT token used to authenticate a client
  459. type OAuth2Token struct {
  460. GrantID int64 `json:"gnt"`
  461. Type OAuth2TokenType `json:"tt"`
  462. Counter int64 `json:"cnt,omitempty"`
  463. jwt.StandardClaims
  464. }
  465. // ParseOAuth2Token parses a singed jwt string
  466. func ParseOAuth2Token(jwtToken string) (*OAuth2Token, error) {
  467. parsedToken, err := jwt.ParseWithClaims(jwtToken, &OAuth2Token{}, func(token *jwt.Token) (interface{}, error) {
  468. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  469. return nil, fmt.Errorf("unexpected signing algo: %v", token.Header["alg"])
  470. }
  471. return setting.OAuth2.JWTSecretBytes, nil
  472. })
  473. if err != nil {
  474. return nil, err
  475. }
  476. var token *OAuth2Token
  477. var ok bool
  478. if token, ok = parsedToken.Claims.(*OAuth2Token); !ok || !parsedToken.Valid {
  479. return nil, fmt.Errorf("invalid token")
  480. }
  481. return token, nil
  482. }
  483. // SignToken signs the token with the JWT secret
  484. func (token *OAuth2Token) SignToken() (string, error) {
  485. token.IssuedAt = time.Now().Unix()
  486. jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS512, token)
  487. return jwtToken.SignedString(setting.OAuth2.JWTSecretBytes)
  488. }
  489. // OIDCToken represents an OpenID Connect id_token
  490. type OIDCToken struct {
  491. jwt.StandardClaims
  492. Nonce string `json:"nonce,omitempty"`
  493. }
  494. // SignToken signs an id_token with the (symmetric) client secret key
  495. func (token *OIDCToken) SignToken(clientSecret string) (string, error) {
  496. token.IssuedAt = time.Now().Unix()
  497. jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS256, token)
  498. return jwtToken.SignedString([]byte(clientSecret))
  499. }