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.

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