s3api_server.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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("GET").Path("/status").HandlerFunc(s3a.StatusHandler)
  99. apiRouter.Methods("OPTIONS").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("PUT").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("PUT").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("POST").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.CompleteMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploadId", "{uploadId:.*}")
  148. // NewMultipartUpload
  149. bucket.Methods("POST").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.NewMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploads", "")
  150. // AbortMultipartUpload
  151. bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.AbortMultipartUploadHandler, ACTION_WRITE)), "DELETE")).Queries("uploadId", "{uploadId:.*}")
  152. // ListObjectParts
  153. bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectPartsHandler, ACTION_READ)), "GET")).Queries("uploadId", "{uploadId:.*}")
  154. // ListMultipartUploads
  155. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListMultipartUploadsHandler, ACTION_READ)), "GET")).Queries("uploads", "")
  156. // GetObjectTagging
  157. bucket.Methods("GET").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectTaggingHandler, ACTION_READ)), "GET")).Queries("tagging", "")
  158. // PutObjectTagging
  159. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectTaggingHandler, ACTION_TAGGING)), "PUT")).Queries("tagging", "")
  160. // DeleteObjectTagging
  161. bucket.Methods("DELETE").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteObjectTaggingHandler, ACTION_TAGGING)), "DELETE")).Queries("tagging", "")
  162. // PutObjectACL
  163. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectAclHandler, ACTION_WRITE_ACP)), "PUT")).Queries("acl", "")
  164. // PutObjectRetention
  165. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectRetentionHandler, ACTION_WRITE)), "PUT")).Queries("retention", "")
  166. // PutObjectLegalHold
  167. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLegalHoldHandler, ACTION_WRITE)), "PUT")).Queries("legal-hold", "")
  168. // PutObjectLockConfiguration
  169. bucket.Methods("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectLockConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("object-lock", "")
  170. // GetObjectACL
  171. bucket.Methods("GET").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("HEAD").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("GET").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetObjectHandler, ACTION_READ)), "GET"))
  178. // CopyObject
  179. bucket.Methods("PUT").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("PUT").Path("/{object:.+}").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutObjectHandler, ACTION_WRITE)), "PUT"))
  182. // DeleteObject
  183. bucket.Methods("DELETE").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("POST").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteMultipleObjectsHandler, ACTION_WRITE)), "DELETE")).Queries("delete", "")
  188. // GetBucketACL
  189. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketAclHandler, ACTION_READ_ACP)), "GET")).Queries("acl", "")
  190. // PutBucketACL
  191. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketAclHandler, ACTION_WRITE_ACP)), "PUT")).Queries("acl", "")
  192. // GetBucketPolicy
  193. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketPolicyHandler, ACTION_READ)), "GET")).Queries("policy", "")
  194. // PutBucketPolicy
  195. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketPolicyHandler, ACTION_WRITE)), "PUT")).Queries("policy", "")
  196. // DeleteBucketPolicy
  197. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketPolicyHandler, ACTION_WRITE)), "DELETE")).Queries("policy", "")
  198. // GetBucketCors
  199. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketCorsHandler, ACTION_READ)), "GET")).Queries("cors", "")
  200. // PutBucketCors
  201. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketCorsHandler, ACTION_WRITE)), "PUT")).Queries("cors", "")
  202. // DeleteBucketCors
  203. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketCorsHandler, ACTION_WRITE)), "DELETE")).Queries("cors", "")
  204. // GetBucketLifecycleConfiguration
  205. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLifecycleConfigurationHandler, ACTION_READ)), "GET")).Queries("lifecycle", "")
  206. // PutBucketLifecycleConfiguration
  207. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketLifecycleConfigurationHandler, ACTION_WRITE)), "PUT")).Queries("lifecycle", "")
  208. // DeleteBucketLifecycleConfiguration
  209. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketLifecycleHandler, ACTION_WRITE)), "DELETE")).Queries("lifecycle", "")
  210. // GetBucketLocation
  211. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketLocationHandler, ACTION_READ)), "GET")).Queries("location", "")
  212. // GetBucketRequestPayment
  213. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketRequestPaymentHandler, ACTION_READ)), "GET")).Queries("requestPayment", "")
  214. // GetBucketVersioning
  215. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetBucketVersioningHandler, ACTION_READ)), "GET")).Queries("versioning", "")
  216. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketVersioningHandler, ACTION_WRITE)), "PUT")).Queries("versioning", "")
  217. // ListObjectsV2
  218. bucket.Methods("GET").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("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.PutBucketOwnershipControls, ACTION_ADMIN), "PUT")).Queries("ownershipControls", "")
  222. //GetBucketOwnershipControls
  223. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.GetBucketOwnershipControls, ACTION_READ), "GET")).Queries("ownershipControls", "")
  224. //DeleteBucketOwnershipControls
  225. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.DeleteBucketOwnershipControls, ACTION_ADMIN), "DELETE")).Queries("ownershipControls", "")
  226. // raw buckets
  227. // PostPolicy
  228. bucket.Methods("POST").HeadersRegexp("Content-Type", "multipart/form-data*").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PostPolicyBucketHandler, ACTION_WRITE)), "POST"))
  229. // HeadBucket
  230. bucket.Methods("HEAD").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.HeadBucketHandler, ACTION_READ)), "GET"))
  231. // PutBucket
  232. bucket.Methods("PUT").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.PutBucketHandler, ACTION_ADMIN)), "PUT"))
  233. // DeleteBucket
  234. bucket.Methods("DELETE").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.DeleteBucketHandler, ACTION_DELETE_BUCKET)), "DELETE"))
  235. // ListObjectsV1 (Legacy)
  236. bucket.Methods("GET").HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectsV1Handler, ACTION_LIST)), "LIST"))
  237. // raw buckets
  238. }
  239. // ListBuckets
  240. apiRouter.Methods("GET").Path("/").HandlerFunc(track(s3a.ListBucketsHandler, "LIST"))
  241. // NotFound
  242. apiRouter.NotFoundHandler = http.HandlerFunc(s3err.NotFoundHandler)
  243. }