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.

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