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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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 auth
  5. import (
  6. "context"
  7. "crypto/sha256"
  8. "encoding/base32"
  9. "encoding/base64"
  10. "fmt"
  11. "net/url"
  12. "strings"
  13. "code.gitea.io/gitea/models/db"
  14. "code.gitea.io/gitea/modules/timeutil"
  15. "code.gitea.io/gitea/modules/util"
  16. uuid "github.com/google/uuid"
  17. "golang.org/x/crypto/bcrypt"
  18. "xorm.io/builder"
  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. 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. func init() {
  33. db.RegisterModel(new(OAuth2Application))
  34. db.RegisterModel(new(OAuth2AuthorizationCode))
  35. db.RegisterModel(new(OAuth2Grant))
  36. }
  37. // TableName sets the table name to `oauth2_application`
  38. func (app *OAuth2Application) TableName() string {
  39. return "oauth2_application"
  40. }
  41. // PrimaryRedirectURI returns the first redirect uri or an empty string if empty
  42. func (app *OAuth2Application) PrimaryRedirectURI() string {
  43. if len(app.RedirectURIs) == 0 {
  44. return ""
  45. }
  46. return app.RedirectURIs[0]
  47. }
  48. // ContainsRedirectURI checks if redirectURI is allowed for app
  49. func (app *OAuth2Application) ContainsRedirectURI(redirectURI string) bool {
  50. return util.IsStringInSlice(redirectURI, app.RedirectURIs, true)
  51. }
  52. // Base32 characters, but lowercased.
  53. const lowerBase32Chars = "abcdefghijklmnopqrstuvwxyz234567"
  54. // base32 encoder that uses lowered characters without padding.
  55. var base32Lower = base32.NewEncoding(lowerBase32Chars).WithPadding(base32.NoPadding)
  56. // GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
  57. func (app *OAuth2Application) GenerateClientSecret() (string, error) {
  58. rBytes, err := util.CryptoRandomBytes(32)
  59. if err != nil {
  60. return "", err
  61. }
  62. // Add a prefix to the base32, this is in order to make it easier
  63. // for code scanners to grab sensitive tokens.
  64. clientSecret := "gto_" + base32Lower.EncodeToString(rBytes)
  65. hashedSecret, err := bcrypt.GenerateFromPassword([]byte(clientSecret), bcrypt.DefaultCost)
  66. if err != nil {
  67. return "", err
  68. }
  69. app.ClientSecret = string(hashedSecret)
  70. if _, err := db.GetEngine(db.DefaultContext).ID(app.ID).Cols("client_secret").Update(app); err != nil {
  71. return "", err
  72. }
  73. return clientSecret, nil
  74. }
  75. // ValidateClientSecret validates the given secret by the hash saved in database
  76. func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool {
  77. return bcrypt.CompareHashAndPassword([]byte(app.ClientSecret), secret) == nil
  78. }
  79. // GetGrantByUserID returns a OAuth2Grant by its user and application ID
  80. func (app *OAuth2Application) GetGrantByUserID(ctx context.Context, userID int64) (grant *OAuth2Grant, err error) {
  81. grant = new(OAuth2Grant)
  82. if has, err := db.GetEngine(ctx).Where("user_id = ? AND application_id = ?", userID, app.ID).Get(grant); err != nil {
  83. return nil, err
  84. } else if !has {
  85. return nil, nil
  86. }
  87. return grant, nil
  88. }
  89. // CreateGrant generates a grant for an user
  90. func (app *OAuth2Application) CreateGrant(ctx context.Context, userID int64, scope string) (*OAuth2Grant, error) {
  91. grant := &OAuth2Grant{
  92. ApplicationID: app.ID,
  93. UserID: userID,
  94. Scope: scope,
  95. }
  96. err := db.Insert(ctx, 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(ctx context.Context, clientID string) (app *OAuth2Application, err error) {
  104. app = new(OAuth2Application)
  105. has, err := db.GetEngine(ctx).Where("client_id = ?", clientID).Get(app)
  106. if !has {
  107. return nil, ErrOAuthClientIDInvalid{ClientID: clientID}
  108. }
  109. return
  110. }
  111. // GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
  112. func GetOAuth2ApplicationByID(ctx context.Context, id int64) (app *OAuth2Application, err error) {
  113. app = new(OAuth2Application)
  114. has, err := db.GetEngine(ctx).ID(id).Get(app)
  115. if err != nil {
  116. return nil, err
  117. }
  118. if !has {
  119. return nil, ErrOAuthApplicationNotFound{ID: id}
  120. }
  121. return app, nil
  122. }
  123. // GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user
  124. func GetOAuth2ApplicationsByUserID(ctx context.Context, userID int64) (apps []*OAuth2Application, err error) {
  125. apps = make([]*OAuth2Application, 0)
  126. err = db.GetEngine(ctx).Where("uid = ?", userID).Find(&apps)
  127. return
  128. }
  129. // CreateOAuth2ApplicationOptions holds options to create an oauth2 application
  130. type CreateOAuth2ApplicationOptions struct {
  131. Name string
  132. UserID int64
  133. RedirectURIs []string
  134. }
  135. // CreateOAuth2Application inserts a new oauth2 application
  136. func CreateOAuth2Application(ctx context.Context, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  137. clientID := uuid.New().String()
  138. app := &OAuth2Application{
  139. UID: opts.UserID,
  140. Name: opts.Name,
  141. ClientID: clientID,
  142. RedirectURIs: opts.RedirectURIs,
  143. }
  144. if err := db.Insert(ctx, app); err != nil {
  145. return nil, err
  146. }
  147. return app, nil
  148. }
  149. // UpdateOAuth2ApplicationOptions holds options to update an oauth2 application
  150. type UpdateOAuth2ApplicationOptions struct {
  151. ID int64
  152. Name string
  153. UserID int64
  154. RedirectURIs []string
  155. }
  156. // UpdateOAuth2Application updates an oauth2 application
  157. func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  158. ctx, committer, err := db.TxContext()
  159. if err != nil {
  160. return nil, err
  161. }
  162. defer committer.Close()
  163. app, err := GetOAuth2ApplicationByID(ctx, opts.ID)
  164. if err != nil {
  165. return nil, err
  166. }
  167. if app.UID != opts.UserID {
  168. return nil, fmt.Errorf("UID mismatch")
  169. }
  170. app.Name = opts.Name
  171. app.RedirectURIs = opts.RedirectURIs
  172. if err = updateOAuth2Application(ctx, app); err != nil {
  173. return nil, err
  174. }
  175. app.ClientSecret = ""
  176. return app, committer.Commit()
  177. }
  178. func updateOAuth2Application(ctx context.Context, app *OAuth2Application) error {
  179. if _, err := db.GetEngine(ctx).ID(app.ID).Update(app); err != nil {
  180. return err
  181. }
  182. return nil
  183. }
  184. func deleteOAuth2Application(ctx context.Context, id, userid int64) error {
  185. sess := db.GetEngine(ctx)
  186. if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil {
  187. return err
  188. } else if deleted == 0 {
  189. return ErrOAuthApplicationNotFound{ID: id}
  190. }
  191. codes := make([]*OAuth2AuthorizationCode, 0)
  192. // delete correlating auth codes
  193. if err := sess.Join("INNER", "oauth2_grant",
  194. "oauth2_authorization_code.grant_id = oauth2_grant.id AND oauth2_grant.application_id = ?", id).Find(&codes); err != nil {
  195. return err
  196. }
  197. codeIDs := make([]int64, 0, len(codes))
  198. for _, grant := range codes {
  199. codeIDs = append(codeIDs, grant.ID)
  200. }
  201. if _, err := sess.In("id", codeIDs).Delete(new(OAuth2AuthorizationCode)); err != nil {
  202. return err
  203. }
  204. if _, err := sess.Where("application_id = ?", id).Delete(new(OAuth2Grant)); err != nil {
  205. return err
  206. }
  207. return nil
  208. }
  209. // 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.
  210. func DeleteOAuth2Application(id, userid int64) error {
  211. ctx, committer, err := db.TxContext()
  212. if err != nil {
  213. return err
  214. }
  215. defer committer.Close()
  216. if err := deleteOAuth2Application(ctx, id, userid); err != nil {
  217. return err
  218. }
  219. return committer.Commit()
  220. }
  221. // ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
  222. func ListOAuth2Applications(uid int64, listOptions db.ListOptions) ([]*OAuth2Application, int64, error) {
  223. sess := db.GetEngine(db.DefaultContext).
  224. Where("uid=?", uid).
  225. Desc("id")
  226. if listOptions.Page != 0 {
  227. sess = db.SetSessionPagination(sess, &listOptions)
  228. apps := make([]*OAuth2Application, 0, listOptions.PageSize)
  229. total, err := sess.FindAndCount(&apps)
  230. return apps, total, err
  231. }
  232. apps := make([]*OAuth2Application, 0, 5)
  233. total, err := sess.FindAndCount(&apps)
  234. return apps, total, err
  235. }
  236. //////////////////////////////////////////////////////
  237. // OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.
  238. type OAuth2AuthorizationCode struct {
  239. ID int64 `xorm:"pk autoincr"`
  240. Grant *OAuth2Grant `xorm:"-"`
  241. GrantID int64
  242. Code string `xorm:"INDEX unique"`
  243. CodeChallenge string
  244. CodeChallengeMethod string
  245. RedirectURI string
  246. ValidUntil timeutil.TimeStamp `xorm:"index"`
  247. }
  248. // TableName sets the table name to `oauth2_authorization_code`
  249. func (code *OAuth2AuthorizationCode) TableName() string {
  250. return "oauth2_authorization_code"
  251. }
  252. // GenerateRedirectURI generates a redirect URI for a successful authorization request. State will be used if not empty.
  253. func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect *url.URL, err error) {
  254. if redirect, err = url.Parse(code.RedirectURI); err != nil {
  255. return
  256. }
  257. q := redirect.Query()
  258. if state != "" {
  259. q.Set("state", state)
  260. }
  261. q.Set("code", code.Code)
  262. redirect.RawQuery = q.Encode()
  263. return
  264. }
  265. // Invalidate deletes the auth code from the database to invalidate this code
  266. func (code *OAuth2AuthorizationCode) Invalidate(ctx context.Context) error {
  267. _, err := db.GetEngine(ctx).ID(code.ID).NoAutoCondition().Delete(code)
  268. return err
  269. }
  270. // ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation.
  271. func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool {
  272. switch code.CodeChallengeMethod {
  273. case "S256":
  274. // base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6
  275. h := sha256.Sum256([]byte(verifier))
  276. hashedVerifier := base64.RawURLEncoding.EncodeToString(h[:])
  277. return hashedVerifier == code.CodeChallenge
  278. case "plain":
  279. return verifier == code.CodeChallenge
  280. case "":
  281. return true
  282. default:
  283. // unsupported method -> return false
  284. return false
  285. }
  286. }
  287. // GetOAuth2AuthorizationByCode returns an authorization by its code
  288. func GetOAuth2AuthorizationByCode(ctx context.Context, code string) (auth *OAuth2AuthorizationCode, err error) {
  289. auth = new(OAuth2AuthorizationCode)
  290. if has, err := db.GetEngine(ctx).Where("code = ?", code).Get(auth); err != nil {
  291. return nil, err
  292. } else if !has {
  293. return nil, nil
  294. }
  295. auth.Grant = new(OAuth2Grant)
  296. if has, err := db.GetEngine(ctx).ID(auth.GrantID).Get(auth.Grant); err != nil {
  297. return nil, err
  298. } else if !has {
  299. return nil, nil
  300. }
  301. return auth, nil
  302. }
  303. //////////////////////////////////////////////////////
  304. // OAuth2Grant represents the permission of an user for a specific application to access resources
  305. type OAuth2Grant struct {
  306. ID int64 `xorm:"pk autoincr"`
  307. UserID int64 `xorm:"INDEX unique(user_application)"`
  308. Application *OAuth2Application `xorm:"-"`
  309. ApplicationID int64 `xorm:"INDEX unique(user_application)"`
  310. Counter int64 `xorm:"NOT NULL DEFAULT 1"`
  311. Scope string `xorm:"TEXT"`
  312. Nonce string `xorm:"TEXT"`
  313. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  314. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  315. }
  316. // TableName sets the table name to `oauth2_grant`
  317. func (grant *OAuth2Grant) TableName() string {
  318. return "oauth2_grant"
  319. }
  320. // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the database
  321. func (grant *OAuth2Grant) GenerateNewAuthorizationCode(ctx context.Context, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
  322. rBytes, err := util.CryptoRandomBytes(32)
  323. if err != nil {
  324. return &OAuth2AuthorizationCode{}, err
  325. }
  326. // Add a prefix to the base32, this is in order to make it easier
  327. // for code scanners to grab sensitive tokens.
  328. codeSecret := "gta_" + base32Lower.EncodeToString(rBytes)
  329. code = &OAuth2AuthorizationCode{
  330. Grant: grant,
  331. GrantID: grant.ID,
  332. RedirectURI: redirectURI,
  333. Code: codeSecret,
  334. CodeChallenge: codeChallenge,
  335. CodeChallengeMethod: codeChallengeMethod,
  336. }
  337. if err := db.Insert(ctx, code); err != nil {
  338. return nil, err
  339. }
  340. return code, nil
  341. }
  342. // IncreaseCounter increases the counter and updates the grant
  343. func (grant *OAuth2Grant) IncreaseCounter(ctx context.Context) error {
  344. _, err := db.GetEngine(ctx).ID(grant.ID).Incr("counter").Update(new(OAuth2Grant))
  345. if err != nil {
  346. return err
  347. }
  348. updatedGrant, err := GetOAuth2GrantByID(ctx, grant.ID)
  349. if err != nil {
  350. return err
  351. }
  352. grant.Counter = updatedGrant.Counter
  353. return nil
  354. }
  355. // ScopeContains returns true if the grant scope contains the specified scope
  356. func (grant *OAuth2Grant) ScopeContains(scope string) bool {
  357. for _, currentScope := range strings.Split(grant.Scope, " ") {
  358. if scope == currentScope {
  359. return true
  360. }
  361. }
  362. return false
  363. }
  364. // SetNonce updates the current nonce value of a grant
  365. func (grant *OAuth2Grant) SetNonce(ctx context.Context, nonce string) error {
  366. grant.Nonce = nonce
  367. _, err := db.GetEngine(ctx).ID(grant.ID).Cols("nonce").Update(grant)
  368. if err != nil {
  369. return err
  370. }
  371. return nil
  372. }
  373. // GetOAuth2GrantByID returns the grant with the given ID
  374. func GetOAuth2GrantByID(ctx context.Context, id int64) (grant *OAuth2Grant, err error) {
  375. grant = new(OAuth2Grant)
  376. if has, err := db.GetEngine(ctx).ID(id).Get(grant); err != nil {
  377. return nil, err
  378. } else if !has {
  379. return nil, nil
  380. }
  381. return
  382. }
  383. // GetOAuth2GrantsByUserID lists all grants of a certain user
  384. func GetOAuth2GrantsByUserID(ctx context.Context, uid int64) ([]*OAuth2Grant, error) {
  385. type joinedOAuth2Grant struct {
  386. Grant *OAuth2Grant `xorm:"extends"`
  387. Application *OAuth2Application `xorm:"extends"`
  388. }
  389. var results *xorm.Rows
  390. var err error
  391. if results, err = db.GetEngine(ctx).
  392. Table("oauth2_grant").
  393. Where("user_id = ?", uid).
  394. Join("INNER", "oauth2_application", "application_id = oauth2_application.id").
  395. Rows(new(joinedOAuth2Grant)); err != nil {
  396. return nil, err
  397. }
  398. defer results.Close()
  399. grants := make([]*OAuth2Grant, 0)
  400. for results.Next() {
  401. joinedGrant := new(joinedOAuth2Grant)
  402. if err := results.Scan(joinedGrant); err != nil {
  403. return nil, err
  404. }
  405. joinedGrant.Grant.Application = joinedGrant.Application
  406. grants = append(grants, joinedGrant.Grant)
  407. }
  408. return grants, nil
  409. }
  410. // RevokeOAuth2Grant deletes the grant with grantID and userID
  411. func RevokeOAuth2Grant(ctx context.Context, grantID, userID int64) error {
  412. _, err := db.DeleteByBean(ctx, &OAuth2Grant{ID: grantID, UserID: userID})
  413. return err
  414. }
  415. // ErrOAuthClientIDInvalid will be thrown if client id cannot be found
  416. type ErrOAuthClientIDInvalid struct {
  417. ClientID string
  418. }
  419. // IsErrOauthClientIDInvalid checks if an error is a ErrReviewNotExist.
  420. func IsErrOauthClientIDInvalid(err error) bool {
  421. _, ok := err.(ErrOAuthClientIDInvalid)
  422. return ok
  423. }
  424. // Error returns the error message
  425. func (err ErrOAuthClientIDInvalid) Error() string {
  426. return fmt.Sprintf("Client ID invalid [Client ID: %s]", err.ClientID)
  427. }
  428. // ErrOAuthApplicationNotFound will be thrown if id cannot be found
  429. type ErrOAuthApplicationNotFound struct {
  430. ID int64
  431. }
  432. // IsErrOAuthApplicationNotFound checks if an error is a ErrReviewNotExist.
  433. func IsErrOAuthApplicationNotFound(err error) bool {
  434. _, ok := err.(ErrOAuthApplicationNotFound)
  435. return ok
  436. }
  437. // Error returns the error message
  438. func (err ErrOAuthApplicationNotFound) Error() string {
  439. return fmt.Sprintf("OAuth application not found [ID: %d]", err.ID)
  440. }
  441. // GetActiveOAuth2ProviderSources returns all actived LoginOAuth2 sources
  442. func GetActiveOAuth2ProviderSources() ([]*Source, error) {
  443. sources := make([]*Source, 0, 1)
  444. if err := db.GetEngine(db.DefaultContext).Where("is_active = ? and type = ?", true, OAuth2).Find(&sources); err != nil {
  445. return nil, err
  446. }
  447. return sources, nil
  448. }
  449. // GetActiveOAuth2SourceByName returns a OAuth2 AuthSource based on the given name
  450. func GetActiveOAuth2SourceByName(name string) (*Source, error) {
  451. authSource := new(Source)
  452. has, err := db.GetEngine(db.DefaultContext).Where("name = ? and type = ? and is_active = ?", name, OAuth2, true).Get(authSource)
  453. if !has || err != nil {
  454. return nil, err
  455. }
  456. return authSource, nil
  457. }
  458. func DeleteOAuth2RelictsByUserID(ctx context.Context, userID int64) error {
  459. deleteCond := builder.Select("id").From("oauth2_grant").Where(builder.Eq{"oauth2_grant.user_id": userID})
  460. if _, err := db.GetEngine(ctx).In("grant_id", deleteCond).
  461. Delete(&OAuth2AuthorizationCode{}); err != nil {
  462. return err
  463. }
  464. if err := db.DeleteBeans(ctx,
  465. &OAuth2Application{UID: userID},
  466. &OAuth2Grant{UserID: userID},
  467. ); err != nil {
  468. return fmt.Errorf("DeleteBeans: %v", err)
  469. }
  470. return nil
  471. }