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.

309 lines
8.9 KiB

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