handlers.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package tokens
  15. import (
  16. "context"
  17. "net/http"
  18. "yunion.io/x/jsonutils"
  19. "yunion.io/x/log"
  20. "yunion.io/x/pkg/errors"
  21. "yunion.io/x/pkg/util/rbacscope"
  22. "yunion.io/x/sqlchemy"
  23. api "yunion.io/x/onecloud/pkg/apis/identity"
  24. "yunion.io/x/onecloud/pkg/appsrv"
  25. "yunion.io/x/onecloud/pkg/cloudcommon/policy"
  26. "yunion.io/x/onecloud/pkg/httperrors"
  27. "yunion.io/x/onecloud/pkg/keystone/cache"
  28. "yunion.io/x/onecloud/pkg/keystone/models"
  29. "yunion.io/x/onecloud/pkg/mcclient"
  30. "yunion.io/x/onecloud/pkg/mcclient/auth"
  31. "yunion.io/x/onecloud/pkg/util/netutils2"
  32. )
  33. func AddHandler(app *appsrv.Application) {
  34. app.AddHandler2("POST", "/v2.0/tokens", authenticateTokensV2, nil, "auth_tokens_v2", nil)
  35. app.AddHandler2("POST", "/v3/auth/tokens", authenticateTokensV3, nil, "auth_tokens_v3", nil)
  36. app.AddHandler2("GET", "/v2.0/tokens/<token>", authenticateToken(verifyTokensV2), nil, "verify_tokens_v2", nil)
  37. app.AddHandler2("GET", "/v3/auth/tokens", authenticateToken(verifyTokensV3), nil, "verify_tokens_v3", nil)
  38. app.AddHandler2("GET", "/v3/auth/policies", authenticateToken(fetchTokenPolicies), nil, "fetch_token_policies", nil)
  39. app.AddHandler2("POST", "/v3/auth/policies", authenticateToken(postTokenPolicies), nil, "post_token_policies", nil)
  40. app.AddHandler2("DELETE", "/v3/auth/tokens", authenticateToken(invalidateTokenV3), nil, "delete_tokens_v3", nil)
  41. app.AddHandler2("GET", "/v3/auth/tokens/invalid", authenticateToken(fetchInvalidTokensV3), nil, "fetch_revoked_tokens_v3", nil)
  42. }
  43. func FetchAuthContext(authCtx mcclient.SAuthContext, r *http.Request) mcclient.SAuthContext {
  44. if len(authCtx.Source) == 0 {
  45. authCtx.Source = mcclient.AuthSourceAPI
  46. }
  47. if len(authCtx.Ip) == 0 || authCtx.Ip == "0.0.0.0" {
  48. authCtx.Ip = netutils2.GetHttpRequestIp(r)
  49. }
  50. return authCtx
  51. }
  52. func authenticateTokensV2(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  53. _, _, body := appsrv.FetchEnv(ctx, w, r)
  54. input := mcclient.SAuthenticationInputV2{}
  55. err := body.Unmarshal(&input)
  56. if err != nil {
  57. httperrors.InvalidInputError(ctx, w, "unrecognized input %s", err)
  58. return
  59. }
  60. input.Auth.Context = FetchAuthContext(input.Auth.Context, r)
  61. token, err := AuthenticateV2(ctx, input)
  62. if err != nil {
  63. log.Errorf("AuthenticateV2 error %s", err)
  64. httperrors.GeneralServerError(ctx, w, err)
  65. return
  66. }
  67. if token == nil {
  68. httperrors.UnauthorizedError(ctx, w, "unauthorized %s", err)
  69. return
  70. }
  71. appsrv.SendJSON(w, jsonutils.Marshal(token))
  72. models.UserManager.TraceLoginV2(ctx, &token.Access)
  73. }
  74. func authenticateTokensV3(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  75. _, _, body := appsrv.FetchEnv(ctx, w, r)
  76. if body == nil {
  77. httperrors.InvalidInputError(ctx, w, "fail to decode request body")
  78. return
  79. }
  80. input := mcclient.SAuthenticationInputV3{}
  81. err := body.Unmarshal(&input)
  82. if err != nil {
  83. httperrors.InvalidInputError(ctx, w, "unrecognized input %s", err)
  84. return
  85. }
  86. input.Auth.Context = FetchAuthContext(input.Auth.Context, r)
  87. token, err := AuthenticateV3(ctx, input)
  88. if err != nil {
  89. log.Errorf("AuthenticateV3 error %s", err)
  90. switch errors.Cause(err) {
  91. case sqlchemy.ErrDuplicateEntry:
  92. httperrors.ConflictError(ctx, w, "duplicate username")
  93. case httperrors.ErrTooManyAttempts,
  94. httperrors.ErrUserNotFound,
  95. httperrors.ErrUserDisabled,
  96. httperrors.ErrUserLocked,
  97. httperrors.ErrInvalidIdpStatus,
  98. httperrors.ErrWrongPassword:
  99. httperrors.GeneralServerError(ctx, w, err)
  100. default:
  101. httperrors.UnauthorizedError(ctx, w, "unauthorized %s", err)
  102. }
  103. return
  104. }
  105. if token == nil {
  106. httperrors.UnauthorizedError(ctx, w, "user not found or not enabled")
  107. return
  108. }
  109. w.Header().Set(api.AUTH_SUBJECT_TOKEN_HEADER, token.Id)
  110. appsrv.SendJSON(w, jsonutils.Marshal(token))
  111. models.UserManager.TraceLoginV3(ctx, token)
  112. }
  113. // swagger:parameters verifyTokensV2
  114. type VerifyTokenV2Param struct {
  115. // keystone V2验证token
  116. // in:path
  117. // required:true
  118. Token string
  119. }
  120. // swagger:route GET /v2.0/tokens/{token} authentication verifyTokensV2
  121. //
  122. // keystone v2验证token API
  123. //
  124. // keystone v2验证token API
  125. //
  126. // Responses:
  127. // 200: tokens_AuthenticateV2Output
  128. func verifyTokensV2(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  129. params, _, _ := appsrv.FetchEnv(ctx, w, r)
  130. tokenStr := params["<token>"]
  131. cachedToken := cache.Get(tokenStr)
  132. if cachedToken != nil {
  133. if v2token, ok := cachedToken.(*mcclient.TokenCredentialV2); ok && v2token.IsValid() {
  134. ret := jsonutils.NewDict()
  135. ret.Add(jsonutils.Marshal(v2token), "access")
  136. appsrv.SendJSON(w, ret)
  137. return
  138. } else {
  139. cache.Remove(tokenStr)
  140. }
  141. }
  142. token, err := verifyCommon(ctx, w, tokenStr)
  143. if err != nil {
  144. httperrors.GeneralServerError(ctx, w, err)
  145. return
  146. }
  147. user, err := models.UserManager.FetchUserExtended(token.UserId, "", "", "")
  148. if err != nil {
  149. httperrors.InvalidCredentialError(ctx, w, "invalid user")
  150. return
  151. }
  152. project, err := models.ProjectManager.FetchProject(token.ProjectId, "", "", "")
  153. if err != nil {
  154. httperrors.InvalidCredentialError(ctx, w, "invalid project")
  155. return
  156. }
  157. projExt, err := project.FetchExtend()
  158. if err != nil {
  159. httperrors.InvalidCredentialError(ctx, w, "invalid project")
  160. return
  161. }
  162. v2token, err := token.getTokenV2(ctx, user, projExt)
  163. if err != nil {
  164. httperrors.InternalServerError(ctx, w, "internal server error %s", err)
  165. return
  166. }
  167. ret := jsonutils.NewDict()
  168. ret.Add(jsonutils.Marshal(v2token), "access")
  169. appsrv.SendJSON(w, ret)
  170. }
  171. // swagger:parameters verifyTokensV3
  172. type VerifyTokenV3Param struct {
  173. // keystone V3验证token
  174. // in:header
  175. // required:true
  176. Token string `json:"X-Subject-Token"`
  177. }
  178. // swagger:route GET /v3/auth/tokens authentication verifyTokensV3
  179. //
  180. // keystone v3验证token API
  181. //
  182. // keystone v3验证token API
  183. //
  184. // Responses:
  185. // 200: tokens_AuthenticateV3Output
  186. func verifyTokensV3(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  187. tokenStr := r.Header.Get(api.AUTH_SUBJECT_TOKEN_HEADER)
  188. cachedToken := cache.Get(tokenStr)
  189. if cachedToken != nil {
  190. if v3token, ok := cachedToken.(*mcclient.TokenCredentialV3); ok && v3token.IsValid() {
  191. w.Header().Set(api.AUTH_SUBJECT_TOKEN_HEADER, v3token.Id)
  192. v3token.Id = ""
  193. appsrv.SendJSON(w, jsonutils.Marshal(v3token))
  194. return
  195. } else {
  196. cache.Remove(tokenStr)
  197. }
  198. }
  199. token, err := verifyCommon(ctx, w, tokenStr)
  200. if err != nil {
  201. httperrors.GeneralServerError(ctx, w, err)
  202. return
  203. }
  204. user, err := models.UserManager.FetchUserExtended(token.UserId, "", "", "")
  205. if err != nil {
  206. httperrors.InvalidCredentialError(ctx, w, "invalid user")
  207. return
  208. }
  209. var projExt *models.SProjectExtended
  210. var domain *models.SDomain
  211. if len(token.ProjectId) > 0 {
  212. project, err := models.ProjectManager.FetchProject(token.ProjectId, "", "", "")
  213. if err != nil {
  214. httperrors.InvalidCredentialError(ctx, w, "invalid project")
  215. return
  216. }
  217. projExt, err = project.FetchExtend()
  218. if err != nil {
  219. httperrors.InvalidCredentialError(ctx, w, "invalid project")
  220. return
  221. }
  222. } else if len(token.DomainId) > 0 {
  223. domain, err = models.DomainManager.FetchDomainById(token.DomainId)
  224. if err != nil {
  225. httperrors.InvalidCredentialError(ctx, w, "invalid domain")
  226. return
  227. }
  228. }
  229. v3token, err := token.getTokenV3(ctx, user, projExt, domain, api.SAccessKeySecretInfo{})
  230. if err != nil {
  231. httperrors.InternalServerError(ctx, w, "internal server error %s", err)
  232. return
  233. }
  234. w.Header().Set(api.AUTH_SUBJECT_TOKEN_HEADER, v3token.Id)
  235. v3token.Id = ""
  236. appsrv.SendJSON(w, jsonutils.Marshal(v3token))
  237. }
  238. func verifyCommon(ctx context.Context, w http.ResponseWriter, tokenStr string) (*SAuthToken, error) {
  239. adminToken := policy.FetchUserCredential(ctx)
  240. if adminToken == nil || len(tokenStr) == 0 {
  241. return nil, httperrors.NewForbiddenError("missing auth token")
  242. }
  243. result := policy.PolicyManager.Allow(rbacscope.ScopeSystem, adminToken, api.SERVICE_TYPE, "tokens", "perform", "auth")
  244. if result.Result.IsDeny() {
  245. return nil, httperrors.NewForbiddenError("%s not allow to auth", adminToken.GetUserName())
  246. }
  247. token, err := TokenStrDecode(ctx, tokenStr)
  248. if err != nil {
  249. return nil, httperrors.NewInvalidCredentialError("invalid token: %v", err)
  250. }
  251. return token, nil
  252. }
  253. func authenticateToken(f appsrv.FilterHandler) appsrv.FilterHandler {
  254. return authenticateTokenWithDelayDecision(f, true)
  255. }
  256. func authenticateTokenWithDelayDecision(f appsrv.FilterHandler, delayDecision bool) appsrv.FilterHandler {
  257. return auth.AuthenticateWithDelayDecision(f, delayDecision)
  258. }