gitea源码

oauth2.go 6.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package auth
  5. import (
  6. "context"
  7. "net/http"
  8. "strings"
  9. "time"
  10. actions_model "code.gitea.io/gitea/models/actions"
  11. auth_model "code.gitea.io/gitea/models/auth"
  12. user_model "code.gitea.io/gitea/models/user"
  13. "code.gitea.io/gitea/modules/auth/httpauth"
  14. "code.gitea.io/gitea/modules/log"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "code.gitea.io/gitea/services/actions"
  18. "code.gitea.io/gitea/services/oauth2_provider"
  19. )
  20. // Ensure the struct implements the interface.
  21. var (
  22. _ Method = &OAuth2{}
  23. )
  24. // GetOAuthAccessTokenScopeAndUserID returns access token scope and user id
  25. func GetOAuthAccessTokenScopeAndUserID(ctx context.Context, accessToken string) (auth_model.AccessTokenScope, int64) {
  26. var accessTokenScope auth_model.AccessTokenScope
  27. if !setting.OAuth2.Enabled {
  28. return accessTokenScope, 0
  29. }
  30. // JWT tokens require a ".", if the token isn't like that, return early
  31. if !strings.Contains(accessToken, ".") {
  32. return accessTokenScope, 0
  33. }
  34. token, err := oauth2_provider.ParseToken(accessToken, oauth2_provider.DefaultSigningKey)
  35. if err != nil {
  36. log.Trace("oauth2.ParseToken: %v", err)
  37. return accessTokenScope, 0
  38. }
  39. var grant *auth_model.OAuth2Grant
  40. if grant, err = auth_model.GetOAuth2GrantByID(ctx, token.GrantID); err != nil || grant == nil {
  41. return accessTokenScope, 0
  42. }
  43. if token.Kind != oauth2_provider.KindAccessToken {
  44. return accessTokenScope, 0
  45. }
  46. if token.ExpiresAt.Before(time.Now()) || token.IssuedAt.After(time.Now()) {
  47. return accessTokenScope, 0
  48. }
  49. accessTokenScope = oauth2_provider.GrantAdditionalScopes(grant.Scope)
  50. return accessTokenScope, grant.UserID
  51. }
  52. // CheckTaskIsRunning verifies that the TaskID corresponds to a running task
  53. func CheckTaskIsRunning(ctx context.Context, taskID int64) bool {
  54. // Verify the task exists
  55. task, err := actions_model.GetTaskByID(ctx, taskID)
  56. if err != nil {
  57. return false
  58. }
  59. // Verify that it's running
  60. return task.Status == actions_model.StatusRunning
  61. }
  62. // OAuth2 implements the Auth interface and authenticates requests
  63. // (API requests only) by looking for an OAuth token in query parameters or the
  64. // "Authorization" header.
  65. type OAuth2 struct{}
  66. // Name represents the name of auth method
  67. func (o *OAuth2) Name() string {
  68. return "oauth2"
  69. }
  70. // parseToken returns the token from request, and a boolean value
  71. // representing whether the token exists or not
  72. func parseToken(req *http.Request) (string, bool) {
  73. _ = req.ParseForm()
  74. if !setting.DisableQueryAuthToken {
  75. // Check token.
  76. if token := req.Form.Get("token"); token != "" {
  77. return token, true
  78. }
  79. // Check access token.
  80. if token := req.Form.Get("access_token"); token != "" {
  81. return token, true
  82. }
  83. } else if req.Form.Get("token") != "" || req.Form.Get("access_token") != "" {
  84. log.Warn("API token sent in query string but DISABLE_QUERY_AUTH_TOKEN=true")
  85. }
  86. // check header token
  87. if auHead := req.Header.Get("Authorization"); auHead != "" {
  88. parsed, ok := httpauth.ParseAuthorizationHeader(auHead)
  89. if ok && parsed.BearerToken != nil {
  90. return parsed.BearerToken.Token, true
  91. }
  92. }
  93. return "", false
  94. }
  95. // userIDFromToken returns the user id corresponding to the OAuth token.
  96. // It will set 'IsApiToken' to true if the token is an API token and
  97. // set 'ApiTokenScope' to the scope of the access token
  98. func (o *OAuth2) userIDFromToken(ctx context.Context, tokenSHA string, store DataStore) int64 {
  99. // Let's see if token is valid.
  100. if strings.Contains(tokenSHA, ".") {
  101. // First attempt to decode an actions JWT, returning the actions user
  102. if taskID, err := actions.TokenToTaskID(tokenSHA); err == nil {
  103. if CheckTaskIsRunning(ctx, taskID) {
  104. store.GetData()["IsActionsToken"] = true
  105. store.GetData()["ActionsTaskID"] = taskID
  106. return user_model.ActionsUserID
  107. }
  108. }
  109. // Otherwise, check if this is an OAuth access token
  110. accessTokenScope, uid := GetOAuthAccessTokenScopeAndUserID(ctx, tokenSHA)
  111. if uid != 0 {
  112. store.GetData()["IsApiToken"] = true
  113. store.GetData()["ApiTokenScope"] = accessTokenScope
  114. }
  115. return uid
  116. }
  117. t, err := auth_model.GetAccessTokenBySHA(ctx, tokenSHA)
  118. if err != nil {
  119. if auth_model.IsErrAccessTokenNotExist(err) {
  120. // check task token
  121. task, err := actions_model.GetRunningTaskByToken(ctx, tokenSHA)
  122. if err == nil && task != nil {
  123. log.Trace("Basic Authorization: Valid AccessToken for task[%d]", task.ID)
  124. store.GetData()["IsActionsToken"] = true
  125. store.GetData()["ActionsTaskID"] = task.ID
  126. return user_model.ActionsUserID
  127. }
  128. } else if !auth_model.IsErrAccessTokenNotExist(err) && !auth_model.IsErrAccessTokenEmpty(err) {
  129. log.Error("GetAccessTokenBySHA: %v", err)
  130. }
  131. return 0
  132. }
  133. t.UpdatedUnix = timeutil.TimeStampNow()
  134. if err = auth_model.UpdateAccessToken(ctx, t); err != nil {
  135. log.Error("UpdateAccessToken: %v", err)
  136. }
  137. store.GetData()["IsApiToken"] = true
  138. store.GetData()["ApiTokenScope"] = t.Scope
  139. return t.UID
  140. }
  141. // Verify extracts the user ID from the OAuth token in the query parameters
  142. // or the "Authorization" header and returns the corresponding user object for that ID.
  143. // If verification is successful returns an existing user object.
  144. // Returns nil if verification fails.
  145. func (o *OAuth2) Verify(req *http.Request, w http.ResponseWriter, store DataStore, sess SessionStore) (*user_model.User, error) {
  146. // These paths are not API paths, but we still want to check for tokens because they maybe in the API returned URLs
  147. detector := newAuthPathDetector(req)
  148. if !detector.isAPIPath() && !detector.isAttachmentDownload() && !detector.isAuthenticatedTokenRequest() &&
  149. !detector.isGitRawOrAttachPath() && !detector.isArchivePath() {
  150. return nil, nil
  151. }
  152. token, ok := parseToken(req)
  153. if !ok {
  154. return nil, nil
  155. }
  156. id := o.userIDFromToken(req.Context(), token, store)
  157. if id <= 0 && id != -2 { // -2 means actions, so we need to allow it.
  158. return nil, user_model.ErrUserNotExist{}
  159. }
  160. log.Trace("OAuth2 Authorization: Found token for user[%d]", id)
  161. user, err := user_model.GetPossibleUserByID(req.Context(), id)
  162. if err != nil {
  163. if !user_model.IsErrUserNotExist(err) {
  164. log.Error("GetUserByName: %v", err)
  165. }
  166. return nil, err
  167. }
  168. log.Trace("OAuth2 Authorization: Logged in user %-v", user)
  169. return user, nil
  170. }