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.

244 lines
6.8 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. package s3api
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "errors"
  6. "fmt"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/s3api/policy"
  9. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  10. "github.com/dustin/go-humanize"
  11. "github.com/gorilla/mux"
  12. "io"
  13. "io/ioutil"
  14. "mime/multipart"
  15. "net/http"
  16. "net/url"
  17. "strings"
  18. )
  19. func (s3a *S3ApiServer) PostPolicyBucketHandler(w http.ResponseWriter, r *http.Request) {
  20. // https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html
  21. // https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
  22. bucket := mux.Vars(r)["bucket"]
  23. glog.V(3).Infof("PostPolicyBucketHandler %s", bucket)
  24. reader, err := r.MultipartReader()
  25. if err != nil {
  26. s3err.WriteErrorResponse(w, s3err.ErrMalformedPOSTRequest, r)
  27. return
  28. }
  29. form, err := reader.ReadForm(int64(5 * humanize.MiByte))
  30. if err != nil {
  31. s3err.WriteErrorResponse(w, s3err.ErrMalformedPOSTRequest, r)
  32. return
  33. }
  34. defer form.RemoveAll()
  35. fileBody, fileName, fileSize, formValues, err := extractPostPolicyFormValues(form)
  36. if err != nil {
  37. s3err.WriteErrorResponse(w, s3err.ErrMalformedPOSTRequest, r)
  38. return
  39. }
  40. if fileBody == nil {
  41. s3err.WriteErrorResponse(w, s3err.ErrPOSTFileRequired, r)
  42. return
  43. }
  44. defer fileBody.Close()
  45. formValues.Set("Bucket", bucket)
  46. if fileName != "" && strings.Contains(formValues.Get("Key"), "${filename}") {
  47. formValues.Set("Key", strings.Replace(formValues.Get("Key"), "${filename}", fileName, -1))
  48. }
  49. object := formValues.Get("Key")
  50. successRedirect := formValues.Get("success_action_redirect")
  51. successStatus := formValues.Get("success_action_status")
  52. var redirectURL *url.URL
  53. if successRedirect != "" {
  54. redirectURL, err = url.Parse(successRedirect)
  55. if err != nil {
  56. s3err.WriteErrorResponse(w, s3err.ErrMalformedPOSTRequest, r)
  57. return
  58. }
  59. }
  60. // Verify policy signature.
  61. errCode := s3a.iam.doesPolicySignatureMatch(formValues)
  62. if errCode != s3err.ErrNone {
  63. s3err.WriteErrorResponse(w, errCode, r)
  64. return
  65. }
  66. policyBytes, err := base64.StdEncoding.DecodeString(formValues.Get("Policy"))
  67. if err != nil {
  68. s3err.WriteErrorResponse(w, s3err.ErrMalformedPOSTRequest, r)
  69. return
  70. }
  71. // Handle policy if it is set.
  72. if len(policyBytes) > 0 {
  73. postPolicyForm, err := policy.ParsePostPolicyForm(string(policyBytes))
  74. if err != nil {
  75. s3err.WriteErrorResponse(w, s3err.ErrPostPolicyConditionInvalidFormat, r)
  76. return
  77. }
  78. // Make sure formValues adhere to policy restrictions.
  79. if err = policy.CheckPostPolicy(formValues, postPolicyForm); err != nil {
  80. w.Header().Set("Location", r.URL.Path)
  81. w.WriteHeader(http.StatusTemporaryRedirect)
  82. return
  83. }
  84. // Ensure that the object size is within expected range, also the file size
  85. // should not exceed the maximum single Put size (5 GiB)
  86. lengthRange := postPolicyForm.Conditions.ContentLengthRange
  87. if lengthRange.Valid {
  88. if fileSize < lengthRange.Min {
  89. s3err.WriteErrorResponse(w, s3err.ErrEntityTooSmall, r)
  90. return
  91. }
  92. if fileSize > lengthRange.Max {
  93. s3err.WriteErrorResponse(w, s3err.ErrEntityTooLarge, r)
  94. return
  95. }
  96. }
  97. }
  98. uploadUrl := fmt.Sprintf("http://%s%s/%s%s", s3a.option.Filer.ToHttpAddress(), s3a.option.BucketsPath, bucket, urlPathEscape(object))
  99. etag, errCode := s3a.putToFiler(r, uploadUrl, fileBody)
  100. if errCode != s3err.ErrNone {
  101. s3err.WriteErrorResponse(w, errCode, r)
  102. return
  103. }
  104. if successRedirect != "" {
  105. // Replace raw query params..
  106. redirectURL.RawQuery = getRedirectPostRawQuery(bucket, object, etag)
  107. w.Header().Set("Location", redirectURL.String())
  108. s3err.WriteEmptyResponse(w, http.StatusSeeOther)
  109. return
  110. }
  111. setEtag(w, etag)
  112. // Decide what http response to send depending on success_action_status parameter
  113. switch successStatus {
  114. case "201":
  115. resp := PostResponse{
  116. Bucket: bucket,
  117. Key: object,
  118. ETag: `"` + etag + `"`,
  119. Location: w.Header().Get("Location"),
  120. }
  121. s3err.WriteXMLResponse(w, http.StatusCreated, resp)
  122. case "200":
  123. s3err.WriteEmptyResponse(w, http.StatusOK)
  124. default:
  125. writeSuccessResponseEmpty(w)
  126. }
  127. }
  128. // Extract form fields and file data from a HTTP POST Policy
  129. func extractPostPolicyFormValues(form *multipart.Form) (filePart io.ReadCloser, fileName string, fileSize int64, formValues http.Header, err error) {
  130. /// HTML Form values
  131. fileName = ""
  132. // Canonicalize the form values into http.Header.
  133. formValues = make(http.Header)
  134. for k, v := range form.Value {
  135. formValues[http.CanonicalHeaderKey(k)] = v
  136. }
  137. // Validate form values.
  138. if err = validateFormFieldSize(formValues); err != nil {
  139. return nil, "", 0, nil, err
  140. }
  141. // this means that filename="" was not specified for file key and Go has
  142. // an ugly way of handling this situation. Refer here
  143. // https://golang.org/src/mime/multipart/formdata.go#L61
  144. if len(form.File) == 0 {
  145. var b = &bytes.Buffer{}
  146. for _, v := range formValues["File"] {
  147. b.WriteString(v)
  148. }
  149. fileSize = int64(b.Len())
  150. filePart = ioutil.NopCloser(b)
  151. return filePart, fileName, fileSize, formValues, nil
  152. }
  153. // Iterator until we find a valid File field and break
  154. for k, v := range form.File {
  155. canonicalFormName := http.CanonicalHeaderKey(k)
  156. if canonicalFormName == "File" {
  157. if len(v) == 0 {
  158. return nil, "", 0, nil, errors.New("Invalid arguments specified")
  159. }
  160. // Fetch fileHeader which has the uploaded file information
  161. fileHeader := v[0]
  162. // Set filename
  163. fileName = fileHeader.Filename
  164. // Open the uploaded part
  165. filePart, err = fileHeader.Open()
  166. if err != nil {
  167. return nil, "", 0, nil, err
  168. }
  169. // Compute file size
  170. fileSize, err = filePart.(io.Seeker).Seek(0, 2)
  171. if err != nil {
  172. return nil, "", 0, nil, err
  173. }
  174. // Reset Seek to the beginning
  175. _, err = filePart.(io.Seeker).Seek(0, 0)
  176. if err != nil {
  177. return nil, "", 0, nil, err
  178. }
  179. // File found and ready for reading
  180. break
  181. }
  182. }
  183. return filePart, fileName, fileSize, formValues, nil
  184. }
  185. // Validate form field size for s3 specification requirement.
  186. func validateFormFieldSize(formValues http.Header) error {
  187. // Iterate over form values
  188. for k := range formValues {
  189. // Check if value's field exceeds S3 limit
  190. if int64(len(formValues.Get(k))) > int64(1*humanize.MiByte) {
  191. return errors.New("Data size larger than expected")
  192. }
  193. }
  194. // Success.
  195. return nil
  196. }
  197. func getRedirectPostRawQuery(bucket, key, etag string) string {
  198. redirectValues := make(url.Values)
  199. redirectValues.Set("bucket", bucket)
  200. redirectValues.Set("key", key)
  201. redirectValues.Set("etag", "\""+etag+"\"")
  202. return redirectValues.Encode()
  203. }
  204. // Check to see if Policy is signed correctly.
  205. func (iam *IdentityAccessManagement) doesPolicySignatureMatch(formValues http.Header) s3err.ErrorCode {
  206. // For SignV2 - Signature field will be valid
  207. if _, ok := formValues["Signature"]; ok {
  208. return iam.doesPolicySignatureV2Match(formValues)
  209. }
  210. return iam.doesPolicySignatureV4Match(formValues)
  211. }