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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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. "code.gitea.io/gitea/modules/secret"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. uuid "github.com/google/uuid"
  15. "golang.org/x/crypto/bcrypt"
  16. "xorm.io/xorm"
  17. )
  18. // OAuth2Application represents an OAuth2 client (RFC 6749)
  19. type OAuth2Application struct {
  20. ID int64 `xorm:"pk autoincr"`
  21. UID int64 `xorm:"INDEX"`
  22. User *User `xorm:"-"`
  23. Name string
  24. ClientID string `xorm:"unique"`
  25. ClientSecret string
  26. RedirectURIs []string `xorm:"redirect_uris JSON TEXT"`
  27. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  28. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  29. }
  30. // TableName sets the table name to `oauth2_application`
  31. func (app *OAuth2Application) TableName() string {
  32. return "oauth2_application"
  33. }
  34. // PrimaryRedirectURI returns the first redirect uri or an empty string if empty
  35. func (app *OAuth2Application) PrimaryRedirectURI() string {
  36. if len(app.RedirectURIs) == 0 {
  37. return ""
  38. }
  39. return app.RedirectURIs[0]
  40. }
  41. // LoadUser will load User by UID
  42. func (app *OAuth2Application) LoadUser() (err error) {
  43. if app.User == nil {
  44. app.User, err = GetUserByID(app.UID)
  45. }
  46. return
  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. // GenerateClientSecret will generate the client secret and returns the plaintext and saves the hash at the database
  53. func (app *OAuth2Application) GenerateClientSecret() (string, error) {
  54. clientSecret, err := secret.New()
  55. if err != nil {
  56. return "", err
  57. }
  58. hashedSecret, err := bcrypt.GenerateFromPassword([]byte(clientSecret), bcrypt.DefaultCost)
  59. if err != nil {
  60. return "", err
  61. }
  62. app.ClientSecret = string(hashedSecret)
  63. if _, err := x.ID(app.ID).Cols("client_secret").Update(app); err != nil {
  64. return "", err
  65. }
  66. return clientSecret, nil
  67. }
  68. // ValidateClientSecret validates the given secret by the hash saved in database
  69. func (app *OAuth2Application) ValidateClientSecret(secret []byte) bool {
  70. return bcrypt.CompareHashAndPassword([]byte(app.ClientSecret), secret) == nil
  71. }
  72. // GetGrantByUserID returns a OAuth2Grant by its user and application ID
  73. func (app *OAuth2Application) GetGrantByUserID(userID int64) (*OAuth2Grant, error) {
  74. return app.getGrantByUserID(x, userID)
  75. }
  76. func (app *OAuth2Application) getGrantByUserID(e Engine, userID int64) (grant *OAuth2Grant, err error) {
  77. grant = new(OAuth2Grant)
  78. if has, err := e.Where("user_id = ? AND application_id = ?", userID, app.ID).Get(grant); err != nil {
  79. return nil, err
  80. } else if !has {
  81. return nil, nil
  82. }
  83. return grant, nil
  84. }
  85. // CreateGrant generates a grant for an user
  86. func (app *OAuth2Application) CreateGrant(userID int64, scope string) (*OAuth2Grant, error) {
  87. return app.createGrant(x, userID, scope)
  88. }
  89. func (app *OAuth2Application) createGrant(e Engine, userID int64, scope string) (*OAuth2Grant, error) {
  90. grant := &OAuth2Grant{
  91. ApplicationID: app.ID,
  92. UserID: userID,
  93. Scope: scope,
  94. }
  95. _, err := e.Insert(grant)
  96. if err != nil {
  97. return nil, err
  98. }
  99. return grant, nil
  100. }
  101. // GetOAuth2ApplicationByClientID returns the oauth2 application with the given client_id. Returns an error if not found.
  102. func GetOAuth2ApplicationByClientID(clientID string) (app *OAuth2Application, err error) {
  103. return getOAuth2ApplicationByClientID(x, clientID)
  104. }
  105. func getOAuth2ApplicationByClientID(e Engine, clientID string) (app *OAuth2Application, err error) {
  106. app = new(OAuth2Application)
  107. has, err := e.Where("client_id = ?", clientID).Get(app)
  108. if !has {
  109. return nil, ErrOAuthClientIDInvalid{ClientID: clientID}
  110. }
  111. return
  112. }
  113. // GetOAuth2ApplicationByID returns the oauth2 application with the given id. Returns an error if not found.
  114. func GetOAuth2ApplicationByID(id int64) (app *OAuth2Application, err error) {
  115. return getOAuth2ApplicationByID(x, id)
  116. }
  117. func getOAuth2ApplicationByID(e Engine, id int64) (app *OAuth2Application, err error) {
  118. app = new(OAuth2Application)
  119. has, err := e.ID(id).Get(app)
  120. if err != nil {
  121. return nil, err
  122. }
  123. if !has {
  124. return nil, ErrOAuthApplicationNotFound{ID: id}
  125. }
  126. return app, nil
  127. }
  128. // GetOAuth2ApplicationsByUserID returns all oauth2 applications owned by the user
  129. func GetOAuth2ApplicationsByUserID(userID int64) (apps []*OAuth2Application, err error) {
  130. return getOAuth2ApplicationsByUserID(x, userID)
  131. }
  132. func getOAuth2ApplicationsByUserID(e Engine, userID int64) (apps []*OAuth2Application, err error) {
  133. apps = make([]*OAuth2Application, 0)
  134. err = e.Where("uid = ?", userID).Find(&apps)
  135. return
  136. }
  137. // CreateOAuth2ApplicationOptions holds options to create an oauth2 application
  138. type CreateOAuth2ApplicationOptions struct {
  139. Name string
  140. UserID int64
  141. RedirectURIs []string
  142. }
  143. // CreateOAuth2Application inserts a new oauth2 application
  144. func CreateOAuth2Application(opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  145. return createOAuth2Application(x, opts)
  146. }
  147. func createOAuth2Application(e Engine, opts CreateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  148. clientID := uuid.New().String()
  149. app := &OAuth2Application{
  150. UID: opts.UserID,
  151. Name: opts.Name,
  152. ClientID: clientID,
  153. RedirectURIs: opts.RedirectURIs,
  154. }
  155. if _, err := e.Insert(app); err != nil {
  156. return nil, err
  157. }
  158. return app, nil
  159. }
  160. // UpdateOAuth2ApplicationOptions holds options to update an oauth2 application
  161. type UpdateOAuth2ApplicationOptions struct {
  162. ID int64
  163. Name string
  164. UserID int64
  165. RedirectURIs []string
  166. }
  167. // UpdateOAuth2Application updates an oauth2 application
  168. func UpdateOAuth2Application(opts UpdateOAuth2ApplicationOptions) (*OAuth2Application, error) {
  169. sess := x.NewSession()
  170. if err := sess.Begin(); err != nil {
  171. return nil, err
  172. }
  173. defer sess.Close()
  174. app, err := getOAuth2ApplicationByID(sess, opts.ID)
  175. if err != nil {
  176. return nil, err
  177. }
  178. if app.UID != opts.UserID {
  179. return nil, fmt.Errorf("UID mismatch")
  180. }
  181. app.Name = opts.Name
  182. app.RedirectURIs = opts.RedirectURIs
  183. if err = updateOAuth2Application(sess, app); err != nil {
  184. return nil, err
  185. }
  186. app.ClientSecret = ""
  187. return app, sess.Commit()
  188. }
  189. func updateOAuth2Application(e Engine, app *OAuth2Application) error {
  190. if _, err := e.ID(app.ID).Update(app); err != nil {
  191. return err
  192. }
  193. return nil
  194. }
  195. func deleteOAuth2Application(sess *xorm.Session, id, userid int64) error {
  196. if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil {
  197. return err
  198. } else if deleted == 0 {
  199. return ErrOAuthApplicationNotFound{ID: id}
  200. }
  201. codes := make([]*OAuth2AuthorizationCode, 0)
  202. // delete correlating auth codes
  203. if err := sess.Join("INNER", "oauth2_grant",
  204. "oauth2_authorization_code.grant_id = oauth2_grant.id AND oauth2_grant.application_id = ?", id).Find(&codes); err != nil {
  205. return err
  206. }
  207. codeIDs := make([]int64, 0)
  208. for _, grant := range codes {
  209. codeIDs = append(codeIDs, grant.ID)
  210. }
  211. if _, err := sess.In("id", codeIDs).Delete(new(OAuth2AuthorizationCode)); err != nil {
  212. return err
  213. }
  214. if _, err := sess.Where("application_id = ?", id).Delete(new(OAuth2Grant)); err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. // 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.
  220. func DeleteOAuth2Application(id, userid int64) error {
  221. sess := x.NewSession()
  222. defer sess.Close()
  223. if err := sess.Begin(); err != nil {
  224. return err
  225. }
  226. if err := deleteOAuth2Application(sess, id, userid); err != nil {
  227. return err
  228. }
  229. return sess.Commit()
  230. }
  231. // ListOAuth2Applications returns a list of oauth2 applications belongs to given user.
  232. func ListOAuth2Applications(uid int64, listOptions ListOptions) ([]*OAuth2Application, int64, error) {
  233. sess := x.
  234. Where("uid=?", uid).
  235. Desc("id")
  236. if listOptions.Page != 0 {
  237. sess = listOptions.setSessionPagination(sess)
  238. apps := make([]*OAuth2Application, 0, listOptions.PageSize)
  239. total, err := sess.FindAndCount(&apps)
  240. return apps, total, err
  241. }
  242. apps := make([]*OAuth2Application, 0, 5)
  243. total, err := sess.FindAndCount(&apps)
  244. return apps, total, err
  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 specific 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 database
  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. }