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.

303 lines
14 KiB

5 years ago
5 years ago
7 months ago
FEATURE: add JWT to HTTP endpoints of Filer and use them in S3 Client - one JWT for reading and one for writing, analogous to how the JWT between Master and Volume Server works - I did not implement IP `whiteList` parameter on the filer Additionally, because http_util.DownloadFile now sets the JWT, the `download` command should now work when `jwt.signing.read` is configured. By looking at the code, I think this case did not work before. ## Docs to be adjusted after a release Page `Amazon-S3-API`: ``` # Authentication with Filer You can use mTLS for the gRPC connection between S3-API-Proxy and the filer, as explained in [Security-Configuration](Security-Configuration) - controlled by the `grpc.*` configuration in `security.toml`. Starting with version XX, it is also possible to authenticate the HTTP operations between the S3-API-Proxy and the Filer (especially uploading new files). This is configured by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. With both configurations (gRPC and JWT), it is possible to have Filer and S3 communicate in fully authenticated fashion; so Filer will reject any unauthenticated communication. ``` Page `Security Overview`: ``` The following items are not covered, yet: - master server http REST services Starting with version XX, the Filer HTTP REST services can be secured with a JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. ... Before version XX: "weed filer -disableHttp", disable http operations, only gRPC operations are allowed. This works with "weed mount" by FUSE. It does **not work** with the [S3 Gateway](Amazon S3 API), as this does HTTP calls to the Filer. Starting with version XX: secured by JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. **This now works with the [S3 Gateway](Amazon S3 API).** ... # Securing Filer HTTP with JWT To enable JWT-based access control for the Filer, 1. generate `security.toml` file by `weed scaffold -config=security` 2. set `filer_jwt.signing.key` to a secret string - and optionally filer_jwt.signing.read.key` as well to a secret string 3. copy the same `security.toml` file to the filers and all S3 proxies. If `filer_jwt.signing.key` is configured: When sending upload/update/delete HTTP operations to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.key`. If `filer_jwt.signing.read.key` is configured: When sending GET or HEAD requests to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.read.key`. The S3 API Gateway reads the above JWT keys and sends authenticated HTTP requests to the filer. ``` Page `Security Configuration`: ``` (update scaffold file) ... [filer_jwt.signing] key = "blahblahblahblah" [filer_jwt.signing.read] key = "blahblahblahblah" ``` Resolves: #158
3 years ago
1 year ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package s3api
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/filer"
  10. "github.com/seaweedfs/seaweedfs/weed/glog"
  11. "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb"
  12. "github.com/seaweedfs/seaweedfs/weed/util/grace"
  13. "github.com/gorilla/mux"
  14. "github.com/seaweedfs/seaweedfs/weed/pb"
  15. . "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  16. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  17. "github.com/seaweedfs/seaweedfs/weed/security"
  18. "github.com/seaweedfs/seaweedfs/weed/util"
  19. util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
  20. util_http_client "github.com/seaweedfs/seaweedfs/weed/util/http/client"
  21. "google.golang.org/grpc"
  22. )
  23. const (
  24. BucketPathTpl = "/{object:[a-z0-9].+[a-z0-9]}"
  25. )
  26. type S3ApiServerOption struct {
  27. Filer pb.ServerAddress
  28. Port int
  29. Config string
  30. DomainName string
  31. AllowedOrigins []string
  32. BucketsPath string
  33. GrpcDialOption grpc.DialOption
  34. AllowEmptyFolder bool
  35. AllowDeleteBucketNotEmpty bool
  36. LocalFilerSocket string
  37. DataCenter string
  38. FilerGroup string
  39. }
  40. type S3ApiServer struct {
  41. s3_pb.UnimplementedSeaweedS3Server
  42. option *S3ApiServerOption
  43. iam *IdentityAccessManagement
  44. cb *CircuitBreaker
  45. randomClientId int32
  46. filerGuard *security.Guard
  47. client util_http_client.HTTPClientInterface
  48. bucketRegistry *BucketRegistry
  49. }
  50. func NewS3ApiServer(router *mux.Router, option *S3ApiServerOption) (s3ApiServer *S3ApiServer, err error) {
  51. v := util.GetViper()
  52. signingKey := v.GetString("jwt.filer_signing.key")
  53. v.SetDefault("jwt.filer_signing.expires_after_seconds", 10)
  54. expiresAfterSec := v.GetInt("jwt.filer_signing.expires_after_seconds")
  55. readSigningKey := v.GetString("jwt.filer_signing.read.key")
  56. v.SetDefault("jwt.filer_signing.read.expires_after_seconds", 60)
  57. readExpiresAfterSec := v.GetInt("jwt.filer_signing.read.expires_after_seconds")
  58. v.SetDefault("cors.allowed_origins.values", "*")
  59. if (option.AllowedOrigins == nil) || (len(option.AllowedOrigins) == 0) {
  60. allowedOrigins := v.GetString("cors.allowed_origins.values")
  61. domains := strings.Split(allowedOrigins, ",")
  62. option.AllowedOrigins = domains
  63. }
  64. s3ApiServer = &S3ApiServer{
  65. option: option,
  66. iam: NewIdentityAccessManagement(option),
  67. randomClientId: util.RandomInt32(),
  68. filerGuard: security.NewGuard([]string{}, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec),
  69. cb: NewCircuitBreaker(option),
  70. }
  71. if option.Config != "" {
  72. grace.OnReload(func() {
  73. if err := s3ApiServer.iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {
  74. glog.Errorf("fail to load config file %s: %v", option.Config, err)
  75. } else {
  76. glog.V(0).Infof("Loaded %d identities from config file %s", len(s3ApiServer.iam.identities), option.Config)
  77. }
  78. })
  79. }
  80. s3ApiServer.bucketRegistry = NewBucketRegistry(s3ApiServer)
  81. if option.LocalFilerSocket == "" {
  82. if s3ApiServer.client, err = util_http.NewGlobalHttpClient(); err != nil {
  83. return nil, err
  84. }
  85. } else {
  86. s3ApiServer.client = &http.Client{
  87. Transport: &http.Transport{
  88. DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
  89. return net.Dial("unix", option.LocalFilerSocket)
  90. },
  91. },
  92. }
  93. }
  94. s3ApiServer.registerRouter(router)
  95. go s3ApiServer.subscribeMetaEvents("s3", time.Now().UnixNano(), filer.DirectoryEtcRoot, []string{option.BucketsPath})
  96. return s3ApiServer, nil
  97. }
  98. func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
  99. // API Router
  100. apiRouter := router.PathPrefix("/").Subrouter()
  101. // Readiness Probe
  102. apiRouter.Methods(http.MethodGet).Path("/status").HandlerFunc(s3a.StatusHandler)
  103. apiRouter.Methods(http.MethodGet).Path("/healthz").HandlerFunc(s3a.StatusHandler)
  104. apiRouter.Methods(http.MethodOptions).HandlerFunc(
  105. func(w http.ResponseWriter, r *http.Request) {
  106. origin := r.Header.Get("Origin")
  107. if origin != "" {
  108. if s3a.option.AllowedOrigins == nil || len(s3a.option.AllowedOrigins) == 0 || s3a.option.AllowedOrigins[0] == "*" {
  109. origin = "*"
  110. } else {
  111. originFound := false
  112. for _, allowedOrigin := range s3a.option.AllowedOrigins {
  113. if origin == allowedOrigin {
  114. originFound = true
  115. }
  116. }
  117. if !originFound {
  118. writeFailureResponse(w, r, http.StatusForbidden)
  119. return
  120. }
  121. }
  122. }
  123. w.Header().Set("Access-Control-Allow-Origin", origin)
  124. w.Header().Set("Access-Control-Expose-Headers", "*")
  125. w.Header().Set("Access-Control-Allow-Methods", "*")
  126. w.Header().Set("Access-Control-Allow-Headers", "*")
  127. writeSuccessResponseEmpty(w, r)
  128. })
  129. var routers []*mux.Router
  130. if s3a.option.DomainName != "" {
  131. domainNames := strings.Split(s3a.option.DomainName, ",")
  132. for _, domainName := range domainNames {
  133. routers = append(routers, apiRouter.Host(
  134. fmt.Sprintf("%s.%s:%d", "{bucket:.+}", domainName, s3a.option.Port)).Subrouter())
  135. routers = append(routers, apiRouter.Host(
  136. fmt.Sprintf("%s.%s", "{bucket:.+}", domainName)).Subrouter())
  137. }
  138. }
  139. routers = append(routers, apiRouter.PathPrefix("/{bucket}").Subrouter())
  140. for _, bucket := range routers {
  141. // each case should follow the next rule:
  142. // - requesting object with query must precede any other methods
  143. // - requesting object must precede any methods with buckets
  144. // - requesting bucket with query must precede raw methods with buckets
  145. // - requesting bucket must be processed in the end
  146. // objects with query
  147. // CopyObjectPart
  148. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HeadersRegexp("X-Amz-Copy-Source", `.*?(\/|%2F).*?`).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CopyObjectPartHandler, ACTION_WRITE)), "PUT")).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
  149. // PutObjectPart
  150. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectPartHandler, ACTION_WRITE)), "PUT")).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
  151. // CompleteMultipartUpload
  152. bucket.Methods(http.MethodPost).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CompleteMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploadId", "{uploadId:.*}")
  153. // NewMultipartUpload
  154. bucket.Methods(http.MethodPost).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.NewMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploads", "")
  155. // AbortMultipartUpload
  156. bucket.Methods(http.MethodDelete).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.AbortMultipartUploadHandler, ACTION_WRITE)), "DELETE")).Queries("uploadId", "{uploadId:.*}")
  157. // ListObjectParts
  158. bucket.Methods(http.MethodGet).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectPartsHandler, ACTION_READ)), "GET")).Queries("uploadId", "{uploadId:.*}")
  159. // ListMultipartUploads
  160. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListMultipartUploadsHandler, ACTION_READ)), "GET")).Queries("uploads", "")
  161. // GetObjectTagging
  162. bucket.Methods(http.MethodGet).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectTaggingHandler, ACTION_READ)), "GET")).Queries("tagging", "")
  163. // PutObjectTagging
  164. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectTaggingHandler, ACTION_TAGGING)), "PUT")).Queries("tagging", "")
  165. // DeleteObjectTagging
  166. bucket.Methods(http.MethodDelete).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteObjectTaggingHandler, ACTION_TAGGING)), "DELETE")).Queries("tagging", "")
  167. // PutObjectACL
  168. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectAclHandler, ACTION_WRITE_ACP)), "PUT")).Queries("acl", "")
  169. // PutObjectRetention
  170. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectRetentionHandler, ACTION_WRITE)), "PUT")).Queries("retention", "")
  171. // PutObjectLegalHold
  172. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLegalHoldHandler, ACTION_WRITE)), "PUT")).Queries("legal-hold", "")
  173. // PutObjectLockConfiguration
  174. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLockConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("object-lock", "")
  175. // GetObjectACL
  176. bucket.Methods(http.MethodGet).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectAclHandler, ACTION_READ_ACP)), "GET")).Queries("acl", "")
  177. // objects with query
  178. // raw objects
  179. // HeadObject
  180. bucket.Methods(http.MethodHead).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.HeadObjectHandler, ACTION_READ)), "GET"))
  181. // GetObject, but directory listing is not supported
  182. bucket.Methods(http.MethodGet).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectHandler, ACTION_READ)), "GET"))
  183. // CopyObject
  184. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HeadersRegexp("X-Amz-Copy-Source", ".*?(\\/|%2F).*?").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CopyObjectHandler, ACTION_WRITE)), "COPY"))
  185. // PutObject
  186. bucket.Methods(http.MethodPut).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectHandler, ACTION_WRITE)), "PUT"))
  187. // DeleteObject
  188. bucket.Methods(http.MethodDelete).Path(BucketPathTpl).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteObjectHandler, ACTION_WRITE)), "DELETE"))
  189. // raw objects
  190. // buckets with query
  191. // DeleteMultipleObjects
  192. bucket.Methods(http.MethodPost).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteMultipleObjectsHandler, ACTION_WRITE)), "DELETE")).Queries("delete", "")
  193. // GetBucketACL
  194. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketAclHandler, ACTION_READ_ACP)), "GET")).Queries("acl", "")
  195. // PutBucketACL
  196. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketAclHandler, ACTION_WRITE_ACP)), "PUT")).Queries("acl", "")
  197. // GetBucketPolicy
  198. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketPolicyHandler, ACTION_READ)), "GET")).Queries("policy", "")
  199. // PutBucketPolicy
  200. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketPolicyHandler, ACTION_WRITE)), "PUT")).Queries("policy", "")
  201. // DeleteBucketPolicy
  202. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketPolicyHandler, ACTION_WRITE)), "DELETE")).Queries("policy", "")
  203. // GetBucketCors
  204. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketCorsHandler, ACTION_READ)), "GET")).Queries("cors", "")
  205. // PutBucketCors
  206. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketCorsHandler, ACTION_WRITE)), "PUT")).Queries("cors", "")
  207. // DeleteBucketCors
  208. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketCorsHandler, ACTION_WRITE)), "DELETE")).Queries("cors", "")
  209. // GetBucketLifecycleConfiguration
  210. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLifecycleConfigurationHandler, ACTION_READ)), "GET")).Queries("lifecycle", "")
  211. // PutBucketLifecycleConfiguration
  212. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketLifecycleConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("lifecycle", "")
  213. // DeleteBucketLifecycleConfiguration
  214. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketLifecycleHandler, ACTION_WRITE)), "DELETE")).Queries("lifecycle", "")
  215. // GetBucketLocation
  216. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLocationHandler, ACTION_READ)), "GET")).Queries("location", "")
  217. // GetBucketRequestPayment
  218. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketRequestPaymentHandler, ACTION_READ)), "GET")).Queries("requestPayment", "")
  219. // GetBucketVersioning
  220. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketVersioningHandler, ACTION_READ)), "GET")).Queries("versioning", "")
  221. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketVersioningHandler, ACTION_WRITE)), "PUT")).Queries("versioning", "")
  222. // ListObjectsV2
  223. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectsV2Handler, ACTION_LIST)), "LIST")).Queries("list-type", "2")
  224. // buckets with query
  225. // PutBucketOwnershipControls
  226. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.PutBucketOwnershipControls, ACTION_ADMIN), "PUT")).Queries("ownershipControls", "")
  227. //GetBucketOwnershipControls
  228. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.GetBucketOwnershipControls, ACTION_READ), "GET")).Queries("ownershipControls", "")
  229. //DeleteBucketOwnershipControls
  230. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.DeleteBucketOwnershipControls, ACTION_ADMIN), "DELETE")).Queries("ownershipControls", "")
  231. // raw buckets
  232. // PostPolicy
  233. bucket.Methods(http.MethodPost).HeadersRegexp("Content-Type", "multipart/form-data*").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PostPolicyBucketHandler, ACTION_WRITE)), "POST"))
  234. // HeadBucket
  235. bucket.Methods(http.MethodHead).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.HeadBucketHandler, ACTION_READ)), "GET"))
  236. // PutBucket
  237. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketHandler, ACTION_ADMIN)), "PUT"))
  238. // DeleteBucket
  239. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketHandler, ACTION_DELETE_BUCKET)), "DELETE"))
  240. // ListObjectsV1 (Legacy)
  241. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectsV1Handler, ACTION_LIST)), "LIST"))
  242. // raw buckets
  243. }
  244. // ListBuckets
  245. apiRouter.Methods(http.MethodGet).Path("/").HandlerFunc(track(s3a.ListBucketsHandler, "LIST"))
  246. // NotFound
  247. apiRouter.NotFoundHandler = http.HandlerFunc(s3err.NotFoundHandler)
  248. }