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.

484 lines
14 KiB

3 years ago
6 years ago
7 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
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
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
4 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
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/chrislusf/seaweedfs/weed/s3api/s3_constants"
  9. "github.com/chrislusf/seaweedfs/weed/security"
  10. "github.com/chrislusf/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/chrislusf/seaweedfs/weed/filer"
  18. "github.com/pquerna/cachecontrol/cacheobject"
  19. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  20. "github.com/chrislusf/seaweedfs/weed/glog"
  21. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  22. weed_server "github.com/chrislusf/seaweedfs/weed/server"
  23. "github.com/chrislusf/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 (s3a *S3ApiServer) toFilerUrl(bucket, object string) string {
  114. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  115. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, urlPathEscape(object))
  116. return destUrl
  117. }
  118. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  119. bucket, object := s3_constants.GetBucketAndObject(r)
  120. glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
  121. if strings.HasSuffix(r.URL.Path, "/") {
  122. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  123. return
  124. }
  125. destUrl := s3a.toFilerUrl(bucket, object)
  126. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  127. }
  128. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  129. bucket, object := s3_constants.GetBucketAndObject(r)
  130. glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
  131. destUrl := s3a.toFilerUrl(bucket, object)
  132. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  133. }
  134. func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
  135. bucket, object := s3_constants.GetBucketAndObject(r)
  136. glog.V(3).Infof("DeleteObjectHandler %s %s", bucket, object)
  137. destUrl := s3a.toFilerUrl(bucket, object)
  138. s3a.proxyToFiler(w, r, destUrl, true, func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  139. statusCode = http.StatusNoContent
  140. for k, v := range proxyResponse.Header {
  141. w.Header()[k] = v
  142. }
  143. w.WriteHeader(statusCode)
  144. return statusCode
  145. })
  146. }
  147. // / ObjectIdentifier carries key name for the object to delete.
  148. type ObjectIdentifier struct {
  149. ObjectName string `xml:"Key"`
  150. }
  151. // DeleteObjectsRequest - xml carrying the object key names which needs to be deleted.
  152. type DeleteObjectsRequest struct {
  153. // Element to enable quiet mode for the request
  154. Quiet bool
  155. // List of objects to be deleted
  156. Objects []ObjectIdentifier `xml:"Object"`
  157. }
  158. // DeleteError structure.
  159. type DeleteError struct {
  160. Code string
  161. Message string
  162. Key string
  163. }
  164. // DeleteObjectsResponse container for multiple object deletes.
  165. type DeleteObjectsResponse struct {
  166. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ DeleteResult" json:"-"`
  167. // Collection of all deleted objects
  168. DeletedObjects []ObjectIdentifier `xml:"Deleted,omitempty"`
  169. // Collection of errors deleting certain objects.
  170. Errors []DeleteError `xml:"Error,omitempty"`
  171. }
  172. // DeleteMultipleObjectsHandler - Delete multiple objects
  173. func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *http.Request) {
  174. bucket, _ := s3_constants.GetBucketAndObject(r)
  175. glog.V(3).Infof("DeleteMultipleObjectsHandler %s", bucket)
  176. deleteXMLBytes, err := io.ReadAll(r.Body)
  177. if err != nil {
  178. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  179. return
  180. }
  181. deleteObjects := &DeleteObjectsRequest{}
  182. if err := xml.Unmarshal(deleteXMLBytes, deleteObjects); err != nil {
  183. s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
  184. return
  185. }
  186. if len(deleteObjects.Objects) > deleteMultipleObjectsLimmit {
  187. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxDeleteObjects)
  188. return
  189. }
  190. var deletedObjects []ObjectIdentifier
  191. var deleteErrors []DeleteError
  192. var auditLog *s3err.AccessLog
  193. directoriesWithDeletion := make(map[string]int)
  194. if s3err.Logger != nil {
  195. auditLog = s3err.GetAccessLog(r, http.StatusNoContent, s3err.ErrNone)
  196. }
  197. s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  198. // delete file entries
  199. for _, object := range deleteObjects.Objects {
  200. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  201. parentDirectoryPath, entryName, isDeleteData, isRecursive := "", object.ObjectName, true, false
  202. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  203. entryName = object.ObjectName[lastSeparator+1:]
  204. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  205. }
  206. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  207. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  208. if err == nil {
  209. directoriesWithDeletion[parentDirectoryPath]++
  210. deletedObjects = append(deletedObjects, object)
  211. } else if strings.Contains(err.Error(), filer.MsgFailDelNonEmptyFolder) {
  212. deletedObjects = append(deletedObjects, object)
  213. } else {
  214. delete(directoriesWithDeletion, parentDirectoryPath)
  215. deleteErrors = append(deleteErrors, DeleteError{
  216. Code: "",
  217. Message: err.Error(),
  218. Key: object.ObjectName,
  219. })
  220. }
  221. if auditLog != nil {
  222. auditLog.Key = entryName
  223. s3err.PostAccessLog(*auditLog)
  224. }
  225. }
  226. // purge empty folders, only checking folders with deletions
  227. for len(directoriesWithDeletion) > 0 {
  228. directoriesWithDeletion = s3a.doDeleteEmptyDirectories(client, directoriesWithDeletion)
  229. }
  230. return nil
  231. })
  232. deleteResp := DeleteObjectsResponse{}
  233. if !deleteObjects.Quiet {
  234. deleteResp.DeletedObjects = deletedObjects
  235. }
  236. deleteResp.Errors = deleteErrors
  237. writeSuccessResponseXML(w, r, deleteResp)
  238. }
  239. func (s3a *S3ApiServer) doDeleteEmptyDirectories(client filer_pb.SeaweedFilerClient, directoriesWithDeletion map[string]int) (newDirectoriesWithDeletion map[string]int) {
  240. var allDirs []string
  241. for dir, _ := range directoriesWithDeletion {
  242. allDirs = append(allDirs, dir)
  243. }
  244. slices.SortFunc(allDirs, func(a, b string) bool {
  245. return len(a) > len(b)
  246. })
  247. newDirectoriesWithDeletion = make(map[string]int)
  248. for _, dir := range allDirs {
  249. parentDir, dirName := util.FullPath(dir).DirAndName()
  250. if parentDir == s3a.option.BucketsPath {
  251. continue
  252. }
  253. if err := doDeleteEntry(client, parentDir, dirName, false, false); err != nil {
  254. glog.V(4).Infof("directory %s has %d deletion but still not empty: %v", dir, directoriesWithDeletion[dir], err)
  255. } else {
  256. newDirectoriesWithDeletion[parentDir]++
  257. }
  258. }
  259. return
  260. }
  261. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, isWrite bool, responseFn func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int)) {
  262. glog.V(3).Infof("s3 proxying %s to %s", r.Method, destUrl)
  263. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  264. if err != nil {
  265. glog.Errorf("NewRequest %s: %v", destUrl, err)
  266. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  267. return
  268. }
  269. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  270. for k, v := range r.URL.Query() {
  271. if _, ok := s3_constants.PassThroughHeaders[strings.ToLower(k)]; ok {
  272. proxyReq.Header[k] = v
  273. }
  274. }
  275. for header, values := range r.Header {
  276. proxyReq.Header[header] = values
  277. }
  278. // ensure that the Authorization header is overriding any previous
  279. // Authorization header which might be already present in proxyReq
  280. s3a.maybeAddFilerJwtAuthorization(proxyReq, isWrite)
  281. resp, postErr := s3a.client.Do(proxyReq)
  282. if postErr != nil {
  283. glog.Errorf("post to filer: %v", postErr)
  284. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  285. return
  286. }
  287. defer util.CloseResponse(resp)
  288. if resp.StatusCode == http.StatusPreconditionFailed {
  289. s3err.WriteErrorResponse(w, r, s3err.ErrPreconditionFailed)
  290. return
  291. }
  292. if resp.StatusCode == http.StatusRequestedRangeNotSatisfiable {
  293. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
  294. return
  295. }
  296. if (resp.ContentLength == -1 || resp.StatusCode == 404) && resp.StatusCode != 304 {
  297. if r.Method != "DELETE" {
  298. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  299. return
  300. }
  301. }
  302. responseStatusCode := responseFn(resp, w)
  303. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  304. }
  305. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  306. for k, v := range proxyResponse.Header {
  307. w.Header()[k] = v
  308. }
  309. if proxyResponse.Header.Get("Content-Range") != "" && proxyResponse.StatusCode == 200 {
  310. w.WriteHeader(http.StatusPartialContent)
  311. statusCode = http.StatusPartialContent
  312. } else {
  313. statusCode = proxyResponse.StatusCode
  314. }
  315. w.WriteHeader(statusCode)
  316. buf := mem.Allocate(128 * 1024)
  317. defer mem.Free(buf)
  318. if n, err := io.CopyBuffer(w, proxyResponse.Body, buf); err != nil {
  319. glog.V(1).Infof("passthrough response read %d bytes: %v", n, err)
  320. }
  321. return statusCode
  322. }
  323. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader, destination string) (etag string, code s3err.ErrorCode) {
  324. hash := md5.New()
  325. var body = io.TeeReader(dataReader, hash)
  326. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  327. if err != nil {
  328. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  329. return "", s3err.ErrInternalError
  330. }
  331. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  332. if destination != "" {
  333. proxyReq.Header.Set(s3_constants.SeaweedStorageDestinationHeader, destination)
  334. }
  335. for header, values := range r.Header {
  336. for _, value := range values {
  337. proxyReq.Header.Add(header, value)
  338. }
  339. }
  340. // ensure that the Authorization header is overriding any previous
  341. // Authorization header which might be already present in proxyReq
  342. s3a.maybeAddFilerJwtAuthorization(proxyReq, true)
  343. resp, postErr := s3a.client.Do(proxyReq)
  344. if postErr != nil {
  345. glog.Errorf("post to filer: %v", postErr)
  346. return "", s3err.ErrInternalError
  347. }
  348. defer resp.Body.Close()
  349. etag = fmt.Sprintf("%x", hash.Sum(nil))
  350. resp_body, ra_err := io.ReadAll(resp.Body)
  351. if ra_err != nil {
  352. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  353. return etag, s3err.ErrInternalError
  354. }
  355. var ret weed_server.FilerPostResult
  356. unmarshal_err := json.Unmarshal(resp_body, &ret)
  357. if unmarshal_err != nil {
  358. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  359. return "", s3err.ErrInternalError
  360. }
  361. if ret.Error != "" {
  362. glog.Errorf("upload to filer error: %v", ret.Error)
  363. return "", filerErrorToS3Error(ret.Error)
  364. }
  365. return etag, s3err.ErrNone
  366. }
  367. func setEtag(w http.ResponseWriter, etag string) {
  368. if etag != "" {
  369. if strings.HasPrefix(etag, "\"") {
  370. w.Header()["ETag"] = []string{etag}
  371. } else {
  372. w.Header()["ETag"] = []string{"\"" + etag + "\""}
  373. }
  374. }
  375. }
  376. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  377. switch {
  378. case strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory"):
  379. return s3err.ErrExistingObjectIsDirectory
  380. case strings.HasSuffix(errString, "is a file"):
  381. return s3err.ErrExistingObjectIsFile
  382. default:
  383. return s3err.ErrInternalError
  384. }
  385. }
  386. func (s3a *S3ApiServer) maybeAddFilerJwtAuthorization(r *http.Request, isWrite bool) {
  387. encodedJwt := s3a.maybeGetFilerJwtAuthorizationToken(isWrite)
  388. if encodedJwt == "" {
  389. return
  390. }
  391. r.Header.Set("Authorization", "BEARER "+string(encodedJwt))
  392. }
  393. func (s3a *S3ApiServer) maybeGetFilerJwtAuthorizationToken(isWrite bool) string {
  394. var encodedJwt security.EncodedJwt
  395. if isWrite {
  396. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.SigningKey, s3a.filerGuard.ExpiresAfterSec)
  397. } else {
  398. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.ReadSigningKey, s3a.filerGuard.ReadExpiresAfterSec)
  399. }
  400. return string(encodedJwt)
  401. }