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.

621 lines
18 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
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/s3account"
  11. "github.com/seaweedfs/seaweedfs/weed/s3api/s3acl"
  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.ErrMalformedDate)
  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.CheckAccessForPutObject(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 urlEscapeObject(object string) string {
  123. t := urlPathEscape(removeDuplicateSlashes(object))
  124. if strings.HasPrefix(t, "/") {
  125. return t
  126. }
  127. return "/" + t
  128. }
  129. func urlPathEscape(object string) string {
  130. var escapedParts []string
  131. for _, part := range strings.Split(object, "/") {
  132. escapedParts = append(escapedParts, url.PathEscape(part))
  133. }
  134. return strings.Join(escapedParts, "/")
  135. }
  136. func removeDuplicateSlashes(object string) string {
  137. result := strings.Builder{}
  138. result.Grow(len(object))
  139. isLastSlash := false
  140. for _, r := range object {
  141. switch r {
  142. case '/':
  143. if !isLastSlash {
  144. result.WriteRune(r)
  145. }
  146. isLastSlash = true
  147. default:
  148. result.WriteRune(r)
  149. isLastSlash = false
  150. }
  151. }
  152. return result.String()
  153. }
  154. func (s3a *S3ApiServer) toFilerUrl(bucket, object string) string {
  155. object = urlPathEscape(removeDuplicateSlashes(object))
  156. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  157. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, object)
  158. return destUrl
  159. }
  160. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  161. bucket, object := s3_constants.GetBucketAndObject(r)
  162. glog.V(3).Infof("GetObjectHandler %s %s", bucket, object)
  163. errCode := s3a.checkBucketAccessForReadObject(r, bucket)
  164. if errCode != s3err.ErrNone {
  165. s3err.WriteErrorResponse(w, r, errCode)
  166. return
  167. }
  168. if strings.HasSuffix(r.URL.Path, "/") {
  169. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  170. return
  171. }
  172. destUrl := s3a.toFilerUrl(bucket, object)
  173. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  174. }
  175. // GetObjectAclHandler Put object ACL
  176. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObjecthtml
  177. func (s3a *S3ApiServer) GetObjectAclHandler(w http.ResponseWriter, r *http.Request) {
  178. bucket, object := s3_constants.GetBucketAndObject(r)
  179. acp, errCode := s3a.checkAccessForReadObjectAcl(r, bucket, object)
  180. if errCode != s3err.ErrNone {
  181. s3err.WriteErrorResponse(w, r, errCode)
  182. return
  183. }
  184. result := &s3.PutBucketAclInput{
  185. AccessControlPolicy: acp,
  186. }
  187. s3err.WriteAwsXMLResponse(w, r, http.StatusOK, &result)
  188. }
  189. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  190. bucket, object := s3_constants.GetBucketAndObject(r)
  191. glog.V(3).Infof("HeadObjectHandler %s %s", bucket, object)
  192. errCode := s3a.checkBucketAccessForReadObject(r, bucket)
  193. if errCode != s3err.ErrNone {
  194. s3err.WriteErrorResponse(w, r, errCode)
  195. return
  196. }
  197. destUrl := s3a.toFilerUrl(bucket, object)
  198. s3a.proxyToFiler(w, r, destUrl, false, passThroughResponse)
  199. }
  200. func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
  201. bucket, object := s3_constants.GetBucketAndObject(r)
  202. glog.V(3).Infof("DeleteObjectHandler %s %s", bucket, object)
  203. destUrl := s3a.toFilerUrl(bucket, object)
  204. s3a.proxyToFiler(w, r, destUrl, true, func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  205. statusCode = http.StatusNoContent
  206. for k, v := range proxyResponse.Header {
  207. w.Header()[k] = v
  208. }
  209. w.WriteHeader(statusCode)
  210. return statusCode
  211. })
  212. }
  213. // / ObjectIdentifier carries key name for the object to delete.
  214. type ObjectIdentifier struct {
  215. ObjectName string `xml:"Key"`
  216. }
  217. // DeleteObjectsRequest - xml carrying the object key names which needs to be deleted.
  218. type DeleteObjectsRequest struct {
  219. // Element to enable quiet mode for the request
  220. Quiet bool
  221. // List of objects to be deleted
  222. Objects []ObjectIdentifier `xml:"Object"`
  223. }
  224. // DeleteError structure.
  225. type DeleteError struct {
  226. Code string
  227. Message string
  228. Key string
  229. }
  230. // DeleteObjectsResponse container for multiple object deletes.
  231. type DeleteObjectsResponse struct {
  232. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ DeleteResult" json:"-"`
  233. // Collection of all deleted objects
  234. DeletedObjects []ObjectIdentifier `xml:"Deleted,omitempty"`
  235. // Collection of errors deleting certain objects.
  236. Errors []DeleteError `xml:"Error,omitempty"`
  237. }
  238. // DeleteMultipleObjectsHandler - Delete multiple objects
  239. func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *http.Request) {
  240. bucket, _ := s3_constants.GetBucketAndObject(r)
  241. glog.V(3).Infof("DeleteMultipleObjectsHandler %s", bucket)
  242. deleteXMLBytes, err := io.ReadAll(r.Body)
  243. if err != nil {
  244. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  245. return
  246. }
  247. deleteObjects := &DeleteObjectsRequest{}
  248. if err := xml.Unmarshal(deleteXMLBytes, deleteObjects); err != nil {
  249. s3err.WriteErrorResponse(w, r, s3err.ErrMalformedXML)
  250. return
  251. }
  252. if len(deleteObjects.Objects) > deleteMultipleObjectsLimit {
  253. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxDeleteObjects)
  254. return
  255. }
  256. var deletedObjects []ObjectIdentifier
  257. var deleteErrors []DeleteError
  258. var auditLog *s3err.AccessLog
  259. directoriesWithDeletion := make(map[string]int)
  260. if s3err.Logger != nil {
  261. auditLog = s3err.GetAccessLog(r, http.StatusNoContent, s3err.ErrNone)
  262. }
  263. s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  264. // delete file entries
  265. for _, object := range deleteObjects.Objects {
  266. if object.ObjectName == "" {
  267. continue
  268. }
  269. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  270. parentDirectoryPath, entryName, isDeleteData, isRecursive := "", object.ObjectName, true, false
  271. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  272. entryName = object.ObjectName[lastSeparator+1:]
  273. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  274. }
  275. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  276. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  277. if err == nil {
  278. directoriesWithDeletion[parentDirectoryPath]++
  279. deletedObjects = append(deletedObjects, object)
  280. } else if strings.Contains(err.Error(), filer.MsgFailDelNonEmptyFolder) {
  281. deletedObjects = append(deletedObjects, object)
  282. } else {
  283. delete(directoriesWithDeletion, parentDirectoryPath)
  284. deleteErrors = append(deleteErrors, DeleteError{
  285. Code: "",
  286. Message: err.Error(),
  287. Key: object.ObjectName,
  288. })
  289. }
  290. if auditLog != nil {
  291. auditLog.Key = entryName
  292. s3err.PostAccessLog(*auditLog)
  293. }
  294. }
  295. // purge empty folders, only checking folders with deletions
  296. for len(directoriesWithDeletion) > 0 {
  297. directoriesWithDeletion = s3a.doDeleteEmptyDirectories(client, directoriesWithDeletion)
  298. }
  299. return nil
  300. })
  301. deleteResp := DeleteObjectsResponse{}
  302. if !deleteObjects.Quiet {
  303. deleteResp.DeletedObjects = deletedObjects
  304. }
  305. deleteResp.Errors = deleteErrors
  306. writeSuccessResponseXML(w, r, deleteResp)
  307. }
  308. func (s3a *S3ApiServer) doDeleteEmptyDirectories(client filer_pb.SeaweedFilerClient, directoriesWithDeletion map[string]int) (newDirectoriesWithDeletion map[string]int) {
  309. var allDirs []string
  310. for dir := range directoriesWithDeletion {
  311. allDirs = append(allDirs, dir)
  312. }
  313. slices.SortFunc(allDirs, func(a, b string) bool {
  314. return len(a) > len(b)
  315. })
  316. newDirectoriesWithDeletion = make(map[string]int)
  317. for _, dir := range allDirs {
  318. parentDir, dirName := util.FullPath(dir).DirAndName()
  319. if parentDir == s3a.option.BucketsPath {
  320. continue
  321. }
  322. if err := doDeleteEntry(client, parentDir, dirName, false, false); err != nil {
  323. glog.V(4).Infof("directory %s has %d deletion but still not empty: %v", dir, directoriesWithDeletion[dir], err)
  324. } else {
  325. newDirectoriesWithDeletion[parentDir]++
  326. }
  327. }
  328. return
  329. }
  330. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, isWrite bool, responseFn func(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int)) {
  331. glog.V(3).Infof("s3 proxying %s to %s", r.Method, destUrl)
  332. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  333. if err != nil {
  334. glog.Errorf("NewRequest %s: %v", destUrl, err)
  335. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  336. return
  337. }
  338. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  339. for k, v := range r.URL.Query() {
  340. if _, ok := s3_constants.PassThroughHeaders[strings.ToLower(k)]; ok {
  341. proxyReq.Header[k] = v
  342. }
  343. }
  344. for header, values := range r.Header {
  345. proxyReq.Header[header] = values
  346. }
  347. // ensure that the Authorization header is overriding any previous
  348. // Authorization header which might be already present in proxyReq
  349. s3a.maybeAddFilerJwtAuthorization(proxyReq, isWrite)
  350. resp, postErr := s3a.client.Do(proxyReq)
  351. if postErr != nil {
  352. glog.Errorf("post to filer: %v", postErr)
  353. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  354. return
  355. }
  356. defer util.CloseResponse(resp)
  357. switch resp.StatusCode {
  358. case http.StatusPreconditionFailed:
  359. s3err.WriteErrorResponse(w, r, s3err.ErrPreconditionFailed)
  360. return
  361. case http.StatusRequestedRangeNotSatisfiable:
  362. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange)
  363. return
  364. case http.StatusForbidden:
  365. s3err.WriteErrorResponse(w, r, s3err.ErrAccessDenied)
  366. return
  367. default:
  368. }
  369. if r.Method == "DELETE" {
  370. if resp.StatusCode == http.StatusNotFound {
  371. // this is normal
  372. responseStatusCode := responseFn(resp, w)
  373. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  374. return
  375. }
  376. }
  377. if resp.StatusCode == http.StatusNotFound {
  378. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  379. return
  380. }
  381. if resp.Header.Get(s3_constants.X_SeaweedFS_Header_Directory_Key) == "true" {
  382. responseStatusCode := responseFn(resp, w)
  383. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  384. return
  385. }
  386. // when HEAD a directory, it should be reported as no such key
  387. // https://github.com/seaweedfs/seaweedfs/issues/3457
  388. if resp.ContentLength == -1 && resp.StatusCode != http.StatusNotModified {
  389. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchKey)
  390. return
  391. }
  392. setUserMetadataKeyToLowercase(resp)
  393. responseStatusCode := responseFn(resp, w)
  394. s3err.PostLog(r, responseStatusCode, s3err.ErrNone)
  395. }
  396. func setUserMetadataKeyToLowercase(resp *http.Response) {
  397. for key, value := range resp.Header {
  398. if strings.HasPrefix(key, s3_constants.AmzUserMetaPrefix) {
  399. resp.Header[strings.ToLower(key)] = value
  400. delete(resp.Header, key)
  401. }
  402. }
  403. }
  404. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) (statusCode int) {
  405. for k, v := range proxyResponse.Header {
  406. w.Header()[k] = v
  407. }
  408. if proxyResponse.Header.Get("Content-Range") != "" && proxyResponse.StatusCode == 200 {
  409. w.WriteHeader(http.StatusPartialContent)
  410. statusCode = http.StatusPartialContent
  411. } else {
  412. statusCode = proxyResponse.StatusCode
  413. }
  414. w.WriteHeader(statusCode)
  415. buf := mem.Allocate(128 * 1024)
  416. defer mem.Free(buf)
  417. if n, err := io.CopyBuffer(w, proxyResponse.Body, buf); err != nil {
  418. glog.V(1).Infof("passthrough response read %d bytes: %v", n, err)
  419. }
  420. return statusCode
  421. }
  422. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader, destination string) (etag string, code s3err.ErrorCode) {
  423. hash := md5.New()
  424. var body = io.TeeReader(dataReader, hash)
  425. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  426. if err != nil {
  427. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  428. return "", s3err.ErrInternalError
  429. }
  430. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  431. if destination != "" {
  432. proxyReq.Header.Set(s3_constants.SeaweedStorageDestinationHeader, destination)
  433. }
  434. for header, values := range r.Header {
  435. for _, value := range values {
  436. proxyReq.Header.Add(header, value)
  437. }
  438. }
  439. // ensure that the Authorization header is overriding any previous
  440. // Authorization header which might be already present in proxyReq
  441. s3a.maybeAddFilerJwtAuthorization(proxyReq, true)
  442. resp, postErr := s3a.client.Do(proxyReq)
  443. if postErr != nil {
  444. glog.Errorf("post to filer: %v", postErr)
  445. return "", s3err.ErrInternalError
  446. }
  447. defer resp.Body.Close()
  448. etag = fmt.Sprintf("%x", hash.Sum(nil))
  449. resp_body, ra_err := io.ReadAll(resp.Body)
  450. if ra_err != nil {
  451. glog.Errorf("upload to filer response read %d: %v", resp.StatusCode, ra_err)
  452. return etag, s3err.ErrInternalError
  453. }
  454. var ret weed_server.FilerPostResult
  455. unmarshal_err := json.Unmarshal(resp_body, &ret)
  456. if unmarshal_err != nil {
  457. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  458. return "", s3err.ErrInternalError
  459. }
  460. if ret.Error != "" {
  461. glog.Errorf("upload to filer error: %v", ret.Error)
  462. return "", filerErrorToS3Error(ret.Error)
  463. }
  464. return etag, s3err.ErrNone
  465. }
  466. func setEtag(w http.ResponseWriter, etag string) {
  467. if etag != "" {
  468. if strings.HasPrefix(etag, "\"") {
  469. w.Header()["ETag"] = []string{etag}
  470. } else {
  471. w.Header()["ETag"] = []string{"\"" + etag + "\""}
  472. }
  473. }
  474. }
  475. func filerErrorToS3Error(errString string) s3err.ErrorCode {
  476. switch {
  477. case strings.HasPrefix(errString, "existing ") && strings.HasSuffix(errString, "is a directory"):
  478. return s3err.ErrExistingObjectIsDirectory
  479. case strings.HasSuffix(errString, "is a file"):
  480. return s3err.ErrExistingObjectIsFile
  481. default:
  482. return s3err.ErrInternalError
  483. }
  484. }
  485. func (s3a *S3ApiServer) maybeAddFilerJwtAuthorization(r *http.Request, isWrite bool) {
  486. encodedJwt := s3a.maybeGetFilerJwtAuthorizationToken(isWrite)
  487. if encodedJwt == "" {
  488. return
  489. }
  490. r.Header.Set("Authorization", "BEARER "+string(encodedJwt))
  491. }
  492. func (s3a *S3ApiServer) maybeGetFilerJwtAuthorizationToken(isWrite bool) string {
  493. var encodedJwt security.EncodedJwt
  494. if isWrite {
  495. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.SigningKey, s3a.filerGuard.ExpiresAfterSec)
  496. } else {
  497. encodedJwt = security.GenJwtForFilerServer(s3a.filerGuard.ReadSigningKey, s3a.filerGuard.ReadExpiresAfterSec)
  498. }
  499. return string(encodedJwt)
  500. }
  501. // PutObjectAclHandler Put object ACL
  502. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_PutObjecthtml
  503. func (s3a *S3ApiServer) PutObjectAclHandler(w http.ResponseWriter, r *http.Request) {
  504. bucket, object := s3_constants.GetBucketAndObject(r)
  505. objectEntry, ownerId, grants, errCode := s3a.checkAccessForWriteObjectAcl(r, bucket, object)
  506. if errCode != s3err.ErrNone {
  507. s3err.WriteErrorResponse(w, r, errCode)
  508. return
  509. }
  510. if errCode != s3err.ErrNone {
  511. s3err.WriteErrorResponse(w, r, errCode)
  512. return
  513. }
  514. errCode = s3acl.AssembleEntryWithAcp(objectEntry, ownerId, grants)
  515. if errCode != s3err.ErrNone {
  516. return
  517. }
  518. err := updateObjectEntry(s3a, bucket, object, objectEntry)
  519. if err != nil {
  520. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  521. return
  522. }
  523. w.WriteHeader(http.StatusOK)
  524. }