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.

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