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.

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