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.

597 lines
17 KiB

3 years ago
6 years ago
7 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
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
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/aws/aws-sdk-go/service/s3"
  9. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  10. "github.com/seaweedfs/seaweedfs/weed/s3api/s3acl"
  11. "github.com/seaweedfs/seaweedfs/weed/s3api/s3account"
  12. "github.com/seaweedfs/seaweedfs/weed/security"
  13. "github.com/seaweedfs/seaweedfs/weed/util/mem"
  14. "golang.org/x/exp/slices"
  15. "io"
  16. "net/http"
  17. "net/url"
  18. "strings"
  19. "time"
  20. "github.com/pquerna/cachecontrol/cacheobject"
  21. "github.com/seaweedfs/seaweedfs/weed/filer"
  22. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  23. "github.com/seaweedfs/seaweedfs/weed/glog"
  24. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  25. weed_server "github.com/seaweedfs/seaweedfs/weed/server"
  26. "github.com/seaweedfs/seaweedfs/weed/util"
  27. )
  28. const (
  29. deleteMultipleObjectsLimit = 1000
  30. )
  31. func mimeDetect(r *http.Request, dataReader io.Reader) io.ReadCloser {
  32. mimeBuffer := make([]byte, 512)
  33. size, _ := dataReader.Read(mimeBuffer)
  34. if size > 0 {
  35. r.Header.Set("Content-Type", http.DetectContentType(mimeBuffer[:size]))
  36. return io.NopCloser(io.MultiReader(bytes.NewReader(mimeBuffer[:size]), dataReader))
  37. }
  38. return io.NopCloser(dataReader)
  39. }
  40. func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) {
  41. // http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
  42. bucket, object := s3_constants.GetBucketAndObject(r)
  43. glog.V(3).Infof("PutObjectHandler %s %s", bucket, object)
  44. _, err := validateContentMd5(r.Header)
  45. if err != nil {
  46. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
  47. return
  48. }
  49. if r.Header.Get("Cache-Control") != "" {
  50. if _, err = cacheobject.ParseRequestCacheControl(r.Header.Get("Cache-Control")); err != nil {
  51. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidDigest)
  52. return
  53. }
  54. }
  55. if r.Header.Get("Expires") != "" {
  56. if _, err = time.Parse(http.TimeFormat, r.Header.Get("Expires")); err != nil {
  57. s3err.WriteErrorResponse(w, r, s3err.ErrMalformedExpires)
  58. return
  59. }
  60. }
  61. dataReader := r.Body
  62. rAuthType := getRequestAuthType(r)
  63. if s3a.iam.isEnabled() {
  64. var s3ErrCode s3err.ErrorCode
  65. var identity *Identity
  66. switch rAuthType {
  67. case authTypeStreamingSigned:
  68. dataReader, identity, s3ErrCode = s3a.iam.newSignV4ChunkedReader(r)
  69. case authTypeSignedV2, authTypePresignedV2:
  70. identity, s3ErrCode = s3a.iam.isReqAuthenticatedV2(r)
  71. case authTypePresigned, authTypeSigned:
  72. identity, s3ErrCode = s3a.iam.reqSignatureV4Verify(r)
  73. case authTypeAnonymous:
  74. identity = IdentityAnonymous
  75. }
  76. if s3ErrCode != s3err.ErrNone {
  77. s3err.WriteErrorResponse(w, r, s3ErrCode)
  78. return
  79. }
  80. if identity.AccountId != s3account.AccountAnonymous.Id {
  81. r.Header.Set(s3_constants.AmzAccountId, identity.AccountId)
  82. }
  83. } else {
  84. if authTypeStreamingSigned == rAuthType {
  85. s3err.WriteErrorResponse(w, r, s3err.ErrAuthNotSetup)
  86. return
  87. }
  88. }
  89. defer dataReader.Close()
  90. errCode := s3a.checkAccessForWriteObject(r, bucket, object)
  91. if errCode != s3err.ErrNone {
  92. s3err.WriteErrorResponse(w, r, errCode)
  93. return
  94. }
  95. objectContentType := r.Header.Get("Content-Type")
  96. if strings.HasSuffix(object, "/") && r.ContentLength == 0 {
  97. if err := s3a.mkdir(
  98. s3a.option.BucketsPath, bucket+strings.TrimSuffix(object, "/"),
  99. func(entry *filer_pb.Entry) {
  100. if objectContentType == "" {
  101. objectContentType = "httpd/unix-directory"
  102. }
  103. entry.Attributes.Mime = objectContentType
  104. }); err != nil {
  105. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  106. return
  107. }
  108. } else {
  109. uploadUrl := s3a.toFilerUrl(bucket, object)
  110. if objectContentType == "" {
  111. dataReader = mimeDetect(r, dataReader)
  112. }
  113. etag, errCode := s3a.putToFiler(r, uploadUrl, dataReader, "")
  114. if errCode != s3err.ErrNone {
  115. s3err.WriteErrorResponse(w, r, errCode)
  116. return
  117. }
  118. setEtag(w, etag)
  119. }
  120. writeSuccessResponseEmpty(w, r)
  121. }
  122. func urlPathEscape(object string) string {
  123. var escapedParts []string
  124. for _, part := range strings.Split(object, "/") {
  125. escapedParts = append(escapedParts, url.PathEscape(part))
  126. }
  127. return strings.Join(escapedParts, "/")
  128. }
  129. func removeDuplicateSlashes(object string) string {
  130. result := strings.Builder{}
  131. result.Grow(len(object))
  132. isLastSlash := false
  133. for _, r := range object {
  134. switch r {
  135. case '/':
  136. if !isLastSlash {
  137. result.WriteRune(r)
  138. }
  139. isLastSlash = true
  140. default:
  141. result.WriteRune(r)
  142. isLastSlash = false
  143. }
  144. }
  145. return result.String()
  146. }
  147. func (s3a *S3ApiServer) toFilerUrl(bucket, object string) string {
  148. object = urlPathEscape(removeDuplicateSlashes(object))
  149. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  150. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, object)
  151. return destUrl
  152. }
  153. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  154. bucket, object := s3_constants.GetBucketAndObject(r)
  155. glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
  156. errCode := s3a.checkBucketAccessForReadObject(r, bucket)
  157. if errCode != s3err.ErrNone {
  158. s3err.WriteErrorResponse(w, r, errCode)
  159. return
  160. }
  161. if strings.HasSuffix(r.URL.Path, "/") {
  162. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  163. return
  164. }
  165. destUrl := s3a.toFilerUrl(bucket, object)
  166. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  167. }
  168. // GetObjectAclHandler Put object ACL
  169. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjecthtml
  170. func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Request) {
  171. bucket, object := s3_constants.GetBucketAndObject(r)
  172. acp, errCode := s3a.checkAccessForReadObjectAcl(r, bucket, object)
  173. if errCode != s3err.ErrNone {
  174. s3err.WriteErrorResponse(w, r, errCode)
  175. return
  176. }
  177. result := &s3.PutBucketAclInput{
  178. AccessControlPolicy: acp,
  179. }
  180. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, &result)
  181. }
  182. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  183. bucket, object := s3_constants.GetBucketAndObject(r)
  184. glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
  185. destUrl := s3a.toFilerUrl(bucket, object)
  186. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  187. }
  188. func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
  189. bucket, object := s3_constants.GetBucketAndObject(r)
  190. glog.V(3).Infof("DeleteObjectHandler %s %s", bucket, object)
  191. destUrl := s3a.toFilerUrl(bucket, object)
  192. s3a.proxyToFiler(w, r, destUrl, true, func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  193. statusCode = http.StatusNoContent
  194. for k, v := range proxyResponse.Header {
  195. w.Header()[k] = v
  196. }
  197. w.WriteHeader(statusCode)
  198. return statusCode
  199. })
  200. }
  201. // / ObjectIdentifier carries key name for the object to delete.
  202. type ObjectIdentifier struct {
  203. ObjectName string `xml:"Key"`
  204. }
  205. // DeleteObjectsRequest - xml carrying the object key names which needs to be deleted.
  206. type DeleteObjectsRequest struct {
  207. // Element to enable quiet mode for the request
  208. Quiet bool
  209. // List of objects to be deleted
  210. Objects []ObjectIdentifier `xml:"Object"`
  211. }
  212. // DeleteError structure.
  213. type DeleteError struct {
  214. Code string
  215. Message string
  216. Key string
  217. }
  218. // DeleteObjectsResponse container for multiple object deletes.
  219. type DeleteObjectsResponse struct {
  220. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ DeleteResult" json:"-"`
  221. // Collection of all deleted objects
  222. DeletedObjects []ObjectIdentifier `xml:"Deleted,omitempty"`
  223. // Collection of errors deleting certain objects.
  224. Errors []DeleteError `xml:"Error,omitempty"`
  225. }
  226. // DeleteMultipleObjectsHandler - Delete multiple objects
  227. func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *http.Request) {
  228. bucket, _ := s3_constants.GetBucketAndObject(r)
  229. glog.V(3).Infof("DeleteMultipleObjectsHandler %s", bucket)
  230. deleteXMLBytes, err := io.ReadAll(r.Body)
  231. if err != nil {
  232. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  233. return
  234. }
  235. deleteObjects := &DeleteObjectsRequest{}
  236. if err := xml.Unmarshal(deleteXMLBytes, deleteObjects); err != nil {
  237. s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
  238. return
  239. }
  240. if len(deleteObjects.Objects) > deleteMultipleObjectsLimit {
  241. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxDeleteObjects)
  242. return
  243. }
  244. var deletedObjects []ObjectIdentifier
  245. var deleteErrors []DeleteError
  246. var auditLog *s3err.AccessLog
  247. directoriesWithDeletion := make(map[string]int)
  248. if s3err.Logger != nil {
  249. auditLog = s3err.GetAccessLog(r, http.StatusNoContent, s3err.ErrNone)
  250. }
  251. s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  252. // delete file entries
  253. for _, object := range deleteObjects.Objects {
  254. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  255. parentDirectoryPath, entryName, isDeleteData, isRecursive := "", object.ObjectName, true, false
  256. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  257. entryName = object.ObjectName[lastSeparator+1:]
  258. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  259. }
  260. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  261. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  262. if err == nil {
  263. directoriesWithDeletion[parentDirectoryPath]++
  264. deletedObjects = append(deletedObjects, object)
  265. } else if strings.Contains(err.Error(), filer.MsgFailDelNonEmptyFolder) {
  266. deletedObjects = append(deletedObjects, object)
  267. } else {
  268. delete(directoriesWithDeletion, parentDirectoryPath)
  269. deleteErrors = append(deleteErrors, DeleteError{
  270. Code: "",
  271. Message: err.Error(),
  272. Key: object.ObjectName,
  273. })
  274. }
  275. if auditLog != nil {
  276. auditLog.Key = entryName
  277. s3err.PostAccessLog(*auditLog)
  278. }
  279. }
  280. // purge empty folders, only checking folders with deletions
  281. for len(directoriesWithDeletion) > 0 {
  282. directoriesWithDeletion = s3a.doDeleteEmptyDirectories(client, directoriesWithDeletion)
  283. }
  284. return nil
  285. })
  286. deleteResp := DeleteObjectsResponse{}
  287. if !deleteObjects.Quiet {
  288. deleteResp.DeletedObjects = deletedObjects
  289. }
  290. deleteResp.Errors = deleteErrors
  291. writeSuccessResponseXML(w, r, deleteResp)
  292. }
  293. func (s3a *S3ApiServer) doDeleteEmptyDirectories(client filer_pb.SeaweedFilerClient, directoriesWithDeletion map[string]int) (newDirectoriesWithDeletion map[string]int) {
  294. var allDirs []string
  295. for dir := range directoriesWithDeletion {
  296. allDirs = append(allDirs, dir)
  297. }
  298. slices.SortFunc(allDirs, func(a, b string) bool {
  299. return len(a) > len(b)
  300. })
  301. newDirectoriesWithDeletion = make(map[string]int)
  302. for _, dir := range allDirs {
  303. parentDir, dirName := util.FullPath(dir).DirAndName()
  304. if parentDir == s3a.option.BucketsPath {
  305. continue
  306. }
  307. if err := doDeleteEntry(client, parentDir, dirName, false, false); err != nil {
  308. glog.V(4).Infof("directory %s has %d deletion but still not empty: %v", dir, directoriesWithDeletion[dir], err)
  309. } else {
  310. newDirectoriesWithDeletion[parentDir]++
  311. }
  312. }
  313. return
  314. }
  315. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, isWrite bool, responseFn func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int)) {
  316. glog.V(3).Infof("s3 proxying %s to %s", r.Method, destUrl)
  317. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  318. if err != nil {
  319. glog.Errorf("NewRequest %s: %v", destUrl, err)
  320. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  321. return
  322. }
  323. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  324. for k, v := range r.URL.Query() {
  325. if _, ok := s3_constants.PassThroughHeaders[strings.ToLower(k)]; ok {
  326. proxyReq.Header[k] = v
  327. }
  328. }
  329. for header, values := range r.Header {
  330. proxyReq.Header[header] = values
  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, isWrite)
  335. resp, postErr := s3a.client.Do(proxyReq)
  336. if postErr != nil {
  337. glog.Errorf("post to filer: %v", postErr)
  338. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  339. return
  340. }
  341. defer util.CloseResponse(resp)
  342. switch resp.StatusCode {
  343. case http.StatusPreconditionFailed:
  344. s3err.WriteErrorResponse(w, r, s3err.ErrPreconditionFailed)
  345. return
  346. case http.StatusRequestedRangeNotSatisfiable:
  347. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
  348. return
  349. case http.StatusForbidden:
  350. s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
  351. return
  352. default:
  353. }
  354. if r.Method == "DELETE" {
  355. if resp.StatusCode == http.StatusNotFound {
  356. // this is normal
  357. responseStatusCode := responseFn(resp, w)
  358. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  359. return
  360. }
  361. }
  362. if resp.StatusCode == http.StatusNotFound {
  363. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  364. return
  365. }
  366. if resp.Header.Get(s3_constants.X_SeaweedFS_Header_Directory_Key) == "true" {
  367. responseStatusCode := responseFn(resp, w)
  368. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  369. return
  370. }
  371. // when HEAD a directory, it should be reported as no such key
  372. // https://github.com/seaweedfs/seaweedfs/issues/3457
  373. if resp.ContentLength == -1 && resp.StatusCode != http.StatusNotModified {
  374. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  375. return
  376. }
  377. responseStatusCode := responseFn(resp, w)
  378. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  379. }
  380. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  381. for k, v := range proxyResponse.Header {
  382. w.Header()[k] = v
  383. }
  384. if proxyResponse.Header.Get("Content-Range") != "" && proxyResponse.StatusCode == 200 {
  385. w.WriteHeader(http.StatusPartialContent)
  386. statusCode = http.StatusPartialContent
  387. } else {
  388. statusCode = proxyResponse.StatusCode
  389. }
  390. w.WriteHeader(statusCode)
  391. buf := mem.Allocate(128 * 1024)
  392. defer mem.Free(buf)
  393. if n, err := io.CopyBuffer(w, proxyResponse.Body, buf); err != nil {
  394. glog.V(1).Infof("passthrough response read %d bytes: %v", n, err)
  395. }
  396. return statusCode
  397. }
  398. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader, destination string) (etag string, code s3err.ErrorCode) {
  399. hash := md5.New()
  400. var body = io.TeeReader(dataReader, hash)
  401. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  402. if err != nil {
  403. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  404. return "", s3err.ErrInternalError
  405. }
  406. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  407. if destination != "" {
  408. proxyReq.Header.Set(s3_constants.SeaweedStorageDestinationHeader, destination)
  409. }
  410. for header, values := range r.Header {
  411. for _, value := range values {
  412. proxyReq.Header.Add(header, value)
  413. }
  414. }
  415. // ensure that the Authorization header is overriding any previous
  416. // Authorization header which might be already present in proxyReq
  417. s3a.maybeAddFilerJwtAuthorization(proxyReq, true)
  418. resp, postErr := s3a.client.Do(proxyReq)
  419. if postErr != nil {
  420. glog.Errorf("post to filer: %v", postErr)
  421. return "", s3err.ErrInternalError
  422. }
  423. defer resp.Body.Close()
  424. etag = fmt.Sprintf("%x", hash.Sum(nil))
  425. resp_body, ra_err := io.ReadAll(resp.Body)
  426. if ra_err != nil {
  427. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  428. return etag, s3err.ErrInternalError
  429. }
  430. var ret weed_server.FilerPostResult
  431. unmarshal_err := json.Unmarshal(resp_body, &ret)
  432. if unmarshal_err != nil {
  433. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  434. return "", s3err.ErrInternalError
  435. }
  436. if ret.Error != "" {
  437. glog.Errorf("upload to filer error: %v", ret.Error)
  438. return "", filerErrorToS3Error(ret.Error)
  439. }
  440. return etag, s3err.ErrNone
  441. }
  442. func setEtag(w http.ResponseWriter, etag string) {
  443. if etag != "" {
  444. if strings.HasPrefix(etag, "\"") {
  445. w.Header()["ETag"] = []string{etag}
  446. } else {
  447. w.Header()["ETag"] = []string{"\"" + etag + "\""}
  448. }
  449. }
  450. }
  451. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  452. switch {
  453. case strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory"):
  454. return s3err.ErrExistingObjectIsDirectory
  455. case strings.HasSuffix(errString, "is a file"):
  456. return s3err.ErrExistingObjectIsFile
  457. default:
  458. return s3err.ErrInternalError
  459. }
  460. }
  461. func (s3a *S3ApiServer) maybeAddFilerJwtAuthorization(r *http.Request, isWrite bool) {
  462. encodedJwt := s3a.maybeGetFilerJwtAuthorizationToken(isWrite)
  463. if encodedJwt == "" {
  464. return
  465. }
  466. r.Header.Set("Authorization", "BEARER "+string(encodedJwt))
  467. }
  468. func (s3a *S3ApiServer) maybeGetFilerJwtAuthorizationToken(isWrite bool) string {
  469. var encodedJwt security.EncodedJwt
  470. if isWrite {
  471. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.SigningKey, s3a.filerGuard.ExpiresAfterSec)
  472. } else {
  473. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.ReadSigningKey, s3a.filerGuard.ReadExpiresAfterSec)
  474. }
  475. return string(encodedJwt)
  476. }
  477. // PutObjectAclHandler Put object ACL
  478. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjecthtml
  479. func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Request) {
  480. bucket, object := s3_constants.GetBucketAndObject(r)
  481. accountId := s3acl.GetAccountId(r)
  482. bucketMetadata, objectEntry, objectOwner, errCode := s3a.checkAccessForWriteObjectAcl(accountId, bucket, object)
  483. if errCode != s3err.ErrNone {
  484. s3err.WriteErrorResponse(w, r, errCode)
  485. return
  486. }
  487. grants, errCode := s3acl.ExtractAcl(r, s3a.accountManager, bucketMetadata.ObjectOwnership, *bucketMetadata.Owner.ID, objectOwner, accountId)
  488. if errCode != s3err.ErrNone {
  489. s3err.WriteErrorResponse(w, r, errCode)
  490. return
  491. }
  492. errCode = s3acl.AssembleEntryWithAcp(objectEntry, objectOwner, grants)
  493. if errCode != s3err.ErrNone {
  494. return
  495. }
  496. err := updateObjectEntry(s3a, bucket, objectEntry)
  497. if err != nil {
  498. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  499. return
  500. }
  501. w.WriteHeader(http.StatusOK)
  502. }