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.

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