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.

463 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
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
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
FEATURE: add JWT to HTTP endpoints of Filer and use them in S3 Client - one JWT for reading and one for writing, analogous to how the JWT between Master and Volume Server works - I did not implement IP `whiteList` parameter on the filer Additionally, because http_util.DownloadFile now sets the JWT, the `download` command should now work when `jwt.signing.read` is configured. By looking at the code, I think this case did not work before. ## Docs to be adjusted after a release Page `Amazon-S3-API`: ``` # Authentication with Filer You can use mTLS for the gRPC connection between S3-API-Proxy and the filer, as explained in [Security-Configuration](Security-Configuration) - controlled by the `grpc.*` configuration in `security.toml`. Starting with version XX, it is also possible to authenticate the HTTP operations between the S3-API-Proxy and the Filer (especially uploading new files). This is configured by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. With both configurations (gRPC and JWT), it is possible to have Filer and S3 communicate in fully authenticated fashion; so Filer will reject any unauthenticated communication. ``` Page `Security Overview`: ``` The following items are not covered, yet: - master server http REST services Starting with version XX, the Filer HTTP REST services can be secured with a JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. ... Before version XX: "weed filer -disableHttp", disable http operations, only gRPC operations are allowed. This works with "weed mount" by FUSE. It does **not work** with the [S3 Gateway](Amazon S3 API), as this does HTTP calls to the Filer. Starting with version XX: secured by JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. **This now works with the [S3 Gateway](Amazon S3 API).** ... # Securing Filer HTTP with JWT To enable JWT-based access control for the Filer, 1. generate `security.toml` file by `weed scaffold -config=security` 2. set `filer_jwt.signing.key` to a secret string - and optionally filer_jwt.signing.read.key` as well to a secret string 3. copy the same `security.toml` file to the filers and all S3 proxies. If `filer_jwt.signing.key` is configured: When sending upload/update/delete HTTP operations to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.key`. If `filer_jwt.signing.read.key` is configured: When sending GET or HEAD requests to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.read.key`. The S3 API Gateway reads the above JWT keys and sends authenticated HTTP requests to the filer. ``` Page `Security Configuration`: ``` (update scaffold file) ... [filer_jwt.signing] key = "blahblahblahblah" [filer_jwt.signing.read] key = "blahblahblahblah" ``` Resolves: #158
3 years ago
3 years ago
FEATURE: add JWT to HTTP endpoints of Filer and use them in S3 Client - one JWT for reading and one for writing, analogous to how the JWT between Master and Volume Server works - I did not implement IP `whiteList` parameter on the filer Additionally, because http_util.DownloadFile now sets the JWT, the `download` command should now work when `jwt.signing.read` is configured. By looking at the code, I think this case did not work before. ## Docs to be adjusted after a release Page `Amazon-S3-API`: ``` # Authentication with Filer You can use mTLS for the gRPC connection between S3-API-Proxy and the filer, as explained in [Security-Configuration](Security-Configuration) - controlled by the `grpc.*` configuration in `security.toml`. Starting with version XX, it is also possible to authenticate the HTTP operations between the S3-API-Proxy and the Filer (especially uploading new files). This is configured by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. With both configurations (gRPC and JWT), it is possible to have Filer and S3 communicate in fully authenticated fashion; so Filer will reject any unauthenticated communication. ``` Page `Security Overview`: ``` The following items are not covered, yet: - master server http REST services Starting with version XX, the Filer HTTP REST services can be secured with a JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. ... Before version XX: "weed filer -disableHttp", disable http operations, only gRPC operations are allowed. This works with "weed mount" by FUSE. It does **not work** with the [S3 Gateway](Amazon S3 API), as this does HTTP calls to the Filer. Starting with version XX: secured by JWT, by setting `filer_jwt.signing.key` and `filer_jwt.signing.read.key` in `security.toml`. **This now works with the [S3 Gateway](Amazon S3 API).** ... # Securing Filer HTTP with JWT To enable JWT-based access control for the Filer, 1. generate `security.toml` file by `weed scaffold -config=security` 2. set `filer_jwt.signing.key` to a secret string - and optionally filer_jwt.signing.read.key` as well to a secret string 3. copy the same `security.toml` file to the filers and all S3 proxies. If `filer_jwt.signing.key` is configured: When sending upload/update/delete HTTP operations to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.key`. If `filer_jwt.signing.read.key` is configured: When sending GET or HEAD requests to a filer server, the request header `Authorization` should be the JWT string (`Authorization: Bearer [JwtToken]`). The operation is authorized after the filer validates the JWT with `filer_jwt.signing.read.key`. The S3 API Gateway reads the above JWT keys and sends authenticated HTTP requests to the filer. ``` Page `Security Configuration`: ``` (update scaffold file) ... [filer_jwt.signing] key = "blahblahblahblah" [filer_jwt.signing.read] key = "blahblahblahblah" ``` Resolves: #158
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
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. "io"
  10. "net/http"
  11. "net/url"
  12. "sort"
  13. "strings"
  14. "time"
  15. "github.com/chrislusf/seaweedfs/weed/filer"
  16. "github.com/pquerna/cachecontrol/cacheobject"
  17. xhttp "github.com/chrislusf/seaweedfs/weed/s3api/http"
  18. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  19. "github.com/chrislusf/seaweedfs/weed/glog"
  20. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  21. weed_server "github.com/chrislusf/seaweedfs/weed/server"
  22. "github.com/chrislusf/seaweedfs/weed/util"
  23. )
  24. var (
  25. client *http.Client
  26. )
  27. func init() {
  28. client = &http.Client{Transport: &http.Transport{
  29. MaxIdleConns: 1024,
  30. MaxIdleConnsPerHost: 1024,
  31. }}
  32. }
  33. func mimeDetect(r *http.Request, dataReader io.Reader) io.ReadCloser {
  34. mimeBuffer := make([]byte, 512)
  35. size, _ := dataReader.Read(mimeBuffer)
  36. if size > 0 {
  37. r.Header.Set("Content-Type", http.DetectContentType(mimeBuffer[:size]))
  38. return io.NopCloser(io.MultiReader(bytes.NewReader(mimeBuffer[:size]), dataReader))
  39. }
  40. return io.NopCloser(dataReader)
  41. }
  42. func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) {
  43. // http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
  44. bucket, object := xhttp.GetBucketAndObject(r)
  45. glog.V(3).Infof("PutObjectHandler %s %s", bucket, object)
  46. _, err := validateContentMd5(r.Header)
  47. if err != nil {
  48. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
  49. return
  50. }
  51. if r.Header.Get("Cache-Control") != "" {
  52. if _, err = cacheobject.ParseRequestCacheControl(r.Header.Get("Cache-Control")); err != nil {
  53. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
  54. return
  55. }
  56. }
  57. if r.Header.Get("Expires") != "" {
  58. if _, err = time.Parse(http.TimeFormat, r.Header.Get("Expires")); err != nil {
  59. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
  60. return
  61. }
  62. }
  63. dataReader := r.Body
  64. rAuthType := getRequestAuthType(r)
  65. if s3a.iam.isEnabled() {
  66. var s3ErrCode s3err.ErrorCode
  67. switch rAuthType {
  68. case authTypeStreamingSigned:
  69. dataReader, s3ErrCode = s3a.iam.newSignV4ChunkedReader(r)
  70. case authTypeSignedV2, authTypePresignedV2:
  71. _, s3ErrCode = s3a.iam.isReqAuthenticatedV2(r)
  72. case authTypePresigned, authTypeSigned:
  73. _, s3ErrCode = s3a.iam.reqSignatureV4Verify(r)
  74. }
  75. if s3ErrCode != s3err.ErrNone {
  76. s3err.WriteErrorResponse(w, r, s3ErrCode)
  77. return
  78. }
  79. } else {
  80. if authTypeStreamingSigned == rAuthType {
  81. s3err.WriteErrorResponse(w, r, s3err.ErrAuthNotSetup)
  82. return
  83. }
  84. }
  85. defer dataReader.Close()
  86. if strings.HasSuffix(object, "/") {
  87. if err := s3a.mkdir(s3a.option.BucketsPath, bucket+object, nil); err != nil {
  88. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  89. return
  90. }
  91. } else {
  92. uploadUrl := fmt.Sprintf("http://%s%s/%s%s", s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, urlPathEscape(object))
  93. if r.Header.Get("Content-Type") == "" {
  94. dataReader = mimeDetect(r, dataReader)
  95. }
  96. etag, errCode := s3a.putToFiler(r, uploadUrl, dataReader)
  97. if errCode != s3err.ErrNone {
  98. s3err.WriteErrorResponse(w, r, errCode)
  99. return
  100. }
  101. setEtag(w, etag)
  102. }
  103. writeSuccessResponseEmpty(w, r)
  104. }
  105. func urlPathEscape(object string) string {
  106. var escapedParts []string
  107. for _, part := range strings.Split(object, "/") {
  108. escapedParts = append(escapedParts, url.PathEscape(part))
  109. }
  110. return strings.Join(escapedParts, "/")
  111. }
  112. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  113. bucket, object := xhttp.GetBucketAndObject(r)
  114. glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
  115. if strings.HasSuffix(r.URL.Path, "/") {
  116. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  117. return
  118. }
  119. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  120. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, urlPathEscape(object))
  121. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  122. }
  123. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  124. bucket, object := xhttp.GetBucketAndObject(r)
  125. glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
  126. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  127. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, urlPathEscape(object))
  128. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  129. }
  130. func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
  131. bucket, object := xhttp.GetBucketAndObject(r)
  132. glog.V(3).Infof("DeleteObjectHandler %s %s", bucket, object)
  133. destUrl := fmt.Sprintf("http://%s%s/%s%s?recursive=true",
  134. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, urlPathEscape(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. var deletedObjects []ObjectIdentifier
  184. var deleteErrors []DeleteError
  185. var auditLog *s3err.AccessLog
  186. directoriesWithDeletion := make(map[string]int)
  187. if s3err.Logger != nil {
  188. auditLog = s3err.GetAccessLog(r, http.StatusNoContent, s3err.ErrNone)
  189. }
  190. s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  191. // delete file entries
  192. for _, object := range deleteObjects.Objects {
  193. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  194. parentDirectoryPath, entryName, isDeleteData, isRecursive := "", object.ObjectName, true, false
  195. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  196. entryName = object.ObjectName[lastSeparator+1:]
  197. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  198. }
  199. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  200. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  201. if err == nil {
  202. directoriesWithDeletion[parentDirectoryPath]++
  203. deletedObjects = append(deletedObjects, object)
  204. } else if strings.Contains(err.Error(), filer.MsgFailDelNonEmptyFolder) {
  205. deletedObjects = append(deletedObjects, object)
  206. } else {
  207. delete(directoriesWithDeletion, parentDirectoryPath)
  208. deleteErrors = append(deleteErrors, DeleteError{
  209. Code: "",
  210. Message: err.Error(),
  211. Key: object.ObjectName,
  212. })
  213. }
  214. if auditLog != nil {
  215. auditLog.Key = entryName
  216. s3err.PostAccessLog(*auditLog)
  217. }
  218. }
  219. // purge empty folders, only checking folders with deletions
  220. for len(directoriesWithDeletion) > 0 {
  221. directoriesWithDeletion = s3a.doDeleteEmptyDirectories(client, directoriesWithDeletion)
  222. }
  223. return nil
  224. })
  225. deleteResp := DeleteObjectsResponse{}
  226. if !deleteObjects.Quiet {
  227. deleteResp.DeletedObjects = deletedObjects
  228. }
  229. deleteResp.Errors = deleteErrors
  230. writeSuccessResponseXML(w, r, deleteResp)
  231. }
  232. func (s3a *S3ApiServer) doDeleteEmptyDirectories(client filer_pb.SeaweedFilerClient, directoriesWithDeletion map[string]int) (newDirectoriesWithDeletion map[string]int) {
  233. var allDirs []string
  234. for dir, _ := range directoriesWithDeletion {
  235. allDirs = append(allDirs, dir)
  236. }
  237. sort.Slice(allDirs, func(i, j int) bool {
  238. return len(allDirs[i]) > len(allDirs[j])
  239. })
  240. newDirectoriesWithDeletion = make(map[string]int)
  241. for _, dir := range allDirs {
  242. parentDir, dirName := util.FullPath(dir).DirAndName()
  243. if parentDir == s3a.option.BucketsPath {
  244. continue
  245. }
  246. if err := doDeleteEntry(client, parentDir, dirName, false, false); err != nil {
  247. glog.V(4).Infof("directory %s has %d deletion but still not empty: %v", dir, directoriesWithDeletion[dir], err)
  248. } else {
  249. newDirectoriesWithDeletion[parentDir]++
  250. }
  251. }
  252. return
  253. }
  254. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, isWrite bool, responseFn func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int)) {
  255. glog.V(3).Infof("s3 proxying %s to %s", r.Method, destUrl)
  256. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  257. if err != nil {
  258. glog.Errorf("NewRequest %s: %v", destUrl, err)
  259. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  260. return
  261. }
  262. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  263. for k, v := range r.URL.Query() {
  264. if _, ok := xhttp.PassThroughHeaders[strings.ToLower(k)]; ok {
  265. proxyReq.Header[k] = v
  266. }
  267. }
  268. for header, values := range r.Header {
  269. proxyReq.Header[header] = values
  270. }
  271. // ensure that the Authorization header is overriding any previous
  272. // Authorization header which might be already present in proxyReq
  273. s3a.maybeAddFilerJwtAuthorization(proxyReq, isWrite)
  274. resp, postErr := client.Do(proxyReq)
  275. if postErr != nil {
  276. glog.Errorf("post to filer: %v", postErr)
  277. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  278. return
  279. }
  280. defer util.CloseResponse(resp)
  281. if resp.StatusCode == http.StatusPreconditionFailed {
  282. s3err.WriteErrorResponse(w, r, s3err.ErrPreconditionFailed)
  283. return
  284. }
  285. if (resp.ContentLength == -1 || resp.StatusCode == 404) && resp.StatusCode != 304 {
  286. if r.Method != "DELETE" {
  287. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  288. return
  289. }
  290. }
  291. responseStatusCode := responseFn(resp, w)
  292. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  293. }
  294. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  295. for k, v := range proxyResponse.Header {
  296. w.Header()[k] = v
  297. }
  298. if proxyResponse.Header.Get("Content-Range") != "" && proxyResponse.StatusCode == 200 {
  299. w.WriteHeader(http.StatusPartialContent)
  300. statusCode = http.StatusPartialContent
  301. } else {
  302. statusCode = proxyResponse.StatusCode
  303. }
  304. w.WriteHeader(statusCode)
  305. if n, err := io.Copy(w, proxyResponse.Body); err != nil {
  306. glog.V(1).Infof("passthrough response read %d bytes: %v", n, err)
  307. }
  308. return statusCode
  309. }
  310. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader) (etag string, code s3err.ErrorCode) {
  311. hash := md5.New()
  312. var body = io.TeeReader(dataReader, hash)
  313. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  314. if err != nil {
  315. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  316. return "", s3err.ErrInternalError
  317. }
  318. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  319. for header, values := range r.Header {
  320. for _, value := range values {
  321. proxyReq.Header.Add(header, value)
  322. }
  323. }
  324. // ensure that the Authorization header is overriding any previous
  325. // Authorization header which might be already present in proxyReq
  326. s3a.maybeAddFilerJwtAuthorization(proxyReq, true)
  327. resp, postErr := client.Do(proxyReq)
  328. if postErr != nil {
  329. glog.Errorf("post to filer: %v", postErr)
  330. return "", s3err.ErrInternalError
  331. }
  332. defer resp.Body.Close()
  333. etag = fmt.Sprintf("%x", hash.Sum(nil))
  334. resp_body, ra_err := io.ReadAll(resp.Body)
  335. if ra_err != nil {
  336. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  337. return etag, s3err.ErrInternalError
  338. }
  339. var ret weed_server.FilerPostResult
  340. unmarshal_err := json.Unmarshal(resp_body, &ret)
  341. if unmarshal_err != nil {
  342. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  343. return "", s3err.ErrInternalError
  344. }
  345. if ret.Error != "" {
  346. glog.Errorf("upload to filer error: %v", ret.Error)
  347. return "", filerErrorToS3Error(ret.Error)
  348. }
  349. return etag, s3err.ErrNone
  350. }
  351. func setEtag(w http.ResponseWriter, etag string) {
  352. if etag != "" {
  353. if strings.HasPrefix(etag, "\"") {
  354. w.Header().Set("ETag", etag)
  355. } else {
  356. w.Header().Set("ETag", "\""+etag+"\"")
  357. }
  358. }
  359. }
  360. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  361. if strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory") {
  362. return s3err.ErrExistingObjectIsDirectory
  363. }
  364. return s3err.ErrInternalError
  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. }