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.

503 lines
15 KiB

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