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.

302 lines
8.8 KiB

4 years ago
4 years ago
3 years ago
3 years ago
4 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
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 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
4 years ago
4 years ago
3 years ago
3 years ago
  1. package s3api
  2. import (
  3. "fmt"
  4. "github.com/chrislusf/seaweedfs/weed/glog"
  5. "github.com/chrislusf/seaweedfs/weed/s3api/s3_constants"
  6. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  7. "modernc.org/strutil"
  8. "net/http"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/chrislusf/seaweedfs/weed/util"
  14. )
  15. const (
  16. DirectiveCopy = "COPY"
  17. DirectiveReplace = "REPLACE"
  18. )
  19. func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request) {
  20. dstBucket, dstObject := s3_constants.GetBucketAndObject(r)
  21. // Copy source path.
  22. cpSrcPath, err := url.QueryUnescape(r.Header.Get("X-Amz-Copy-Source"))
  23. if err != nil {
  24. // Save unescaped string as is.
  25. cpSrcPath = r.Header.Get("X-Amz-Copy-Source")
  26. }
  27. srcBucket, srcObject := pathToBucketAndObject(cpSrcPath)
  28. glog.V(3).Infof("CopyObjectHandler %s %s => %s %s", srcBucket, srcObject, dstBucket, dstObject)
  29. replaceMeta, replaceTagging := replaceDirective(r.Header)
  30. if (srcBucket == dstBucket && srcObject == dstObject || cpSrcPath == "") && (replaceMeta || replaceTagging) {
  31. fullPath := util.FullPath(fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, dstBucket, dstObject))
  32. dir, name := fullPath.DirAndName()
  33. entry, err := s3a.getEntry(dir, name)
  34. if err != nil || entry.IsDirectory {
  35. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  36. return
  37. }
  38. entry.Extended = processMetadataBytes(r.Header, entry.Extended, replaceMeta, replaceTagging)
  39. err = s3a.touch(dir, name, entry)
  40. if err != nil {
  41. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  42. return
  43. }
  44. writeSuccessResponseXML(w, r, CopyObjectResult{
  45. ETag: fmt.Sprintf("%x", entry.Attributes.Md5),
  46. LastModified: time.Now().UTC(),
  47. })
  48. return
  49. }
  50. // If source object is empty or bucket is empty, reply back invalid copy source.
  51. if srcObject == "" || srcBucket == "" {
  52. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  53. return
  54. }
  55. srcPath := util.FullPath(fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, srcBucket, srcObject))
  56. dir, name := srcPath.DirAndName()
  57. if entry, err := s3a.getEntry(dir, name); err != nil || entry.IsDirectory {
  58. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  59. return
  60. }
  61. if srcBucket == dstBucket && srcObject == dstObject {
  62. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopyDest)
  63. return
  64. }
  65. dstUrl := fmt.Sprintf("http://%s%s/%s%s",
  66. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, dstBucket, urlPathEscape(dstObject))
  67. srcUrl := fmt.Sprintf("http://%s%s/%s%s",
  68. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, srcBucket, urlPathEscape(srcObject))
  69. _, _, resp, err := util.DownloadFile(srcUrl, s3a.maybeGetFilerJwtAuthorizationToken(false))
  70. if err != nil {
  71. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  72. return
  73. }
  74. defer util.CloseResponse(resp)
  75. tagErr := processMetadata(r.Header, resp.Header, replaceMeta, replaceTagging, s3a.getTags, dir, name)
  76. if tagErr != nil {
  77. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  78. return
  79. }
  80. glog.V(2).Infof("copy from %s to %s", srcUrl, dstUrl)
  81. destination := fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, dstBucket, dstObject)
  82. etag, errCode := s3a.putToFiler(r, dstUrl, resp.Body, destination)
  83. if errCode != s3err.ErrNone {
  84. s3err.WriteErrorResponse(w, r, errCode)
  85. return
  86. }
  87. setEtag(w, etag)
  88. response := CopyObjectResult{
  89. ETag: etag,
  90. LastModified: time.Now().UTC(),
  91. }
  92. writeSuccessResponseXML(w, r, response)
  93. }
  94. func pathToBucketAndObject(path string) (bucket, object string) {
  95. path = strings.TrimPrefix(path, "/")
  96. parts := strings.SplitN(path, "/", 2)
  97. if len(parts) == 2 {
  98. return parts[0], "/" + parts[1]
  99. }
  100. return parts[0], "/"
  101. }
  102. type CopyPartResult struct {
  103. LastModified time.Time `xml:"LastModified"`
  104. ETag string `xml:"ETag"`
  105. }
  106. func (s3a *S3ApiServer) CopyObjectPartHandler(w http.ResponseWriter, r *http.Request) {
  107. // https://docs.aws.amazon.com/AmazonS3/latest/dev/CopyingObjctsUsingRESTMPUapi.html
  108. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_UploadPartCopy.html
  109. dstBucket, dstObject := s3_constants.GetBucketAndObject(r)
  110. // Copy source path.
  111. cpSrcPath, err := url.QueryUnescape(r.Header.Get("X-Amz-Copy-Source"))
  112. if err != nil {
  113. // Save unescaped string as is.
  114. cpSrcPath = r.Header.Get("X-Amz-Copy-Source")
  115. }
  116. srcBucket, srcObject := pathToBucketAndObject(cpSrcPath)
  117. // If source object is empty or bucket is empty, reply back invalid copy source.
  118. if srcObject == "" || srcBucket == "" {
  119. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  120. return
  121. }
  122. uploadID := r.URL.Query().Get("uploadId")
  123. partIDString := r.URL.Query().Get("partNumber")
  124. partID, err := strconv.Atoi(partIDString)
  125. if err != nil {
  126. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidPart)
  127. return
  128. }
  129. glog.V(3).Infof("CopyObjectPartHandler %s %s => %s part %d", srcBucket, srcObject, dstBucket, partID)
  130. // check partID with maximum part ID for multipart objects
  131. if partID > globalMaxPartID {
  132. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxParts)
  133. return
  134. }
  135. rangeHeader := r.Header.Get("x-amz-copy-source-range")
  136. dstUrl := fmt.Sprintf("http://%s%s/%s/%04d.part",
  137. s3a.option.Filer.ToHttpAddress(), s3a.genUploadsFolder(dstBucket), uploadID, partID)
  138. srcUrl := fmt.Sprintf("http://%s%s/%s%s",
  139. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, srcBucket, urlPathEscape(srcObject))
  140. dataReader, err := util.ReadUrlAsReaderCloser(srcUrl, s3a.maybeGetFilerJwtAuthorizationToken(false), rangeHeader)
  141. if err != nil {
  142. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  143. return
  144. }
  145. defer dataReader.Close()
  146. glog.V(2).Infof("copy from %s to %s", srcUrl, dstUrl)
  147. destination := fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, dstBucket, dstObject)
  148. etag, errCode := s3a.putToFiler(r, dstUrl, dataReader, destination)
  149. if errCode != s3err.ErrNone {
  150. s3err.WriteErrorResponse(w, r, errCode)
  151. return
  152. }
  153. setEtag(w, etag)
  154. response := CopyPartResult{
  155. ETag: etag,
  156. LastModified: time.Now().UTC(),
  157. }
  158. writeSuccessResponseXML(w, r, response)
  159. }
  160. func replaceDirective(reqHeader http.Header) (replaceMeta, replaceTagging bool) {
  161. return reqHeader.Get(s3_constants.AmzUserMetaDirective) == DirectiveReplace, reqHeader.Get(s3_constants.AmzObjectTaggingDirective) == DirectiveReplace
  162. }
  163. func processMetadata(reqHeader, existing http.Header, replaceMeta, replaceTagging bool, getTags func(parentDirectoryPath string, entryName string) (tags map[string]string, err error), dir, name string) (err error) {
  164. if sc := reqHeader.Get(s3_constants.AmzStorageClass); len(sc) == 0 {
  165. if sc := existing[s3_constants.AmzStorageClass]; len(sc) > 0 {
  166. reqHeader[s3_constants.AmzStorageClass] = sc
  167. }
  168. }
  169. if !replaceMeta {
  170. for header, _ := range reqHeader {
  171. if strings.HasPrefix(header, s3_constants.AmzUserMetaPrefix) {
  172. delete(reqHeader, header)
  173. }
  174. }
  175. for k, v := range existing {
  176. if strings.HasPrefix(k, s3_constants.AmzUserMetaPrefix) {
  177. reqHeader[k] = v
  178. }
  179. }
  180. }
  181. if !replaceTagging {
  182. for header, _ := range reqHeader {
  183. if strings.HasPrefix(header, s3_constants.AmzObjectTagging) {
  184. delete(reqHeader, header)
  185. }
  186. }
  187. found := false
  188. for k, _ := range existing {
  189. if strings.HasPrefix(k, s3_constants.AmzObjectTaggingPrefix) {
  190. found = true
  191. break
  192. }
  193. }
  194. if found {
  195. tags, err := getTags(dir, name)
  196. if err != nil {
  197. return err
  198. }
  199. var tagArr []string
  200. for k, v := range tags {
  201. tagArr = append(tagArr, fmt.Sprintf("%s=%s", k, v))
  202. }
  203. tagStr := strutil.JoinFields(tagArr, "&")
  204. reqHeader.Set(s3_constants.AmzObjectTagging, tagStr)
  205. }
  206. }
  207. return
  208. }
  209. func processMetadataBytes(reqHeader http.Header, existing map[string][]byte, replaceMeta, replaceTagging bool) (metadata map[string][]byte) {
  210. metadata = make(map[string][]byte)
  211. if sc := existing[s3_constants.AmzStorageClass]; len(sc) > 0 {
  212. metadata[s3_constants.AmzStorageClass] = sc
  213. }
  214. if sc := reqHeader.Get(s3_constants.AmzStorageClass); len(sc) > 0 {
  215. metadata[s3_constants.AmzStorageClass] = []byte(sc)
  216. }
  217. if replaceMeta {
  218. for header, values := range reqHeader {
  219. if strings.HasPrefix(header, s3_constants.AmzUserMetaPrefix) {
  220. for _, value := range values {
  221. metadata[header] = []byte(value)
  222. }
  223. }
  224. }
  225. } else {
  226. for k, v := range existing {
  227. if strings.HasPrefix(k, s3_constants.AmzUserMetaPrefix) {
  228. metadata[k] = v
  229. }
  230. }
  231. }
  232. if replaceTagging {
  233. if tags := reqHeader.Get(s3_constants.AmzObjectTagging); tags != "" {
  234. for _, v := range strings.Split(tags, "&") {
  235. tag := strings.Split(v, "=")
  236. if len(tag) == 2 {
  237. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  238. } else if len(tag) == 1 {
  239. metadata[s3_constants.AmzObjectTagging+"-"+tag[0]] = nil
  240. }
  241. }
  242. }
  243. } else {
  244. for k, v := range existing {
  245. if strings.HasPrefix(k, s3_constants.AmzObjectTagging) {
  246. metadata[k] = v
  247. }
  248. }
  249. delete(metadata, s3_constants.AmzTagCount)
  250. }
  251. return
  252. }