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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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/google/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.New().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) (*OAuth2Application, error) {
  170. sess := x.NewSession()
  171. if err := sess.Begin(); err != nil {
  172. return nil, err
  173. }
  174. defer sess.Close()
  175. app, err := getOAuth2ApplicationByID(sess, opts.ID)
  176. if err != nil {
  177. return nil, err
  178. }
  179. if app.UID != opts.UserID {
  180. return nil, fmt.Errorf("UID missmatch")
  181. }
  182. app.Name = opts.Name
  183. app.RedirectURIs = opts.RedirectURIs
  184. if err = updateOAuth2Application(sess, app); err != nil {
  185. return nil, err
  186. }
  187. app.ClientSecret = ""
  188. return app, sess.Commit()
  189. }
  190. func updateOAuth2Application(e Engine, app *OAuth2Application) error {
  191. if _, err := e.ID(app.ID).Update(app); err != nil {
  192. return err
  193. }
  194. return nil
  195. }
  196. func deleteOAuth2Application(sess *xorm.Session, id, userid int64) error {
  197. if deleted, err := sess.Delete(&OAuth2Application{ID: id, UID: userid}); err != nil {
  198. return err
  199. } else if deleted == 0 {
  200. return fmt.Errorf("cannot find oauth2 application")
  201. }
  202. codes := make([]*OAuth2AuthorizationCode, 0)
  203. // delete correlating auth codes
  204. if err := sess.Join("INNER", "oauth2_grant",
  205. "oauth2_authorization_code.grant_id = oauth2_grant.id AND oauth2_grant.application_id = ?", id).Find(&codes); err != nil {
  206. return err
  207. }
  208. codeIDs := make([]int64, 0)
  209. for _, grant := range codes {
  210. codeIDs = append(codeIDs, grant.ID)
  211. }
  212. if _, err := sess.In("id", codeIDs).Delete(new(OAuth2AuthorizationCode)); err != nil {
  213. return err
  214. }
  215. if _, err := sess.Where("application_id = ?", id).Delete(new(OAuth2Grant)); err != nil {
  216. return err
  217. }
  218. return nil
  219. }
  220. // 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.
  221. func DeleteOAuth2Application(id, userid int64) error {
  222. sess := x.NewSession()
  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, 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. return apps, sess.Find(&apps)
  240. }
  241. apps := make([]*OAuth2Application, 0, 5)
  242. return apps, sess.Find(&apps)
  243. }
  244. //////////////////////////////////////////////////////
  245. // OAuth2AuthorizationCode is a code to obtain an access token in combination with the client secret once. It has a limited lifetime.
  246. type OAuth2AuthorizationCode struct {
  247. ID int64 `xorm:"pk autoincr"`
  248. Grant *OAuth2Grant `xorm:"-"`
  249. GrantID int64
  250. Code string `xorm:"INDEX unique"`
  251. CodeChallenge string
  252. CodeChallengeMethod string
  253. RedirectURI string
  254. ValidUntil timeutil.TimeStamp `xorm:"index"`
  255. }
  256. // TableName sets the table name to `oauth2_authorization_code`
  257. func (code *OAuth2AuthorizationCode) TableName() string {
  258. return "oauth2_authorization_code"
  259. }
  260. // GenerateRedirectURI generates a redirect URI for a successful authorization request. State will be used if not empty.
  261. func (code *OAuth2AuthorizationCode) GenerateRedirectURI(state string) (redirect *url.URL, err error) {
  262. if redirect, err = url.Parse(code.RedirectURI); err != nil {
  263. return
  264. }
  265. q := redirect.Query()
  266. if state != "" {
  267. q.Set("state", state)
  268. }
  269. q.Set("code", code.Code)
  270. redirect.RawQuery = q.Encode()
  271. return
  272. }
  273. // Invalidate deletes the auth code from the database to invalidate this code
  274. func (code *OAuth2AuthorizationCode) Invalidate() error {
  275. return code.invalidate(x)
  276. }
  277. func (code *OAuth2AuthorizationCode) invalidate(e Engine) error {
  278. _, err := e.Delete(code)
  279. return err
  280. }
  281. // ValidateCodeChallenge validates the given verifier against the saved code challenge. This is part of the PKCE implementation.
  282. func (code *OAuth2AuthorizationCode) ValidateCodeChallenge(verifier string) bool {
  283. return code.validateCodeChallenge(verifier)
  284. }
  285. func (code *OAuth2AuthorizationCode) validateCodeChallenge(verifier string) bool {
  286. switch code.CodeChallengeMethod {
  287. case "S256":
  288. // base64url(SHA256(verifier)) see https://tools.ietf.org/html/rfc7636#section-4.6
  289. h := sha256.Sum256([]byte(verifier))
  290. hashedVerifier := base64.RawURLEncoding.EncodeToString(h[:])
  291. return hashedVerifier == code.CodeChallenge
  292. case "plain":
  293. return verifier == code.CodeChallenge
  294. case "":
  295. return true
  296. default:
  297. // unsupported method -> return false
  298. return false
  299. }
  300. }
  301. // GetOAuth2AuthorizationByCode returns an authorization by its code
  302. func GetOAuth2AuthorizationByCode(code string) (*OAuth2AuthorizationCode, error) {
  303. return getOAuth2AuthorizationByCode(x, code)
  304. }
  305. func getOAuth2AuthorizationByCode(e Engine, code string) (auth *OAuth2AuthorizationCode, err error) {
  306. auth = new(OAuth2AuthorizationCode)
  307. if has, err := e.Where("code = ?", code).Get(auth); err != nil {
  308. return nil, err
  309. } else if !has {
  310. return nil, nil
  311. }
  312. auth.Grant = new(OAuth2Grant)
  313. if has, err := e.ID(auth.GrantID).Get(auth.Grant); err != nil {
  314. return nil, err
  315. } else if !has {
  316. return nil, nil
  317. }
  318. return auth, nil
  319. }
  320. //////////////////////////////////////////////////////
  321. // OAuth2Grant represents the permission of an user for a specifc application to access resources
  322. type OAuth2Grant struct {
  323. ID int64 `xorm:"pk autoincr"`
  324. UserID int64 `xorm:"INDEX unique(user_application)"`
  325. Application *OAuth2Application `xorm:"-"`
  326. ApplicationID int64 `xorm:"INDEX unique(user_application)"`
  327. Counter int64 `xorm:"NOT NULL DEFAULT 1"`
  328. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  329. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  330. }
  331. // TableName sets the table name to `oauth2_grant`
  332. func (grant *OAuth2Grant) TableName() string {
  333. return "oauth2_grant"
  334. }
  335. // GenerateNewAuthorizationCode generates a new authorization code for a grant and saves it to the databse
  336. func (grant *OAuth2Grant) GenerateNewAuthorizationCode(redirectURI, codeChallenge, codeChallengeMethod string) (*OAuth2AuthorizationCode, error) {
  337. return grant.generateNewAuthorizationCode(x, redirectURI, codeChallenge, codeChallengeMethod)
  338. }
  339. func (grant *OAuth2Grant) generateNewAuthorizationCode(e Engine, redirectURI, codeChallenge, codeChallengeMethod string) (code *OAuth2AuthorizationCode, err error) {
  340. var codeSecret string
  341. if codeSecret, err = secret.New(); err != nil {
  342. return &OAuth2AuthorizationCode{}, err
  343. }
  344. code = &OAuth2AuthorizationCode{
  345. Grant: grant,
  346. GrantID: grant.ID,
  347. RedirectURI: redirectURI,
  348. Code: codeSecret,
  349. CodeChallenge: codeChallenge,
  350. CodeChallengeMethod: codeChallengeMethod,
  351. }
  352. if _, err := e.Insert(code); err != nil {
  353. return nil, err
  354. }
  355. return code, nil
  356. }
  357. // IncreaseCounter increases the counter and updates the grant
  358. func (grant *OAuth2Grant) IncreaseCounter() error {
  359. return grant.increaseCount(x)
  360. }
  361. func (grant *OAuth2Grant) increaseCount(e Engine) error {
  362. _, err := e.ID(grant.ID).Incr("counter").Update(new(OAuth2Grant))
  363. if err != nil {
  364. return err
  365. }
  366. updatedGrant, err := getOAuth2GrantByID(e, grant.ID)
  367. if err != nil {
  368. return err
  369. }
  370. grant.Counter = updatedGrant.Counter
  371. return nil
  372. }
  373. // GetOAuth2GrantByID returns the grant with the given ID
  374. func GetOAuth2GrantByID(id int64) (*OAuth2Grant, error) {
  375. return getOAuth2GrantByID(x, id)
  376. }
  377. func getOAuth2GrantByID(e Engine, id int64) (grant *OAuth2Grant, err error) {
  378. grant = new(OAuth2Grant)
  379. if has, err := e.ID(id).Get(grant); err != nil {
  380. return nil, err
  381. } else if !has {
  382. return nil, nil
  383. }
  384. return
  385. }
  386. // GetOAuth2GrantsByUserID lists all grants of a certain user
  387. func GetOAuth2GrantsByUserID(uid int64) ([]*OAuth2Grant, error) {
  388. return getOAuth2GrantsByUserID(x, uid)
  389. }
  390. func getOAuth2GrantsByUserID(e Engine, uid int64) ([]*OAuth2Grant, error) {
  391. type joinedOAuth2Grant struct {
  392. Grant *OAuth2Grant `xorm:"extends"`
  393. Application *OAuth2Application `xorm:"extends"`
  394. }
  395. var results *xorm.Rows
  396. var err error
  397. if results, err = e.
  398. Table("oauth2_grant").
  399. Where("user_id = ?", uid).
  400. Join("INNER", "oauth2_application", "application_id = oauth2_application.id").
  401. Rows(new(joinedOAuth2Grant)); err != nil {
  402. return nil, err
  403. }
  404. defer results.Close()
  405. grants := make([]*OAuth2Grant, 0)
  406. for results.Next() {
  407. joinedGrant := new(joinedOAuth2Grant)
  408. if err := results.Scan(joinedGrant); err != nil {
  409. return nil, err
  410. }
  411. joinedGrant.Grant.Application = joinedGrant.Application
  412. grants = append(grants, joinedGrant.Grant)
  413. }
  414. return grants, nil
  415. }
  416. // RevokeOAuth2Grant deletes the grant with grantID and userID
  417. func RevokeOAuth2Grant(grantID, userID int64) error {
  418. return revokeOAuth2Grant(x, grantID, userID)
  419. }
  420. func revokeOAuth2Grant(e Engine, grantID, userID int64) error {
  421. _, err := e.Delete(&OAuth2Grant{ID: grantID, UserID: userID})
  422. return err
  423. }
  424. //////////////////////////////////////////////////////////////
  425. // OAuth2TokenType represents the type of token for an oauth application
  426. type OAuth2TokenType int
  427. const (
  428. // TypeAccessToken is a token with short lifetime to access the api
  429. TypeAccessToken OAuth2TokenType = 0
  430. // TypeRefreshToken is token with long lifetime to refresh access tokens obtained by the client
  431. TypeRefreshToken = iota
  432. )
  433. // OAuth2Token represents a JWT token used to authenticate a client
  434. type OAuth2Token struct {
  435. GrantID int64 `json:"gnt"`
  436. Type OAuth2TokenType `json:"tt"`
  437. Counter int64 `json:"cnt,omitempty"`
  438. jwt.StandardClaims
  439. }
  440. // ParseOAuth2Token parses a singed jwt string
  441. func ParseOAuth2Token(jwtToken string) (*OAuth2Token, error) {
  442. parsedToken, err := jwt.ParseWithClaims(jwtToken, &OAuth2Token{}, func(token *jwt.Token) (interface{}, error) {
  443. if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
  444. return nil, fmt.Errorf("unexpected signing algo: %v", token.Header["alg"])
  445. }
  446. return setting.OAuth2.JWTSecretBytes, nil
  447. })
  448. if err != nil {
  449. return nil, err
  450. }
  451. var token *OAuth2Token
  452. var ok bool
  453. if token, ok = parsedToken.Claims.(*OAuth2Token); !ok || !parsedToken.Valid {
  454. return nil, fmt.Errorf("invalid token")
  455. }
  456. return token, nil
  457. }
  458. // SignToken signs the token with the JWT secret
  459. func (token *OAuth2Token) SignToken() (string, error) {
  460. token.IssuedAt = time.Now().Unix()
  461. jwtToken := jwt.NewWithClaims(jwt.SigningMethodHS512, token)
  462. return jwtToken.SignedString(setting.OAuth2.JWTSecretBytes)
  463. }