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.

301 lines
8.5 KiB

4 years ago
3 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
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. headers "github.com/chrislusf/seaweedfs/weed/s3api/http"
  6. xhttp "github.com/chrislusf/seaweedfs/weed/s3api/http"
  7. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  8. "modernc.org/strutil"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/chrislusf/seaweedfs/weed/util"
  15. )
  16. const (
  17. DirectiveCopy = "COPY"
  18. DirectiveReplace = "REPLACE"
  19. )
  20. func (s3a *S3ApiServer) CopyObjectHandler(w http.ResponseWriter, r *http.Request) {
  21. dstBucket, dstObject := xhttp.GetBucketAndObject(r)
  22. // Copy source path.
  23. cpSrcPath, err := url.QueryUnescape(r.Header.Get("X-Amz-Copy-Source"))
  24. if err != nil {
  25. // Save unescaped string as is.
  26. cpSrcPath = r.Header.Get("X-Amz-Copy-Source")
  27. }
  28. srcBucket, srcObject := pathToBucketAndObject(cpSrcPath)
  29. glog.V(3).Infof("CopyObjectHandler %s %s => %s %s", srcBucket, srcObject, dstBucket, dstObject)
  30. replaceMeta, replaceTagging := replaceDirective(r.Header)
  31. if (srcBucket == dstBucket && srcObject == dstObject || cpSrcPath == "") && (replaceMeta || replaceTagging) {
  32. fullPath := util.FullPath(fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, dstBucket, dstObject))
  33. dir, name := fullPath.DirAndName()
  34. entry, err := s3a.getEntry(dir, name)
  35. if err != nil || entry.IsDirectory {
  36. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  37. return
  38. }
  39. entry.Extended = processMetadataBytes(r.Header, entry.Extended, replaceMeta, replaceTagging)
  40. err = s3a.touch(dir, name, entry)
  41. if err != nil {
  42. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  43. return
  44. }
  45. writeSuccessResponseXML(w, r, CopyObjectResult{
  46. ETag: fmt.Sprintf("%x", entry.Attributes.Md5),
  47. LastModified: time.Now().UTC(),
  48. })
  49. return
  50. }
  51. // If source object is empty or bucket is empty, reply back invalid copy source.
  52. if srcObject == "" || srcBucket == "" {
  53. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  54. return
  55. }
  56. srcPath := util.FullPath(fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, srcBucket, srcObject))
  57. dir, name := srcPath.DirAndName()
  58. if entry, err := s3a.getEntry(dir, name); err != nil || entry.IsDirectory {
  59. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  60. return
  61. }
  62. if srcBucket == dstBucket && srcObject == dstObject {
  63. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopyDest)
  64. return
  65. }
  66. dstUrl := fmt.Sprintf("http://%s%s/%s%s?collection=%s",
  67. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, dstBucket, urlPathEscape(dstObject), dstBucket)
  68. srcUrl := fmt.Sprintf("http://%s%s/%s%s",
  69. s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, srcBucket, urlPathEscape(srcObject))
  70. _, _, resp, err := util.DownloadFile(srcUrl, s3a.maybeGetFilerJwtAuthorizationToken(false))
  71. if err != nil {
  72. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  73. return
  74. }
  75. defer util.CloseResponse(resp)
  76. tagErr := processMetadata(r.Header, resp.Header, replaceMeta, replaceTagging, s3a.getTags, dir, name)
  77. if tagErr != nil {
  78. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidCopySource)
  79. return
  80. }
  81. glog.V(2).Infof("copy from %s to %s", srcUrl, dstUrl)
  82. etag, errCode := s3a.putToFiler(r, dstUrl, resp.Body)
  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, _ := xhttp.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?collection=%s",
  137. s3a.option.Filer.ToHttpAddress(), s3a.genUploadsFolder(dstBucket), uploadID, partID, dstBucket)
  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. etag, errCode := s3a.putToFiler(r, dstUrl, dataReader)
  148. if errCode != s3err.ErrNone {
  149. s3err.WriteErrorResponse(w, r, errCode)
  150. return
  151. }
  152. setEtag(w, etag)
  153. response := CopyPartResult{
  154. ETag: etag,
  155. LastModified: time.Now().UTC(),
  156. }
  157. writeSuccessResponseXML(w, r, response)
  158. }
  159. func replaceDirective(reqHeader http.Header) (replaceMeta, replaceTagging bool) {
  160. return reqHeader.Get(headers.AmzUserMetaDirective) == DirectiveReplace, reqHeader.Get(headers.AmzObjectTaggingDirective) == DirectiveReplace
  161. }
  162. 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) {
  163. if sc := reqHeader.Get(xhttp.AmzStorageClass); len(sc) == 0 {
  164. if sc := existing[xhttp.AmzStorageClass]; len(sc) > 0 {
  165. reqHeader[xhttp.AmzStorageClass] = sc
  166. }
  167. }
  168. if !replaceMeta {
  169. for header, _ := range reqHeader {
  170. if strings.HasPrefix(header, xhttp.AmzUserMetaPrefix) {
  171. delete(reqHeader, header)
  172. }
  173. }
  174. for k, v := range existing {
  175. if strings.HasPrefix(k, xhttp.AmzUserMetaPrefix) {
  176. reqHeader[k] = v
  177. }
  178. }
  179. }
  180. if !replaceTagging {
  181. for header, _ := range reqHeader {
  182. if strings.HasPrefix(header, xhttp.AmzObjectTagging) {
  183. delete(reqHeader, header)
  184. }
  185. }
  186. found := false
  187. for k, _ := range existing {
  188. if strings.HasPrefix(k, xhttp.AmzObjectTaggingPrefix) {
  189. found = true
  190. break
  191. }
  192. }
  193. if found {
  194. tags, err := getTags(dir, name)
  195. if err != nil {
  196. return err
  197. }
  198. var tagArr []string
  199. for k, v := range tags {
  200. tagArr = append(tagArr, fmt.Sprintf("%s=%s", k, v))
  201. }
  202. tagStr := strutil.JoinFields(tagArr, "&")
  203. reqHeader.Set(xhttp.AmzObjectTagging, tagStr)
  204. }
  205. }
  206. return
  207. }
  208. func processMetadataBytes(reqHeader http.Header, existing map[string][]byte, replaceMeta, replaceTagging bool) (metadata map[string][]byte) {
  209. metadata = make(map[string][]byte)
  210. if sc := existing[xhttp.AmzStorageClass]; len(sc) > 0 {
  211. metadata[xhttp.AmzStorageClass] = sc
  212. }
  213. if sc := reqHeader.Get(xhttp.AmzStorageClass); len(sc) > 0 {
  214. metadata[xhttp.AmzStorageClass] = []byte(sc)
  215. }
  216. if replaceMeta {
  217. for header, values := range reqHeader {
  218. if strings.HasPrefix(header, xhttp.AmzUserMetaPrefix) {
  219. for _, value := range values {
  220. metadata[header] = []byte(value)
  221. }
  222. }
  223. }
  224. } else {
  225. for k, v := range existing {
  226. if strings.HasPrefix(k, xhttp.AmzUserMetaPrefix) {
  227. metadata[k] = v
  228. }
  229. }
  230. }
  231. if replaceTagging {
  232. if tags := reqHeader.Get(xhttp.AmzObjectTagging); tags != "" {
  233. for _, v := range strings.Split(tags, "&") {
  234. tag := strings.Split(v, "=")
  235. if len(tag) == 2 {
  236. metadata[xhttp.AmzObjectTagging+"-"+tag[0]] = []byte(tag[1])
  237. } else if len(tag) == 1 {
  238. metadata[xhttp.AmzObjectTagging+"-"+tag[0]] = nil
  239. }
  240. }
  241. }
  242. } else {
  243. for k, v := range existing {
  244. if strings.HasPrefix(k, xhttp.AmzObjectTagging) {
  245. metadata[k] = v
  246. }
  247. }
  248. delete(metadata, xhttp.AmzTagCount)
  249. }
  250. return
  251. }