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.

619 lines
18 KiB

3 years ago
6 years ago
7 years ago
7 years ago
7 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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
3 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
3 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
5 years ago
3 years ago
3 years ago
3 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
3 years ago
3 years ago
4 years ago
3 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 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
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. package s3api
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/json"
  6. "encoding/xml"
  7. "fmt"
  8. "github.com/aws/aws-sdk-go/service/s3"
  9. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  10. "github.com/seaweedfs/seaweedfs/weed/s3api/s3account"
  11. "github.com/seaweedfs/seaweedfs/weed/s3api/s3acl"
  12. "github.com/seaweedfs/seaweedfs/weed/security"
  13. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  14. "golang.org/x/exp/slices"
  15. "io"
  16. "net/http"
  17. "net/url"
  18. "strings"
  19. "time"
  20. "github.com/pquerna/cachecontrol/cacheobject"
  21. "github.com/seaweedfs/seaweedfs/weed/filer"
  22. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  23. "github.com/seaweedfs/seaweedfs/weed/glog"
  24. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  25. weed_server "github.com/seaweedfs/seaweedfs/weed/server"
  26. "github.com/seaweedfs/seaweedfs/weed/util"
  27. )
  28. const (
  29. deleteMultipleObjectsLimit = 1000
  30. )
  31. func mimeDetect(r *http.Request, dataReader io.Reader) io.ReadCloser {
  32. mimeBuffer := make([]byte, 512)
  33. size, _ := dataReader.Read(mimeBuffer)
  34. if size > 0 {
  35. r.Header.Set("Content-Type", http.DetectContentType(mimeBuffer[:size]))
  36. return io.NopCloser(io.MultiReader(bytes.NewReader(mimeBuffer[:size]), dataReader))
  37. }
  38. return io.NopCloser(dataReader)
  39. }
  40. func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) {
  41. // http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
  42. bucket, object := s3_constants.GetBucketAndObject(r)
  43. glog.V(3).Infof("PutObjectHandler %s %s", bucket, object)
  44. _, err := validateContentMd5(r.Header)
  45. if err != nil {
  46. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
  47. return
  48. }
  49. if r.Header.Get("Cache-Control") != "" {
  50. if _, err = cacheobject.ParseRequestCacheControl(r.Header.Get("Cache-Control")); err != nil {
  51. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
  52. return
  53. }
  54. }
  55. if r.Header.Get("Expires") != "" {
  56. if _, err = time.Parse(http.TimeFormat, r.Header.Get("Expires")); err != nil {
  57. s3err.WriteErrorResponse(w, r, s3err.ErrMalformedDate)
  58. return
  59. }
  60. }
  61. dataReader := r.Body
  62. rAuthType := getRequestAuthType(r)
  63. if s3a.iam.isEnabled() {
  64. var s3ErrCode s3err.ErrorCode
  65. var identity *Identity
  66. switch rAuthType {
  67. case authTypeStreamingSigned:
  68. dataReader, identity, s3ErrCode = s3a.iam.newSignV4ChunkedReader(r)
  69. case authTypeSignedV2, authTypePresignedV2:
  70. identity, s3ErrCode = s3a.iam.isReqAuthenticatedV2(r)
  71. case authTypePresigned, authTypeSigned:
  72. identity, s3ErrCode = s3a.iam.reqSignatureV4Verify(r)
  73. case authTypeAnonymous:
  74. identity = IdentityAnonymous
  75. }
  76. if s3ErrCode != s3err.ErrNone {
  77. s3err.WriteErrorResponse(w, r, s3ErrCode)
  78. return
  79. }
  80. if identity.AccountId != s3account.AccountAnonymous.Id {
  81. r.Header.Set(s3_constants.AmzAccountId, identity.AccountId)
  82. }
  83. } else {
  84. if authTypeStreamingSigned == rAuthType {
  85. s3err.WriteErrorResponse(w, r, s3err.ErrAuthNotSetup)
  86. return
  87. }
  88. }
  89. defer dataReader.Close()
  90. errCode := s3a.CheckAccessForPutObject(r, bucket, object)
  91. if errCode != s3err.ErrNone {
  92. s3err.WriteErrorResponse(w, r, errCode)
  93. return
  94. }
  95. objectContentType := r.Header.Get("Content-Type")
  96. if strings.HasSuffix(object, "/") && r.ContentLength == 0 {
  97. if err := s3a.mkdir(
  98. s3a.option.BucketsPath, bucket+strings.TrimSuffix(object, "/"),
  99. func(entry *filer_pb.Entry) {
  100. if objectContentType == "" {
  101. objectContentType = "httpd/unix-directory"
  102. }
  103. entry.Attributes.Mime = objectContentType
  104. }); err != nil {
  105. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  106. return
  107. }
  108. } else {
  109. uploadUrl := s3a.toFilerUrl(bucket, object)
  110. if objectContentType == "" {
  111. dataReader = mimeDetect(r, dataReader)
  112. }
  113. etag, errCode := s3a.putToFiler(r, uploadUrl, dataReader, "")
  114. if errCode != s3err.ErrNone {
  115. s3err.WriteErrorResponse(w, r, errCode)
  116. return
  117. }
  118. setEtag(w, etag)
  119. }
  120. writeSuccessResponseEmpty(w, r)
  121. }
  122. func urlEscapeObject(object string) string {
  123. t := urlPathEscape(removeDuplicateSlashes(object))
  124. if strings.HasPrefix(t, "/") {
  125. return t
  126. }
  127. return "/" + t
  128. }
  129. func urlPathEscape(object string) string {
  130. var escapedParts []string
  131. for _, part := range strings.Split(object, "/") {
  132. escapedParts = append(escapedParts, url.PathEscape(part))
  133. }
  134. return strings.Join(escapedParts, "/")
  135. }
  136. func removeDuplicateSlashes(object string) string {
  137. result := strings.Builder{}
  138. result.Grow(len(object))
  139. isLastSlash := false
  140. for _, r := range object {
  141. switch r {
  142. case '/':
  143. if !isLastSlash {
  144. result.WriteRune(r)
  145. }
  146. isLastSlash = true
  147. default:
  148. result.WriteRune(r)
  149. isLastSlash = false
  150. }
  151. }
  152. return result.String()
  153. }
  154. func (s3a *S3ApiServer) toFilerUrl(bucket, object string) string {
  155. object = urlPathEscape(removeDuplicateSlashes(object))
  156. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  157. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, object)
  158. return destUrl
  159. }
  160. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  161. bucket, object := s3_constants.GetBucketAndObject(r)
  162. glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
  163. errCode := s3a.checkBucketAccessForReadObject(r, bucket)
  164. if errCode != s3err.ErrNone {
  165. s3err.WriteErrorResponse(w, r, errCode)
  166. return
  167. }
  168. if strings.HasSuffix(r.URL.Path, "/") {
  169. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  170. return
  171. }
  172. destUrl := s3a.toFilerUrl(bucket, object)
  173. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  174. }
  175. // GetObjectAclHandler Put object ACL
  176. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjecthtml
  177. func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Request) {
  178. bucket, object := s3_constants.GetBucketAndObject(r)
  179. acp, errCode := s3a.checkAccessForReadObjectAcl(r, bucket, object)
  180. if errCode != s3err.ErrNone {
  181. s3err.WriteErrorResponse(w, r, errCode)
  182. return
  183. }
  184. result := &s3.PutBucketAclInput{
  185. AccessControlPolicy: acp,
  186. }
  187. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, &result)
  188. }
  189. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  190. bucket, object := s3_constants.GetBucketAndObject(r)
  191. glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
  192. destUrl := s3a.toFilerUrl(bucket, object)
  193. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  194. }
  195. func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
  196. bucket, object := s3_constants.GetBucketAndObject(r)
  197. glog.V(3).Infof("DeleteObjectHandler %s %s", bucket, object)
  198. destUrl := s3a.toFilerUrl(bucket, object)
  199. s3a.proxyToFiler(w, r, destUrl, true, func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  200. statusCode = http.StatusNoContent
  201. for k, v := range proxyResponse.Header {
  202. w.Header()[k] = v
  203. }
  204. w.WriteHeader(statusCode)
  205. return statusCode
  206. })
  207. }
  208. // / ObjectIdentifier carries key name for the object to delete.
  209. type ObjectIdentifier struct {
  210. ObjectName string `xml:"Key"`
  211. }
  212. // DeleteObjectsRequest - xml carrying the object key names which needs to be deleted.
  213. type DeleteObjectsRequest struct {
  214. // Element to enable quiet mode for the request
  215. Quiet bool
  216. // List of objects to be deleted
  217. Objects []ObjectIdentifier `xml:"Object"`
  218. }
  219. // DeleteError structure.
  220. type DeleteError struct {
  221. Code string
  222. Message string
  223. Key string
  224. }
  225. // DeleteObjectsResponse container for multiple object deletes.
  226. type DeleteObjectsResponse struct {
  227. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ DeleteResult" json:"-"`
  228. // Collection of all deleted objects
  229. DeletedObjects []ObjectIdentifier `xml:"Deleted,omitempty"`
  230. // Collection of errors deleting certain objects.
  231. Errors []DeleteError `xml:"Error,omitempty"`
  232. }
  233. // DeleteMultipleObjectsHandler - Delete multiple objects
  234. func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *http.Request) {
  235. bucket, _ := s3_constants.GetBucketAndObject(r)
  236. glog.V(3).Infof("DeleteMultipleObjectsHandler %s", bucket)
  237. deleteXMLBytes, err := io.ReadAll(r.Body)
  238. if err != nil {
  239. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  240. return
  241. }
  242. deleteObjects := &DeleteObjectsRequest{}
  243. if err := xml.Unmarshal(deleteXMLBytes, deleteObjects); err != nil {
  244. s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
  245. return
  246. }
  247. if len(deleteObjects.Objects) > deleteMultipleObjectsLimit {
  248. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxDeleteObjects)
  249. return
  250. }
  251. var deletedObjects []ObjectIdentifier
  252. var deleteErrors []DeleteError
  253. var auditLog *s3err.AccessLog
  254. directoriesWithDeletion := make(map[string]int)
  255. if s3err.Logger != nil {
  256. auditLog = s3err.GetAccessLog(r, http.StatusNoContent, s3err.ErrNone)
  257. }
  258. s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  259. // delete file entries
  260. for _, object := range deleteObjects.Objects {
  261. if object.ObjectName == "" {
  262. continue
  263. }
  264. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  265. parentDirectoryPath, entryName, isDeleteData, isRecursive := "", object.ObjectName, true, false
  266. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  267. entryName = object.ObjectName[lastSeparator+1:]
  268. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  269. }
  270. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  271. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  272. if err == nil {
  273. directoriesWithDeletion[parentDirectoryPath]++
  274. deletedObjects = append(deletedObjects, object)
  275. } else if strings.Contains(err.Error(), filer.MsgFailDelNonEmptyFolder) {
  276. deletedObjects = append(deletedObjects, object)
  277. } else {
  278. delete(directoriesWithDeletion, parentDirectoryPath)
  279. deleteErrors = append(deleteErrors, DeleteError{
  280. Code: "",
  281. Message: err.Error(),
  282. Key: object.ObjectName,
  283. })
  284. }
  285. if auditLog != nil {
  286. auditLog.Key = entryName
  287. s3err.PostAccessLog(*auditLog)
  288. }
  289. }
  290. // purge empty folders, only checking folders with deletions
  291. for len(directoriesWithDeletion) > 0 {
  292. directoriesWithDeletion = s3a.doDeleteEmptyDirectories(client, directoriesWithDeletion)
  293. }
  294. return nil
  295. })
  296. deleteResp := DeleteObjectsResponse{}
  297. if !deleteObjects.Quiet {
  298. deleteResp.DeletedObjects = deletedObjects
  299. }
  300. deleteResp.Errors = deleteErrors
  301. writeSuccessResponseXML(w, r, deleteResp)
  302. }
  303. func (s3a *S3ApiServer) doDeleteEmptyDirectories(client filer_pb.SeaweedFilerClient, directoriesWithDeletion map[string]int) (newDirectoriesWithDeletion map[string]int) {
  304. var allDirs []string
  305. for dir := range directoriesWithDeletion {
  306. allDirs = append(allDirs, dir)
  307. }
  308. slices.SortFunc(allDirs, func(a, b string) bool {
  309. return len(a) > len(b)
  310. })
  311. newDirectoriesWithDeletion = make(map[string]int)
  312. for _, dir := range allDirs {
  313. parentDir, dirName := util.FullPath(dir).DirAndName()
  314. if parentDir == s3a.option.BucketsPath {
  315. continue
  316. }
  317. if err := doDeleteEntry(client, parentDir, dirName, false, false); err != nil {
  318. glog.V(4).Infof("directory %s has %d deletion but still not empty: %v", dir, directoriesWithDeletion[dir], err)
  319. } else {
  320. newDirectoriesWithDeletion[parentDir]++
  321. }
  322. }
  323. return
  324. }
  325. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, isWrite bool, responseFn func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int)) {
  326. glog.V(3).Infof("s3 proxying %s to %s", r.Method, destUrl)
  327. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  328. if err != nil {
  329. glog.Errorf("NewRequest %s: %v", destUrl, err)
  330. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  331. return
  332. }
  333. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  334. for k, v := range r.URL.Query() {
  335. if _, ok := s3_constants.PassThroughHeaders[strings.ToLower(k)]; ok {
  336. proxyReq.Header[k] = v
  337. }
  338. }
  339. for header, values := range r.Header {
  340. proxyReq.Header[header] = values
  341. }
  342. // ensure that the Authorization header is overriding any previous
  343. // Authorization header which might be already present in proxyReq
  344. s3a.maybeAddFilerJwtAuthorization(proxyReq, isWrite)
  345. resp, postErr := s3a.client.Do(proxyReq)
  346. if postErr != nil {
  347. glog.Errorf("post to filer: %v", postErr)
  348. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  349. return
  350. }
  351. defer util.CloseResponse(resp)
  352. switch resp.StatusCode {
  353. case http.StatusPreconditionFailed:
  354. s3err.WriteErrorResponse(w, r, s3err.ErrPreconditionFailed)
  355. return
  356. case http.StatusRequestedRangeNotSatisfiable:
  357. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
  358. return
  359. case http.StatusForbidden:
  360. s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
  361. return
  362. default:
  363. }
  364. if r.Method == "DELETE" {
  365. if resp.StatusCode == http.StatusNotFound {
  366. // this is normal
  367. responseStatusCode := responseFn(resp, w)
  368. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  369. return
  370. }
  371. }
  372. if resp.StatusCode == http.StatusNotFound {
  373. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  374. return
  375. }
  376. if resp.Header.Get(s3_constants.X_SeaweedFS_Header_Directory_Key) == "true" {
  377. responseStatusCode := responseFn(resp, w)
  378. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  379. return
  380. }
  381. // when HEAD a directory, it should be reported as no such key
  382. // https://github.com/seaweedfs/seaweedfs/issues/3457
  383. if resp.ContentLength == -1 && resp.StatusCode != http.StatusNotModified {
  384. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  385. return
  386. }
  387. setUserMetadataKeyToLowercase(resp)
  388. responseStatusCode := responseFn(resp, w)
  389. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  390. }
  391. func setUserMetadataKeyToLowercase(resp *http.Response) {
  392. for key, value := range resp.Header {
  393. if strings.HasPrefix(key, s3_constants.AmzUserMetaPrefix) {
  394. resp.Header[strings.ToLower(key)] = value
  395. delete(resp.Header, key)
  396. }
  397. }
  398. }
  399. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  400. for k, v := range proxyResponse.Header {
  401. w.Header()[k] = v
  402. }
  403. if proxyResponse.Header.Get("Content-Range") != "" && proxyResponse.StatusCode == 200 {
  404. w.WriteHeader(http.StatusPartialContent)
  405. statusCode = http.StatusPartialContent
  406. } else {
  407. statusCode = proxyResponse.StatusCode
  408. }
  409. w.WriteHeader(statusCode)
  410. buf := mem.Allocate(128 * 1024)
  411. defer mem.Free(buf)
  412. if n, err := io.CopyBuffer(w, proxyResponse.Body, buf); err != nil {
  413. glog.V(1).Infof("passthrough response read %d bytes: %v", n, err)
  414. }
  415. return statusCode
  416. }
  417. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader, destination string) (etag string, code s3err.ErrorCode) {
  418. hash := md5.New()
  419. var body = io.TeeReader(dataReader, hash)
  420. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  421. if err != nil {
  422. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  423. return "", s3err.ErrInternalError
  424. }
  425. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  426. if destination != "" {
  427. proxyReq.Header.Set(s3_constants.SeaweedStorageDestinationHeader, destination)
  428. }
  429. for header, values := range r.Header {
  430. for _, value := range values {
  431. proxyReq.Header.Add(header, value)
  432. }
  433. }
  434. // ensure that the Authorization header is overriding any previous
  435. // Authorization header which might be already present in proxyReq
  436. s3a.maybeAddFilerJwtAuthorization(proxyReq, true)
  437. resp, postErr := s3a.client.Do(proxyReq)
  438. if postErr != nil {
  439. glog.Errorf("post to filer: %v", postErr)
  440. return "", s3err.ErrInternalError
  441. }
  442. defer resp.Body.Close()
  443. etag = fmt.Sprintf("%x", hash.Sum(nil))
  444. resp_body, ra_err := io.ReadAll(resp.Body)
  445. if ra_err != nil {
  446. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  447. return etag, s3err.ErrInternalError
  448. }
  449. var ret weed_server.FilerPostResult
  450. unmarshal_err := json.Unmarshal(resp_body, &ret)
  451. if unmarshal_err != nil {
  452. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  453. return "", s3err.ErrInternalError
  454. }
  455. if ret.Error != "" {
  456. glog.Errorf("upload to filer error: %v", ret.Error)
  457. return "", filerErrorToS3Error(ret.Error)
  458. }
  459. return etag, s3err.ErrNone
  460. }
  461. func setEtag(w http.ResponseWriter, etag string) {
  462. if etag != "" {
  463. if strings.HasPrefix(etag, "\"") {
  464. w.Header()["ETag"] = []string{etag}
  465. } else {
  466. w.Header()["ETag"] = []string{"\"" + etag + "\""}
  467. }
  468. }
  469. }
  470. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  471. switch {
  472. case strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory"):
  473. return s3err.ErrExistingObjectIsDirectory
  474. case strings.HasSuffix(errString, "is a file"):
  475. return s3err.ErrExistingObjectIsFile
  476. default:
  477. return s3err.ErrInternalError
  478. }
  479. }
  480. func (s3a *S3ApiServer) maybeAddFilerJwtAuthorization(r *http.Request, isWrite bool) {
  481. encodedJwt := s3a.maybeGetFilerJwtAuthorizationToken(isWrite)
  482. if encodedJwt == "" {
  483. return
  484. }
  485. r.Header.Set("Authorization", "BEARER "+string(encodedJwt))
  486. }
  487. func (s3a *S3ApiServer) maybeGetFilerJwtAuthorizationToken(isWrite bool) string {
  488. var encodedJwt security.EncodedJwt
  489. if isWrite {
  490. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.SigningKey, s3a.filerGuard.ExpiresAfterSec)
  491. } else {
  492. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.ReadSigningKey, s3a.filerGuard.ReadExpiresAfterSec)
  493. }
  494. return string(encodedJwt)
  495. }
  496. // PutObjectAclHandler Put object ACL
  497. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjecthtml
  498. func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Request) {
  499. bucket, object := s3_constants.GetBucketAndObject(r)
  500. accountId := s3acl.GetAccountId(r)
  501. bucketMetadata, objectEntry, objectOwner, errCode := s3a.checkAccessForWriteObjectAcl(accountId, bucket, object)
  502. if errCode != s3err.ErrNone {
  503. s3err.WriteErrorResponse(w, r, errCode)
  504. return
  505. }
  506. grants, errCode := s3acl.ExtractAcl(r, s3a.accountManager, bucketMetadata.ObjectOwnership, *bucketMetadata.Owner.ID, objectOwner, accountId)
  507. if errCode != s3err.ErrNone {
  508. s3err.WriteErrorResponse(w, r, errCode)
  509. return
  510. }
  511. errCode = s3acl.AssembleEntryWithAcp(objectEntry, objectOwner, grants)
  512. if errCode != s3err.ErrNone {
  513. return
  514. }
  515. err := updateObjectEntry(s3a, bucket, object, objectEntry)
  516. if err != nil {
  517. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  518. return
  519. }
  520. w.WriteHeader(http.StatusOK)
  521. }