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.

256 lines
7.3 KiB

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