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.

476 lines
14 KiB

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