From 480a1baa20cfc184f68685ee1bb7f886e771fe2a Mon Sep 17 00:00:00 2001 From: Chris Lu Date: Mon, 30 Nov 2026 15:09:19 -0800 Subject: [PATCH] s3api: GetPart, reading parts of in-progress and completed multipart uploads (#13174) * s3api: GetPart reads one part of a multipart upload GET /key?part&partNumber=N&uploadId=X serves the latest attempt of an open upload's part, or the bytes that part became in the object a completed upload assembled, including a version that is no longer latest. x-amz-multipart-upload-status says which. A Range counts within the part, and a whole part answers 200 even though a completed part is served as a range of the object. The route sits ahead of ListParts and claims any ?part request, so a missing partNumber is InvalidArgument rather than a listing, and the request resolves to s3:GetObject, not the ListParts grant. * s3api: reading an open upload's part needs s3:GetIncompleteUpload AWS gates GetPart on an upload that has not completed behind s3:GetIncompleteUpload on top of s3:GetObject, so a plain read grant does not start exposing data its writer has not committed yet. The action is its own legacy grant too; Read alone does not carry it, Admin does. A completed upload's part needs only the read grant, plus s3:GetObjectVersion when it lives in a version. * s3api: a GetPart request carrying ?uploads is not a multipart listing Co-Authored-By: Claude Opus 5.5 * s3api: GetPart answers a completed empty part with an empty 200 Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- .../s3-example-integration-tests.yml | 7 + test/s3/normal/s3_get_part_test.go | 352 ++++++++++++++++++ .../view/app/policy_action_suggestions.go | 1 + weed/iam/helpers.go | 3 + weed/s3api/auth_credentials.go | 3 + weed/s3api/filer_multipart.go | 24 +- weed/s3api/s3_action_resolver.go | 8 +- weed/s3api/s3_constants/header.go | 1 + weed/s3api/s3_constants/s3_action_strings.go | 1 + weed/s3api/s3_constants/s3_actions.go | 2 + weed/s3api/s3_list_parts_action_test.go | 14 + weed/s3api/s3api_object_handlers_get_part.go | 250 +++++++++++++ .../s3api_object_handlers_get_part_test.go | 63 ++++ weed/s3api/s3api_server.go | 2 + weed/s3api/s3err/s3api_errors.go | 6 + 15 files changed, 724 insertions(+), 13 deletions(-) create mode 100644 test/s3/normal/s3_get_part_test.go create mode 100644 weed/s3api/s3api_object_handlers_get_part.go create mode 100644 weed/s3api/s3api_object_handlers_get_part_test.go diff --git a/.github/workflows/s3-example-integration-tests.yml b/.github/workflows/s3-example-integration-tests.yml index edd9dea91d..cf4819ded1 100644 --- a/.github/workflows/s3-example-integration-tests.yml +++ b/.github/workflows/s3-example-integration-tests.yml @@ -73,6 +73,13 @@ jobs: echo "=== Running S3 Prefix Object Tests ===" go test -v -timeout=180s -run TestS3PrefixObjectKeys ./... + - name: Run S3 GetPart Tests + timeout-minutes: 15 + working-directory: test/s3/normal + run: | + set -x + go test -v -timeout=180s -run TestS3GetPart ./... + - name: Run IAM Integration Tests timeout-minutes: 15 working-directory: test/s3/normal diff --git a/test/s3/normal/s3_get_part_test.go b/test/s3/normal/s3_get_part_test.go new file mode 100644 index 0000000000..45da72d336 --- /dev/null +++ b/test/s3/normal/s3_get_part_test.go @@ -0,0 +1,352 @@ +package example + +import ( + "bytes" + "encoding/base64" + "encoding/xml" + "fmt" + "hash/crc32" + "io" + "net/http" + "net/url" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/session" + v4 "github.com/aws/aws-sdk-go/aws/signer/v4" + "github.com/aws/aws-sdk-go/service/iam" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// getPart issues GetPart, which the SDK this suite pins predates, as a signed +// raw request. +func getPart(t *testing.T, cluster *TestCluster, creds *credentials.Credentials, bucket, key, uploadID string, partNumber int, header http.Header) (*http.Response, []byte) { + t.Helper() + query := url.Values{} + query.Set("part", "") + query.Set("partNumber", fmt.Sprint(partNumber)) + query.Set("uploadId", uploadID) + req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/%s/%s?%s", cluster.s3Endpoint, bucket, key, query.Encode()), nil) + require.NoError(t, err) + for k, v := range header { + req.Header[k] = v + } + _, err = v4.NewSigner(creds).Sign(req, nil, "s3", testRegion, time.Now()) + require.NoError(t, err) + resp, err := http.DefaultClient.Do(req) + require.NoError(t, err) + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + require.NoError(t, err) + return resp, body +} + +func errorCode(t *testing.T, body []byte) string { + t.Helper() + var e struct{ Code string } + require.NoError(t, xml.Unmarshal(body, &e), string(body)) + return e.Code +} + +func TestS3GetPart(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + cluster, err := startMiniCluster(t) + require.NoError(t, err) + defer cluster.Stop() + + client := cluster.s3Client + admin := client.Config.Credentials + bucket := createTestBucket(t, cluster, "test-get-part-") + key := "media/clip.bin" + + part1 := bytes.Repeat([]byte("a"), 5*1024*1024) + part1Retry := bytes.Repeat([]byte("c"), 5*1024*1024) + part2 := []byte("the last part, short") + + created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + require.NoError(t, err) + uploadID := aws.StringValue(created.UploadId) + upload := func(n int64, data []byte) *s3.UploadPartOutput { + out, err := client.UploadPart(&s3.UploadPartInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID), + PartNumber: aws.Int64(n), Body: bytes.NewReader(data), + }) + require.NoError(t, err) + return out + } + upload(1, part1) + retried := upload(1, part1Retry) + uploaded2 := upload(2, part2) + + t.Run("open upload serves the latest attempt", func(t *testing.T) { + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil) + require.Equal(t, http.StatusOK, resp.StatusCode, string(body)) + assert.Equal(t, "IN_PROGRESS", resp.Header.Get("x-amz-multipart-upload-status")) + assert.Equal(t, aws.StringValue(retried.ETag), resp.Header.Get("ETag")) + assert.Empty(t, resp.Header.Get("Content-Range")) + assert.True(t, bytes.Equal(part1Retry, body), "part 1 body is not the retried attempt") + }) + + t.Run("open upload range counts within the part", func(t *testing.T) { + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=4-7"}}) + require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body)) + assert.Equal(t, fmt.Sprintf("bytes 4-7/%d", len(part2)), resp.Header.Get("Content-Range")) + assert.Equal(t, string(part2[4:8]), string(body)) + }) + + t.Run("missing part", func(t *testing.T) { + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil) + require.Equal(t, http.StatusNotFound, resp.StatusCode) + assert.Equal(t, "NoSuchPart", errorCode(t, body)) + }) + + t.Run("sse request header is rejected", func(t *testing.T) { + resp, _ := getPart(t, cluster, admin, bucket, key, uploadID, 1, http.Header{"X-Amz-Server-Side-Encryption": {"AES256"}}) + assert.Equal(t, http.StatusBadRequest, resp.StatusCode) + }) + + t.Run("open part returns its checksum when asked", func(t *testing.T) { + data := []byte("checksummed part") + sum := crc32.ChecksumIEEE(data) + want := base64.StdEncoding.EncodeToString([]byte{byte(sum >> 24), byte(sum >> 16), byte(sum >> 8), byte(sum)}) + _, err := client.UploadPart(&s3.UploadPartInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID), + PartNumber: aws.Int64(5), Body: bytes.NewReader(data), ChecksumCRC32: aws.String(want), + }) + require.NoError(t, err) + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 5, http.Header{"X-Amz-Checksum-Mode": {"ENABLED"}}) + require.Equal(t, http.StatusOK, resp.StatusCode, string(body)) + assert.Equal(t, want, resp.Header.Get("x-amz-checksum-crc32")) + }) + + t.Run("ListParts still answers without ?part", func(t *testing.T) { + parts, err := client.ListParts(&s3.ListPartsInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID)}) + require.NoError(t, err) + require.Len(t, parts.Parts, 3) + }) + + _, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: aws.String(uploadID), + MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{ + {PartNumber: aws.Int64(1), ETag: retried.ETag}, + {PartNumber: aws.Int64(2), ETag: uploaded2.ETag}, + }}, + }) + require.NoError(t, err) + + t.Run("completed upload serves the part from the object", func(t *testing.T) { + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, nil) + require.Equal(t, http.StatusOK, resp.StatusCode, string(body)) + assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status")) + assert.Equal(t, aws.StringValue(uploaded2.ETag), resp.Header.Get("ETag")) + assert.Empty(t, resp.Header.Get("Content-Range")) + assert.Equal(t, string(part2), string(body)) + }) + + t.Run("completed upload range counts within the part", func(t *testing.T) { + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=-4"}}) + require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body)) + n := len(part2) + assert.Equal(t, fmt.Sprintf("bytes %d-%d/%d", n-4, n-1, n), resp.Header.Get("Content-Range")) + assert.Equal(t, string(part2[n-4:]), string(body)) + }) + + t.Run("completed upload has no such part", func(t *testing.T) { + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 3, nil) + require.Equal(t, http.StatusNotFound, resp.StatusCode) + assert.Equal(t, "NoSuchPart", errorCode(t, body)) + }) + + t.Run("completed upload in a version that is no longer latest", func(t *testing.T) { + vbucket := createTestBucket(t, cluster, "test-get-part-versioned-") + _, err := client.PutBucketVersioning(&s3.PutBucketVersioningInput{ + Bucket: aws.String(vbucket), VersioningConfiguration: &s3.VersioningConfiguration{Status: aws.String("Enabled")}, + }) + require.NoError(t, err) + created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(vbucket), Key: aws.String(key)}) + require.NoError(t, err) + out, err := client.UploadPart(&s3.UploadPartInput{ + Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId, + PartNumber: aws.Int64(1), Body: bytes.NewReader(part2), + }) + require.NoError(t, err) + done, err := client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{ + Bucket: aws.String(vbucket), Key: aws.String(key), UploadId: created.UploadId, + MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: out.ETag}}}, + }) + require.NoError(t, err) + _, err = client.PutObject(&s3.PutObjectInput{Bucket: aws.String(vbucket), Key: aws.String(key), Body: strings.NewReader("newer")}) + require.NoError(t, err) + + resp, body := getPart(t, cluster, admin, vbucket, key, aws.StringValue(created.UploadId), 1, nil) + require.Equal(t, http.StatusOK, resp.StatusCode, string(body)) + assert.Equal(t, aws.StringValue(done.VersionId), resp.Header.Get("x-amz-version-id")) + assert.Equal(t, string(part2), string(body)) + }) + + t.Run("completed empty part", func(t *testing.T) { + emptyKey := "media/empty-tail.bin" + created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(emptyKey)}) + require.NoError(t, err) + var parts []*s3.CompletedPart + for n, data := range [][]byte{part1, nil} { + out, err := client.UploadPart(&s3.UploadPartInput{ + Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId, + PartNumber: aws.Int64(int64(n + 1)), Body: bytes.NewReader(data), + }) + require.NoError(t, err) + parts = append(parts, &s3.CompletedPart{PartNumber: aws.Int64(int64(n + 1)), ETag: out.ETag}) + } + _, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(emptyKey), UploadId: created.UploadId, + MultipartUpload: &s3.CompletedMultipartUpload{Parts: parts}, + }) + require.NoError(t, err) + + resp, body := getPart(t, cluster, admin, bucket, emptyKey, aws.StringValue(created.UploadId), 2, nil) + require.Equal(t, http.StatusOK, resp.StatusCode, string(body)) + assert.Equal(t, "COMPLETED", resp.Header.Get("x-amz-multipart-upload-status")) + assert.Equal(t, aws.StringValue(parts[1].ETag), resp.Header.Get("ETag")) + assert.Empty(t, body) + }) + + t.Run("aborted upload", func(t *testing.T) { + other, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + require.NoError(t, err) + _, err = client.AbortMultipartUpload(&s3.AbortMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key), UploadId: other.UploadId}) + require.NoError(t, err) + resp, body := getPart(t, cluster, admin, bucket, key, aws.StringValue(other.UploadId), 1, nil) + require.Equal(t, http.StatusNotFound, resp.StatusCode) + assert.Equal(t, "NoSuchUpload", errorCode(t, body)) + }) +} + +// TestS3GetPartIncompleteUploadGrant checks that reading a part of an open +// upload needs s3:GetIncompleteUpload on top of s3:GetObject, while a +// completed upload's part needs only the read grant. +func TestS3GetPartIncompleteUploadGrant(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + cluster, err := startMiniCluster(t) + require.NoError(t, err) + defer cluster.Stop() + + client := cluster.s3Client + bucket := createTestBucket(t, cluster, "test-get-part-grant-") + openKey, doneKey := "open.bin", "done.bin" + + start := func(key string) (string, *s3.UploadPartOutput) { + created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{Bucket: aws.String(bucket), Key: aws.String(key)}) + require.NoError(t, err) + part, err := client.UploadPart(&s3.UploadPartInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId, + PartNumber: aws.Int64(1), Body: strings.NewReader("only part"), + }) + require.NoError(t, err) + return aws.StringValue(created.UploadId), part + } + openID, _ := start(openKey) + doneID, donePart := start(doneKey) + _, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(doneKey), UploadId: aws.String(doneID), + MultipartUpload: &s3.CompletedMultipartUpload{Parts: []*s3.CompletedPart{{PartNumber: aws.Int64(1), ETag: donePart.ETag}}}, + }) + require.NoError(t, err) + + sess, err := session.NewSession(client.Config.Copy()) + require.NoError(t, err) + iamClient := iam.New(sess) + userName := "getpart-reader" + _, err = iamClient.CreateUser(&iam.CreateUserInput{UserName: aws.String(userName)}) + require.NoError(t, err) + key, err := iamClient.CreateAccessKey(&iam.CreateAccessKeyInput{UserName: aws.String(userName)}) + require.NoError(t, err) + reader := credentials.NewStaticCredentials(aws.StringValue(key.AccessKey.AccessKeyId), aws.StringValue(key.AccessKey.SecretAccessKey), "") + + grant := func(actions ...string) { + policy := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["%s"],"Resource":["arn:aws:s3:::%s/*"]}]}`, strings.Join(actions, `","`), bucket) + _, err := iamClient.PutUserPolicy(&iam.PutUserPolicyInput{UserName: aws.String(userName), PolicyName: aws.String("reader"), PolicyDocument: aws.String(policy)}) + require.NoError(t, err) + } + expectStatus := func(t *testing.T, key, uploadID string, want int) { + t.Helper() + require.Eventually(t, func() bool { + resp, _ := getPart(t, cluster, reader, bucket, key, uploadID, 1, nil) + return resp.StatusCode == want + }, 10*time.Second, 200*time.Millisecond) + } + + grant("s3:GetObject") + t.Run("read grant alone reads a completed part", func(t *testing.T) { + expectStatus(t, doneKey, doneID, http.StatusOK) + }) + t.Run("read grant alone cannot read an open part", func(t *testing.T) { + expectStatus(t, openKey, openID, http.StatusForbidden) + }) + + grant("s3:GetObject", "s3:GetIncompleteUpload") + t.Run("GetIncompleteUpload opens the part", func(t *testing.T) { + expectStatus(t, openKey, openID, http.StatusOK) + }) +} + +// TestS3GetPartSSES3 reads SSE-S3 parts back decrypted, before and after the +// upload completes. +func TestS3GetPartSSES3(t *testing.T) { + if testing.Short() { + t.Skip("Skipping integration test in short mode") + } + cluster, err := startMiniCluster(t) + require.NoError(t, err) + defer cluster.Stop() + + client := cluster.s3Client + admin := client.Config.Credentials + bucket := createTestBucket(t, cluster, "test-get-part-sse-") + key := "secret.bin" + part1 := bytes.Repeat([]byte("0123456789"), 600*1024) + part2 := []byte("encrypted tail") + + created, err := client.CreateMultipartUpload(&s3.CreateMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(key), ServerSideEncryption: aws.String("AES256"), + }) + require.NoError(t, err) + var completed []*s3.CompletedPart + for i, data := range [][]byte{part1, part2} { + out, err := client.UploadPart(&s3.UploadPartInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId, + PartNumber: aws.Int64(int64(i + 1)), Body: bytes.NewReader(data), + }) + require.NoError(t, err) + completed = append(completed, &s3.CompletedPart{PartNumber: aws.Int64(int64(i + 1)), ETag: out.ETag}) + } + uploadID := aws.StringValue(created.UploadId) + + check := func(t *testing.T, status string) { + resp, body := getPart(t, cluster, admin, bucket, key, uploadID, 1, nil) + require.Equal(t, http.StatusOK, resp.StatusCode, string(body)) + assert.Equal(t, status, resp.Header.Get("x-amz-multipart-upload-status")) + assert.True(t, bytes.Equal(part1, body), "part 1 does not decrypt to what was uploaded") + + resp, body = getPart(t, cluster, admin, bucket, key, uploadID, 2, http.Header{"Range": {"bytes=0-8"}}) + require.Equal(t, http.StatusPartialContent, resp.StatusCode, string(body)) + assert.Equal(t, fmt.Sprintf("bytes 0-8/%d", len(part2)), resp.Header.Get("Content-Range")) + assert.Equal(t, string(part2[:9]), string(body)) + } + t.Run("open", func(t *testing.T) { check(t, "IN_PROGRESS") }) + + _, err = client.CompleteMultipartUpload(&s3.CompleteMultipartUploadInput{ + Bucket: aws.String(bucket), Key: aws.String(key), UploadId: created.UploadId, + MultipartUpload: &s3.CompletedMultipartUpload{Parts: completed}, + }) + require.NoError(t, err) + t.Run("completed", func(t *testing.T) { check(t, "COMPLETED") }) +} diff --git a/weed/admin/view/app/policy_action_suggestions.go b/weed/admin/view/app/policy_action_suggestions.go index 990312d098..3a5bae2830 100644 --- a/weed/admin/view/app/policy_action_suggestions.go +++ b/weed/admin/view/app/policy_action_suggestions.go @@ -56,6 +56,7 @@ func buildPolicyActionSuggestions() []string { s3_constants.S3_ACTION_UPLOAD_PART_COPY, s3_constants.S3_ACTION_LIST_PARTS, s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS, + s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD, s3_constants.S3_ACTION_CREATE_BUCKET, s3_constants.S3_ACTION_DELETE_BUCKET, s3_constants.S3_ACTION_LIST_BUCKET, diff --git a/weed/iam/helpers.go b/weed/iam/helpers.go index 0b4d78e4bc..ae174d312f 100644 --- a/weed/iam/helpers.go +++ b/weed/iam/helpers.go @@ -156,6 +156,7 @@ var baseS3ActionMap = map[string]string{ // resolved request action. "ListBucketMultipartUploads": s3_constants.ACTION_LIST_MULTIPART_UPLOADS, "ListMultipartUploadParts": s3_constants.ACTION_LIST_PARTS, + "GetIncompleteUpload": s3_constants.ACTION_GET_INCOMPLETE_UPLOAD, // Retention and legal hold operations "GetObjectRetention": s3_constants.ACTION_GET_OBJECT_RETENTION, "PutObjectRetention": s3_constants.ACTION_PUT_OBJECT_RETENTION, @@ -230,6 +231,8 @@ func MapToIdentitiesAction(action string) string { return "ListBucketMultipartUploads" case s3_constants.ACTION_LIST_PARTS: return "ListMultipartUploadParts" + case s3_constants.ACTION_GET_INCOMPLETE_UPLOAD: + return "GetIncompleteUpload" default: return "" } diff --git a/weed/s3api/auth_credentials.go b/weed/s3api/auth_credentials.go index d4b536a2a3..76be57d06e 100644 --- a/weed/s3api/auth_credentials.go +++ b/weed/s3api/auth_credentials.go @@ -2078,6 +2078,9 @@ func multipartListingAction(r *http.Request, action Action) Action { query := r.URL.Query() _, object := s3_constants.GetBucketAndObject(r) if object != "" && object != "/" && query.Has("uploadId") { + if query.Has("part") { + return "" + } return s3_constants.ACTION_LIST_PARTS } if query.Has("uploads") { diff --git a/weed/s3api/filer_multipart.go b/weed/s3api/filer_multipart.go index e8a51a194d..59dd2e0574 100644 --- a/weed/s3api/filer_multipart.go +++ b/weed/s3api/filer_multipart.go @@ -1260,7 +1260,7 @@ func (s3a *S3ApiServer) removeUploadDir(bucket, uploadId, object string) s3err.E glog.Errorf("bucket %s remove upload %s completed check: %v", bucket, uploadId, err) return s3err.ErrInternalError } - if completed { + if completed != nil { if err := s3a.uploadFiler(bucket, object).rm(context.Background(), s3a.genUploadsFolder(bucket), uploadId, false, true); err != nil { glog.V(1).Infof("bucket %s remove upload %s: %v", bucket, uploadId, err) return s3err.ErrInternalError @@ -1343,12 +1343,12 @@ func (s3a *S3ApiServer) uploadCommitPath(bucket, object string) (string, error) return dirName + "/" + entryName, nil } -// uploadCompleted reports whether the upload assembled into an object: the -// object entry, or any version file under .versions, still carries the -// upload id completion stamps on it. -func (s3a *S3ApiServer) uploadCompleted(bucket, uploadId, objectKey string) (bool, error) { +// uploadCompleted returns the object the upload assembled into: the object +// entry, or the version file under .versions, that still carries the +// upload id completion stamps on it; nil when there is none. +func (s3a *S3ApiServer) uploadCompleted(bucket, uploadId, objectKey string) (*filer_pb.Entry, error) { if objectKey == "" { - return false, nil + return nil, nil } bucketDir := s3a.bucketDir(bucket) name := path.Base(objectKey) @@ -1360,25 +1360,25 @@ func (s3a *S3ApiServer) uploadCompleted(bucket, uploadId, objectKey string) (boo entry, err := s3a.getObjectEntryRoutedByKey(bucket, objectKey) if err != nil && !isFilerNotFound(err) { - return false, err + return nil, err } if entry != nil && string(entry.Extended[s3_constants.SeaweedFSUploadId]) == uploadId { - return true, nil + return entry, nil } versions, _, err := s3a.listObjectScopedEntriesRoutedByKey(bucket, objectKey, objectDir+"/"+name+s3_constants.VersionsFolder, "", "", false, math.MaxInt32) if err != nil { if isFilerNotFound(err) { - return false, nil + return nil, nil } - return false, err + return nil, err } for _, version := range versions { if string(version.Extended[s3_constants.SeaweedFSUploadId]) == uploadId { - return true, nil + return version, nil } } - return false, nil + return nil, nil } type ListMultipartUploadsResult struct { diff --git a/weed/s3api/s3_action_resolver.go b/weed/s3api/s3_action_resolver.go index 52d6a282a3..16a288ff1e 100644 --- a/weed/s3api/s3_action_resolver.go +++ b/weed/s3api/s3_action_resolver.go @@ -45,7 +45,8 @@ func ResolveS3Action(r *http.Request, baseAction string, bucket string, object s s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD, s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD, s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG, - s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG: + s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG, + s3_constants.ACTION_GET_INCOMPLETE_UPLOAD: return mapBaseActionToS3Format(baseAction) } @@ -155,6 +156,9 @@ func resolveFromQueryParameters(query url.Values, method string, hasObject bool) case http.MethodDelete: return s3_constants.S3_ACTION_ABORT_MULTIPART case http.MethodGet: + if query.Has("part") { + return s3_constants.S3_ACTION_GET_OBJECT + } return s3_constants.S3_ACTION_LIST_PARTS } } @@ -417,6 +421,8 @@ func mapBaseActionToS3Format(baseAction string) string { return s3_constants.S3_ACTION_BYPASS_GOVERNANCE case s3_constants.ACTION_GET_OBJECT_RETENTION: return s3_constants.S3_ACTION_GET_OBJECT_RETENTION + case s3_constants.ACTION_GET_INCOMPLETE_UPLOAD: + return s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD case s3_constants.ACTION_PUT_OBJECT_RETENTION: return s3_constants.S3_ACTION_PUT_OBJECT_RETENTION case s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD: diff --git a/weed/s3api/s3_constants/header.go b/weed/s3api/s3_constants/header.go index 8a09583b9a..9261eddacb 100644 --- a/weed/s3api/s3_constants/header.go +++ b/weed/s3api/s3_constants/header.go @@ -69,6 +69,7 @@ const ( SeaweedFSExpiresS3 = "X-Seaweedfs-Expires-S3" SeaweedFSVectorSearchMode = "x-seaweedfs-vector-search-mode" AmzMpPartsCount = "x-amz-mp-parts-count" + AmzMultipartUploadStatus = "x-amz-multipart-upload-status" // S3 ACL headers AmzCannedAcl = "X-Amz-Acl" diff --git a/weed/s3api/s3_constants/s3_action_strings.go b/weed/s3api/s3_constants/s3_action_strings.go index d71ccfc46c..6297f37aac 100644 --- a/weed/s3api/s3_constants/s3_action_strings.go +++ b/weed/s3api/s3_constants/s3_action_strings.go @@ -45,6 +45,7 @@ const ( S3_ACTION_UPLOAD_PART_COPY = "s3:UploadPartCopy" S3_ACTION_LIST_PARTS = "s3:ListMultipartUploadParts" S3_ACTION_LIST_MULTIPART_UPLOADS = "s3:ListBucketMultipartUploads" + S3_ACTION_GET_INCOMPLETE_UPLOAD = "s3:GetIncompleteUpload" // Bucket operations S3_ACTION_CREATE_BUCKET = "s3:CreateBucket" diff --git a/weed/s3api/s3_constants/s3_actions.go b/weed/s3api/s3_constants/s3_actions.go index cb682aafdc..f411fd3c9b 100644 --- a/weed/s3api/s3_constants/s3_actions.go +++ b/weed/s3api/s3_constants/s3_actions.go @@ -28,6 +28,8 @@ const ( // these names must not widen into a general Read grant. ACTION_LIST_MULTIPART_UPLOADS = "ListBucketMultipartUploads" ACTION_LIST_PARTS = "ListMultipartUploadParts" + // Checked on top of Read before a part of an open upload is served. + ACTION_GET_INCOMPLETE_UPLOAD = "GetIncompleteUpload" SeaweedStorageDestinationHeader = "x-seaweedfs-destination" MultipartUploadsFolder = ".uploads" diff --git a/weed/s3api/s3_list_parts_action_test.go b/weed/s3api/s3_list_parts_action_test.go index e83be9be77..9edd23b7ae 100644 --- a/weed/s3api/s3_list_parts_action_test.go +++ b/weed/s3api/s3_list_parts_action_test.go @@ -56,6 +56,20 @@ func TestListPartsActionMapping(t *testing.T) { expectedAction: "s3:ListMultipartUploadParts", description: "GET request with uploadId plus other multipart params should map to s3:ListMultipartUploadParts", }, + { + name: "get_part", + method: "GET", + bucket: "test-bucket", + objectKey: "test-object.txt", + queryParams: map[string]string{ + "part": "", + "partNumber": "1", + "uploadId": "test-upload-id", + }, + fallbackAction: s3_constants.ACTION_READ, + expectedAction: "s3:GetObject", + description: "GetPart reads part bytes, so a ListParts grant must not cover it", + }, { name: "get_object_with_versionId", method: "GET", diff --git a/weed/s3api/s3api_object_handlers_get_part.go b/weed/s3api/s3api_object_handlers_get_part.go new file mode 100644 index 0000000000..b67e1836e2 --- /dev/null +++ b/weed/s3api/s3api_object_handlers_get_part.go @@ -0,0 +1,250 @@ +package s3api + +import ( + "fmt" + "net/http" + "strconv" + "strings" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/service/s3" + "github.com/seaweedfs/seaweedfs/weed/glog" + "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3err" +) + +const ( + multipartUploadStatusInProgress = "IN_PROGRESS" + multipartUploadStatusCompleted = "COMPLETED" +) + +// GetPartHandler reads one part of a multipart upload: the latest attempt of +// an open upload's part, or the bytes that part became in the object a +// completed upload assembled. +// https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetPart.html +func (s3a *S3ApiServer) GetPartHandler(w http.ResponseWriter, r *http.Request) { + bucket, object := s3_constants.GetBucketAndObject(r) + if errCode := s3a.checkBucket(r, bucket); errCode != s3err.ErrNone { + s3err.WriteErrorResponse(w, r, errCode) + return + } + + query := r.URL.Query() + partNumber, err := strconv.Atoi(query.Get("partNumber")) + if err != nil || partNumber < 1 || partNumber > s3_constants.MaxS3MultipartParts { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidArgument) + return + } + // GetPart decrypts SSE-S3/SSE-KMS parts on its own and never takes SSE-C + if r.Header.Get(s3_constants.AmzServerSideEncryption) != "" { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidArgument) + return + } + if r.Header.Get(s3_constants.AmzServerSideEncryptionCustomerAlgorithm) != "" { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest) + return + } + + uploadID := query.Get("uploadId") + if s3a.checkUploadId(object, uploadID) != nil { + s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchUpload) + return + } + + uploadEntry, err := s3a.uploadFiler(bucket, object).getEntry(s3a.genUploadsFolder(bucket), uploadID) + if err != nil && !isFilerNotFound(err) { + glog.Errorf("GetPart %s/%s upload %s: %v", bucket, object, uploadID, err) + s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) + return + } + if isMultipartUploadEntry(uploadEntry) { + s3a.getOpenUploadPart(w, r, bucket, object, uploadID, partNumber) + return + } + s3a.getCompletedUploadPart(w, r, bucket, object, uploadID, partNumber) +} + +func (s3a *S3ApiServer) getOpenUploadPart(w http.ResponseWriter, r *http.Request, bucket, object, uploadID string, partNumber int) { + if errCode := s3a.checkIncompleteUploadGrant(r, bucket, object); errCode != s3err.ErrNone { + s3err.WriteErrorResponse(w, r, errCode) + return + } + part, err := s3a.latestPartAttempt(bucket, object, uploadID, partNumber) + if err != nil { + if isFilerNotFound(err) { + s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchUpload) + return + } + glog.Errorf("GetPart %s/%s upload %s part %d: %v", bucket, object, uploadID, partNumber, err) + s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) + return + } + if part == nil { + s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchPart) + return + } + sseType := s3a.detectPrimarySSEType(part) + if sseType == s3_constants.SSETypeC { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest) + return + } + w.Header().Set(s3_constants.AmzMultipartUploadStatus, multipartUploadStatusInProgress) + setEtag(w, getEtagFromEntry(part)) + // setResponseHeaders leaves out the checksum on any partNumber read, but a + // whole open part is exactly what its stored checksum covers. + if r.Header.Get("Range") == "" && strings.EqualFold(r.Header.Get(s3_constants.AmzChecksumMode), "ENABLED") { + if name, value := part.Extended[s3_constants.ExtChecksumAlgorithm], part.Extended[s3_constants.ExtChecksumValue]; len(name) > 0 && len(value) > 0 { + w.Header().Set(string(name), string(value)) + } + } + s3a.streamPart(w, r, part, sseType, bucket, object, "") +} + +func (s3a *S3ApiServer) getCompletedUploadPart(w http.ResponseWriter, r *http.Request, bucket, object, uploadID string, partNumber int) { + entry, err := s3a.uploadCompleted(bucket, uploadID, object) + if err != nil { + glog.Errorf("GetPart %s/%s upload %s completed check: %v", bucket, object, uploadID, err) + s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) + return + } + if entry == nil { + s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchUpload) + return + } + + versionId := string(entry.Extended[s3_constants.ExtVersionIdKey]) + var errCode s3err.ErrorCode + if versionId != "" { + errCode = s3a.checkVersionReadGrant(r, bucket, object, versionId, entry.Extended) + } else { + errCode = s3a.recheckPolicyWithObjectEntry(r, bucket, object, string(s3_constants.ACTION_READ), entry.Extended, "GetPartHandler") + } + if errCode != s3err.ErrNone { + s3err.WriteErrorResponse(w, r, errCode) + return + } + + sseType := s3a.detectPrimarySSEType(entry) + if sseType == s3_constants.SSETypeC { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRequest) + return + } + + // Without recorded boundaries the part cannot be told apart from its + // neighbours, and guessing one chunk per part would serve the wrong bytes. + _, partInfo, _ := s3a.getMultipartInfo(entry, partNumber) + if partInfo == nil { + s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchPart) + return + } + if partInfo.EndChunk == partInfo.StartChunk && partInfo.EndOffset <= partInfo.StartOffset { + if r.Header.Get("Range") != "" { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange) + return + } + if versionId != "" { + w.Header().Set("x-amz-version-id", versionId) + } + w.Header().Set(s3_constants.AmzMultipartUploadStatus, multipartUploadStatusCompleted) + setEtag(w, partInfo.ETag) + w.Header().Set("Content-Length", "0") + w.WriteHeader(http.StatusOK) + return + } + partStart, partEnd, ok := partRange(partInfo, entry.Chunks) + if !ok { + glog.Errorf("GetPart %s/%s upload %s: part %d boundary out of range", bucket, object, uploadID, partNumber) + s3err.WriteErrorResponse(w, r, s3err.ErrInternalError) + return + } + readStart, readEnd := partStart, partEnd + clientRange := r.Header.Get("Range") + if clientRange != "" { + if readStart, readEnd, err = adjustRangeForPart(partStart, partEnd, clientRange); err != nil { + s3err.WriteErrorResponse(w, r, s3err.ErrInvalidRange) + return + } + } + r.Header.Set("Range", fmt.Sprintf("bytes=%d-%d", readStart, readEnd)) + + if versionId != "" { + w.Header().Set("x-amz-version-id", versionId) + } + w.Header().Set(s3_constants.AmzMultipartUploadStatus, multipartUploadStatusCompleted) + setEtag(w, partInfo.ETag) + pw := &partRangeWriter{ + ResponseWriter: w, + ranged: clientRange != "", + contentRange: fmt.Sprintf("bytes %d-%d/%d", readStart-partStart, readEnd-partStart, partEnd-partStart+1), + } + s3a.streamPart(pw, r, entry, sseType, bucket, object, versionId) +} + +func (s3a *S3ApiServer) streamPart(w http.ResponseWriter, r *http.Request, entry *filer_pb.Entry, sseType, bucket, object, versionId string) { + if err := s3a.streamFromVolumeServersWithSSE(w, r, entry, sseType, bucket, object, versionId); err != nil { + if streamCanceled(r.Context(), err) { + logCanceledStream(r, "GetPartHandler", bucket, object, err) + } else { + glog.Errorf("GetPart %s/%s: %v", bucket, object, err) + } + writeStreamErrorResponse(w, r, err) + } +} + +// latestPartAttempt returns the newest stored attempt of an open upload's +// part, or nil when that part number was never uploaded. +func (s3a *S3ApiServer) latestPartAttempt(bucket, object, uploadID string, partNumber int) (*filer_pb.Entry, error) { + input := &s3.ListPartsInput{ + Bucket: aws.String(bucket), + Key: aws.String(object), + UploadId: aws.String(uploadID), + MaxParts: aws.Int64(1), + } + var latest *filer_pb.Entry + // "%04d" also prefixes the five-digit part number 10000 under part 1000 + name := fmt.Sprintf("%04d", partNumber) + _, err := s3a.scanPartAttempts(input, name, name, func(n int) bool { return n == partNumber }, func(_ int, entry *filer_pb.Entry) bool { + if latest == nil || compareLatestPartAttempt(entry, latest) < 0 { + latest = entry + } + return false + }) + return latest, err +} + +// checkIncompleteUploadGrant enforces s3:GetIncompleteUpload, which AWS +// requires on top of the read grant before a part of an open upload is served. +func (s3a *S3ApiServer) checkIncompleteUploadGrant(r *http.Request, bucket, object string) s3err.ErrorCode { + if identity, ok := s3_constants.GetIdentityFromContext(r).(*Identity); ok && identity != nil { + if errCode := s3a.iam.VerifyActionPermission(r, identity, s3_constants.ACTION_GET_INCOMPLETE_UPLOAD, bucket, object); errCode != s3err.ErrNone { + return errCode + } + } + return s3a.recheckPolicyWithObjectEntry(r, bucket, object, s3_constants.ACTION_GET_INCOMPLETE_UPLOAD, nil, "GetPartHandler") +} + +// partRangeWriter answers a read of a completed upload's part the way GetPart +// does: byte positions count from the part's start, and a read of the whole +// part is a 200 rather than the object range it was served as. +type partRangeWriter struct { + http.ResponseWriter + ranged bool + contentRange string +} + +func (p *partRangeWriter) WriteHeader(code int) { + if code == http.StatusPartialContent { + if p.ranged { + p.Header().Set("Content-Range", p.contentRange) + } else { + p.Header().Del("Content-Range") + code = http.StatusOK + } + } + p.ResponseWriter.WriteHeader(code) +} + +func (p *partRangeWriter) Unwrap() http.ResponseWriter { + return p.ResponseWriter +} diff --git a/weed/s3api/s3api_object_handlers_get_part_test.go b/weed/s3api/s3api_object_handlers_get_part_test.go new file mode 100644 index 0000000000..670638da0a --- /dev/null +++ b/weed/s3api/s3api_object_handlers_get_part_test.go @@ -0,0 +1,63 @@ +package s3api + +import ( + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/gorilla/mux" + "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" + "github.com/stretchr/testify/assert" +) + +func getPartRequest() *http.Request { + req := &http.Request{ + Method: http.MethodGet, + URL: &url.URL{Path: "/bucket/key", RawQuery: "part&partNumber=1&uploadId=abc"}, + } + return mux.SetURLVars(req, map[string]string{"bucket": "bucket", "object": "key"}) +} + +func TestGetPartIncompleteUploadActionIgnoresRequestShape(t *testing.T) { + assert.Equal(t, s3_constants.S3_ACTION_GET_INCOMPLETE_UPLOAD, + ResolveS3Action(getPartRequest(), s3_constants.ACTION_GET_INCOMPLETE_UPLOAD, "bucket", "key")) +} + +func TestGetPartIsNotAPartsListing(t *testing.T) { + assert.Equal(t, Action(""), multipartListingAction(getPartRequest(), s3_constants.ACTION_READ)) + + withUploads := getPartRequest() + withUploads.URL.RawQuery = "part&partNumber=1&uploadId=abc&uploads" + assert.Equal(t, Action(""), multipartListingAction(withUploads, s3_constants.ACTION_READ)) + + listing := getPartRequest() + listing.URL.RawQuery = "uploadId=abc" + assert.Equal(t, Action(s3_constants.ACTION_LIST_PARTS), multipartListingAction(listing, s3_constants.ACTION_READ)) +} + +func TestPartRangeWriter(t *testing.T) { + cases := []struct { + name string + ranged bool + wantStatus int + wantRangeHdr string + }{ + {"whole part answers 200", false, http.StatusOK, ""}, + {"ranged read counts within the part", true, http.StatusPartialContent, "bytes 2-5/10"}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + rec := httptest.NewRecorder() + w := &partRangeWriter{ResponseWriter: rec, ranged: c.ranged, contentRange: "bytes 2-5/10"} + w.Header().Set("Content-Range", "bytes 102-105/4096") + w.WriteHeader(http.StatusPartialContent) + assert.Equal(t, c.wantStatus, rec.Code) + assert.Equal(t, c.wantRangeHdr, rec.Header().Get("Content-Range")) + }) + } + + rec := httptest.NewRecorder() + (&partRangeWriter{ResponseWriter: rec}).WriteHeader(http.StatusInternalServerError) + assert.Equal(t, http.StatusInternalServerError, rec.Code) +} diff --git a/weed/s3api/s3api_server.go b/weed/s3api/s3api_server.go index db454ab44a..5fe8f2dbff 100644 --- a/weed/s3api/s3api_server.go +++ b/weed/s3api/s3api_server.go @@ -1100,6 +1100,8 @@ func (s3a *S3ApiServer) registerRouter(router *mux.Router) { bucket.Methods(http.MethodPost).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.NewMultipartUploadHandler, ACTION_WRITE)), "POST")).Queries("uploads", "") // AbortMultipartUpload bucket.Methods(http.MethodDelete).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.AbortMultipartUploadHandler, ACTION_WRITE)), "DELETE")).Queries("uploadId", "{uploadId:.*}") + // GetPart; partNumber is checked by the handler so a ?part request never falls through to ListParts + bucket.Methods(http.MethodGet).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.GetPartHandler, ACTION_READ)), "GET")).Queries("part", "", "uploadId", "{uploadId:.*}") // ListObjectParts bucket.Methods(http.MethodGet).Path(objectPath).HandlerFunc(track(s3a.iam.Auth(s3a.cb.Limit(s3a.ListObjectPartsHandler, ACTION_READ)), "GET")).Queries("uploadId", "{uploadId:.*}") // ListMultipartUploads diff --git a/weed/s3api/s3err/s3api_errors.go b/weed/s3api/s3err/s3api_errors.go index 56abe1bbb2..1509daadd4 100644 --- a/weed/s3api/s3err/s3api_errors.go +++ b/weed/s3api/s3err/s3api_errors.go @@ -61,6 +61,7 @@ const ( ErrNoSuchKey ErrNoSuchVersion ErrNoSuchUpload + ErrNoSuchPart ErrInvalidBucketName ErrInvalidBucketState ErrInvalidDigest @@ -346,6 +347,11 @@ var errorCodeResponse = map[ErrorCode]APIError{ Description: "The specified multipart upload does not exist. The upload ID may be invalid, or the upload may have been aborted or completed.", HTTPStatusCode: http.StatusNotFound, }, + ErrNoSuchPart: { + Code: "NoSuchPart", + Description: "The specified part does not exist. The part may not have been uploaded.", + HTTPStatusCode: http.StatusNotFound, + }, ErrInternalError: { Code: "InternalError", Description: "We encountered an internal error, please try again.",