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.

297 lines
14 KiB

5 years ago
5 years 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
3 years ago
3 years ago
3 years ago
3 years ago
3 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. "google.golang.org/grpc"
  20. )
  21. type S3ApiServerOption struct {
  22. Filer pb.ServerAddress
  23. Port int
  24. Config string
  25. DomainName string
  26. AllowedOrigins []string
  27. BucketsPath string
  28. GrpcDialOption grpc.DialOption
  29. AllowEmptyFolder bool
  30. AllowDeleteBucketNotEmpty bool
  31. LocalFilerSocket string
  32. DataCenter string
  33. FilerGroup string
  34. }
  35. type S3ApiServer struct {
  36. s3_pb.UnimplementedSeaweedS3Server
  37. option *S3ApiServerOption
  38. iam *IdentityAccessManagement
  39. cb *CircuitBreaker
  40. randomClientId int32
  41. filerGuard *security.Guard
  42. client *http.Client
  43. bucketRegistry *BucketRegistry
  44. }
  45. func NewS3ApiServer(router *mux.Router, option *S3ApiServerOption) (s3ApiServer *S3ApiServer, err error) {
  46. v := util.GetViper()
  47. signingKey := v.GetString("jwt.filer_signing.key")
  48. v.SetDefault("jwt.filer_signing.expires_after_seconds", 10)
  49. expiresAfterSec := v.GetInt("jwt.filer_signing.expires_after_seconds")
  50. readSigningKey := v.GetString("jwt.filer_signing.read.key")
  51. v.SetDefault("jwt.filer_signing.read.expires_after_seconds", 60)
  52. readExpiresAfterSec := v.GetInt("jwt.filer_signing.read.expires_after_seconds")
  53. v.SetDefault("cors.allowed_origins.values", "*")
  54. if (option.AllowedOrigins == nil) || (len(option.AllowedOrigins) == 0) {
  55. allowedOrigins := v.GetString("cors.allowed_origins.values")
  56. domains := strings.Split(allowedOrigins, ",")
  57. option.AllowedOrigins = domains
  58. }
  59. s3ApiServer = &S3ApiServer{
  60. option: option,
  61. iam: NewIdentityAccessManagement(option),
  62. randomClientId: util.RandomInt32(),
  63. filerGuard: security.NewGuard([]string{}, signingKey, expiresAfterSec, readSigningKey, readExpiresAfterSec),
  64. cb: NewCircuitBreaker(option),
  65. }
  66. if option.Config != "" {
  67. grace.OnReload(func() {
  68. if err := s3ApiServer.iam.loadS3ApiConfigurationFromFile(option.Config); err != nil {
  69. glog.Errorf("fail to load config file %s: %v", option.Config, err)
  70. } else {
  71. glog.V(0).Infof("Loaded %d identities from config file %s", len(s3ApiServer.iam.identities), option.Config)
  72. }
  73. })
  74. }
  75. s3ApiServer.bucketRegistry = NewBucketRegistry(s3ApiServer)
  76. if option.LocalFilerSocket == "" {
  77. s3ApiServer.client = &http.Client{Transport: &http.Transport{
  78. MaxIdleConns: 1024,
  79. MaxIdleConnsPerHost: 1024,
  80. }}
  81. } else {
  82. s3ApiServer.client = &http.Client{
  83. Transport: &http.Transport{
  84. DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
  85. return net.Dial("unix", option.LocalFilerSocket)
  86. },
  87. },
  88. }
  89. }
  90. s3ApiServer.registerRouter(router)
  91. go s3ApiServer.subscribeMetaEvents("s3", time.Now().UnixNano(), filer.DirectoryEtcRoot, []string{option.BucketsPath})
  92. return s3ApiServer, nil
  93. }
  94. func (s3a *S3ApiServer) registerRouter(router *mux.Router) {
  95. // API Router
  96. apiRouter := router.PathPrefix("/").Subrouter()
  97. // Readiness Probe
  98. apiRouter.Methods(http.MethodGet).Path("/status").HandlerFunc(s3a.StatusHandler)
  99. apiRouter.Methods(http.MethodOptions).HandlerFunc(
  100. func(w http.ResponseWriter, r *http.Request) {
  101. origin := r.Header.Get("Origin")
  102. if origin != "" {
  103. if s3a.option.AllowedOrigins == nil || len(s3a.option.AllowedOrigins) == 0 || s3a.option.AllowedOrigins[0] == "*" {
  104. origin = "*"
  105. } else {
  106. originFound := false
  107. for _, allowedOrigin := range s3a.option.AllowedOrigins {
  108. if origin == allowedOrigin {
  109. originFound = true
  110. }
  111. }
  112. if !originFound {
  113. writeFailureResponse(w, r, http.StatusForbidden)
  114. return
  115. }
  116. }
  117. }
  118. w.Header().Set("Access-Control-Allow-Origin", origin)
  119. w.Header().Set("Access-Control-Expose-Headers", "*")
  120. w.Header().Set("Access-Control-Allow-Methods", "*")
  121. w.Header().Set("Access-Control-Allow-Headers", "*")
  122. writeSuccessResponseEmpty(w, r)
  123. })
  124. var routers []*mux.Router
  125. if s3a.option.DomainName != "" {
  126. domainNames := strings.Split(s3a.option.DomainName, ",")
  127. for _, domainName := range domainNames {
  128. routers = append(routers, apiRouter.Host(
  129. fmt.Sprintf("%s.%s:%d", "{bucket:.+}", domainName, s3a.option.Port)).Subrouter())
  130. routers = append(routers, apiRouter.Host(
  131. fmt.Sprintf("%s.%s", "{bucket:.+}", domainName)).Subrouter())
  132. }
  133. }
  134. routers = append(routers, apiRouter.PathPrefix("/{bucket}").Subrouter())
  135. for _, bucket := range routers {
  136. // each case should follow the next rule:
  137. // - requesting object with query must precede any other methods
  138. // - requesting object must precede any methods with buckets
  139. // - requesting bucket with query must precede raw methods with buckets
  140. // - requesting bucket must be processed in the end
  141. // objects with query
  142. // CopyObjectPart
  143. bucket.Methods(http.MethodPut).Path("/{object:.+}").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:.*}")
  144. // PutObjectPart
  145. bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectPartHandler, ACTION_WRITE)), "PUT")).Queries("partNumber", "{partNumber:[0-9]+}", "uploadId", "{uploadId:.*}")
  146. // CompleteMultipartUpload
  147. bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CompleteMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploadId", "{uploadId:.*}")
  148. // NewMultipartUpload
  149. bucket.Methods(http.MethodPost).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.NewMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploads", "")
  150. // AbortMultipartUpload
  151. bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.AbortMultipartUploadHandler, ACTION_WRITE)), "DELETE")).Queries("uploadId", "{uploadId:.*}")
  152. // ListObjectParts
  153. bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectPartsHandler, ACTION_READ)), "GET")).Queries("uploadId", "{uploadId:.*}")
  154. // ListMultipartUploads
  155. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListMultipartUploadsHandler, ACTION_READ)), "GET")).Queries("uploads", "")
  156. // GetObjectTagging
  157. bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectTaggingHandler, ACTION_READ)), "GET")).Queries("tagging", "")
  158. // PutObjectTagging
  159. bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectTaggingHandler, ACTION_TAGGING)), "PUT")).Queries("tagging", "")
  160. // DeleteObjectTagging
  161. bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteObjectTaggingHandler, ACTION_TAGGING)), "DELETE")).Queries("tagging", "")
  162. // PutObjectACL
  163. bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectAclHandler, ACTION_WRITE_ACP)), "PUT")).Queries("acl", "")
  164. // PutObjectRetention
  165. bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectRetentionHandler, ACTION_WRITE)), "PUT")).Queries("retention", "")
  166. // PutObjectLegalHold
  167. bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLegalHoldHandler, ACTION_WRITE)), "PUT")).Queries("legal-hold", "")
  168. // PutObjectLockConfiguration
  169. bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLockConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("object-lock", "")
  170. // GetObjectACL
  171. bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectAclHandler, ACTION_READ_ACP)), "GET")).Queries("acl", "")
  172. // objects with query
  173. // raw objects
  174. // HeadObject
  175. bucket.Methods(http.MethodHead).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.HeadObjectHandler, ACTION_READ)), "GET"))
  176. // GetObject, but directory listing is not supported
  177. bucket.Methods(http.MethodGet).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectHandler, ACTION_READ)), "GET"))
  178. // CopyObject
  179. bucket.Methods(http.MethodPut).Path("/{object:.+}").HeadersRegexp("X-Amz-Copy-Source", ".*?(\\/|%2F).*?").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CopyObjectHandler, ACTION_WRITE)), "COPY"))
  180. // PutObject
  181. bucket.Methods(http.MethodPut).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectHandler, ACTION_WRITE)), "PUT"))
  182. // DeleteObject
  183. bucket.Methods(http.MethodDelete).Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteObjectHandler, ACTION_WRITE)), "DELETE"))
  184. // raw objects
  185. // buckets with query
  186. // DeleteMultipleObjects
  187. bucket.Methods(http.MethodPost).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteMultipleObjectsHandler, ACTION_WRITE)), "DELETE")).Queries("delete", "")
  188. // GetBucketACL
  189. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketAclHandler, ACTION_READ_ACP)), "GET")).Queries("acl", "")
  190. // PutBucketACL
  191. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketAclHandler, ACTION_WRITE_ACP)), "PUT")).Queries("acl", "")
  192. // GetBucketPolicy
  193. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketPolicyHandler, ACTION_READ)), "GET")).Queries("policy", "")
  194. // PutBucketPolicy
  195. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketPolicyHandler, ACTION_WRITE)), "PUT")).Queries("policy", "")
  196. // DeleteBucketPolicy
  197. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketPolicyHandler, ACTION_WRITE)), "DELETE")).Queries("policy", "")
  198. // GetBucketCors
  199. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketCorsHandler, ACTION_READ)), "GET")).Queries("cors", "")
  200. // PutBucketCors
  201. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketCorsHandler, ACTION_WRITE)), "PUT")).Queries("cors", "")
  202. // DeleteBucketCors
  203. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketCorsHandler, ACTION_WRITE)), "DELETE")).Queries("cors", "")
  204. // GetBucketLifecycleConfiguration
  205. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLifecycleConfigurationHandler, ACTION_READ)), "GET")).Queries("lifecycle", "")
  206. // PutBucketLifecycleConfiguration
  207. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketLifecycleConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("lifecycle", "")
  208. // DeleteBucketLifecycleConfiguration
  209. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketLifecycleHandler, ACTION_WRITE)), "DELETE")).Queries("lifecycle", "")
  210. // GetBucketLocation
  211. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLocationHandler, ACTION_READ)), "GET")).Queries("location", "")
  212. // GetBucketRequestPayment
  213. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketRequestPaymentHandler, ACTION_READ)), "GET")).Queries("requestPayment", "")
  214. // GetBucketVersioning
  215. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketVersioningHandler, ACTION_READ)), "GET")).Queries("versioning", "")
  216. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketVersioningHandler, ACTION_WRITE)), "PUT")).Queries("versioning", "")
  217. // ListObjectsV2
  218. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectsV2Handler, ACTION_LIST)), "LIST")).Queries("list-type", "2")
  219. // buckets with query
  220. // PutBucketOwnershipControls
  221. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.PutBucketOwnershipControls, ACTION_ADMIN), "PUT")).Queries("ownershipControls", "")
  222. //GetBucketOwnershipControls
  223. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.GetBucketOwnershipControls, ACTION_READ), "GET")).Queries("ownershipControls", "")
  224. //DeleteBucketOwnershipControls
  225. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.DeleteBucketOwnershipControls, ACTION_ADMIN), "DELETE")).Queries("ownershipControls", "")
  226. // raw buckets
  227. // PostPolicy
  228. bucket.Methods(http.MethodPost).HeadersRegexp("Content-Type", "multipart/form-data*").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PostPolicyBucketHandler, ACTION_WRITE)), "POST"))
  229. // HeadBucket
  230. bucket.Methods(http.MethodHead).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.HeadBucketHandler, ACTION_READ)), "GET"))
  231. // PutBucket
  232. bucket.Methods(http.MethodPut).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketHandler, ACTION_ADMIN)), "PUT"))
  233. // DeleteBucket
  234. bucket.Methods(http.MethodDelete).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketHandler, ACTION_DELETE_BUCKET)), "DELETE"))
  235. // ListObjectsV1 (Legacy)
  236. bucket.Methods(http.MethodGet).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectsV1Handler, ACTION_LIST)), "LIST"))
  237. // raw buckets
  238. }
  239. // ListBuckets
  240. apiRouter.Methods(http.MethodGet).Path("/").HandlerFunc(track(s3a.ListBucketsHandler, "LIST"))
  241. // NotFound
  242. apiRouter.NotFoundHandler = http.HandlerFunc(s3err.NotFoundHandler)
  243. }