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.

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