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.

540 lines
16 KiB

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