diff --git a/compatibility-tests/.gitignore b/compatibility-tests/.gitignore index c31b65ae04..522724d6dd 100644 --- a/compatibility-tests/.gitignore +++ b/compatibility-tests/.gitignore @@ -66,3 +66,7 @@ Thumbs.db # Local Personal files/test *-local.* + +# Generated by the Terraform / OpenTofu compat setup for aws_s3_object.large +compat-terraform/large-object.bin +compat-opentofu/large-object.bin diff --git a/compatibility-tests/compat-opentofu/Dockerfile b/compatibility-tests/compat-opentofu/Dockerfile index 0bbfea289c..20bb03a4e1 100644 --- a/compatibility-tests/compat-opentofu/Dockerfile +++ b/compatibility-tests/compat-opentofu/Dockerfile @@ -1,6 +1,8 @@ FROM ghcr.io/opentofu/opentofu:1.8 AS opentofu -FROM amazon/aws-cli:2.15.52 +# Same CLI as compat-terraform: 2.15 predates the S3 checksum type (x-amz-checksum-type, December 2024) +# and cannot show ChecksumType in head-object / get-object-attributes output. +FROM amazon/aws-cli:2.34.32 # Copy tofu binary from official OpenTofu image COPY --from=opentofu /usr/local/bin/tofu /usr/local/bin/tofu diff --git a/compatibility-tests/compat-opentofu/main.tf b/compatibility-tests/compat-opentofu/main.tf index 44a071333e..c221d350d1 100644 --- a/compatibility-tests/compat-opentofu/main.tf +++ b/compatibility-tests/compat-opentofu/main.tf @@ -20,6 +20,18 @@ resource "aws_s3_bucket_versioning" "app" { } } +# A 12 MiB file with a declared checksum algorithm: the provider uploads it through the SDK transfer +# manager as a multipart upload (5 MiB parts), so S3 stores a COMPOSITE checksum and a multipart ETag. +# The file is generated by the test setup (see test/*.bats) and is not committed. +resource "aws_s3_object" "large" { + bucket = aws_s3_bucket.app.id + key = "large/multipart.bin" + source = "${path.module}/large-object.bin" + checksum_algorithm = "SHA256" + + depends_on = [aws_s3_bucket_versioning.app] +} + # ── SQS Queue ────────────────────────────────────────────────────────────── resource "aws_sqs_queue" "jobs" { name = "floci-compat-jobs" @@ -610,3 +622,7 @@ resource "aws_guardduty_organization_configuration" "compat" { output "guardduty_detector_id" { value = aws_guardduty_detector.compat.id } + +output "large_object_checksum_sha256" { + value = aws_s3_object.large.checksum_sha256 +} diff --git a/compatibility-tests/compat-opentofu/test/opentofu.bats b/compatibility-tests/compat-opentofu/test/opentofu.bats index cddd4c9f71..42eb6e8eb7 100644 --- a/compatibility-tests/compat-opentofu/test/opentofu.bats +++ b/compatibility-tests/compat-opentofu/test/opentofu.bats @@ -16,6 +16,9 @@ setup_file() { create_state_backend generate_backend_config + # 12 MiB source for aws_s3_object.large: above the provider's 5 MiB part size, so it goes multipart + head -c $((12 * 1024 * 1024)) /dev/urandom > "$TOFU_DIR/large-object.bin" + echo "# --- tofu init ---" >&3 run tofu init -backend-config=/tmp/floci-backend.hcl \ -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color @@ -53,6 +56,7 @@ teardown_file() { echo "# --- tofu destroy ---" >&3 tofu destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true + rm -f "$TOFU_DIR/large-object.bin" } setup() { @@ -66,6 +70,72 @@ setup() { assert_success } +# Base64 of a hex SHA256 digest, the way S3 encodes checksums. +hex_to_b64() { + printf "$(echo "$1" | sed 's/../\\x&/g')" | base64 | tr -d '\n' +} + +# The composite SHA256 S3 stores for a multipart object: cut the local file at the part sizes S3 +# reports, hash each part, hash the concatenated binary digests and append the part count. +sha256_composite_by_sizes() { + local file="$1" + shift + local joined offset=0 count=0 size hex + joined=$(mktemp) + for size in "$@"; do + hex=$(tail -c +$((offset + 1)) "$file" | head -c "$size" | sha256sum | cut -c1-64) + printf "$(echo "$hex" | sed 's/../\\x&/g')" >> "$joined" + offset=$((offset + size)) + count=$((count + 1)) + done + echo "$(hex_to_b64 "$(sha256sum "$joined" | cut -c1-64)")-$count" + rm -f "$joined" +} + +@test "OpenTofu: large aws_s3_object is multipart-uploaded with the composite SHA256 checksum" { + run aws_cmd s3api head-object --bucket floci-compat-app --key large/multipart.bin \ + --checksum-mode ENABLED --output json + assert_success + local checksum type etag + checksum=$(echo "$output" | jq -r '.ChecksumSHA256') + type=$(echo "$output" | jq -r '.ChecksumType') + etag=$(echo "$output" | jq -r '.ETag') + [ "$type" = "COMPOSITE" ] + [[ "$etag" =~ -[0-9]+\"$ ]] + + run aws_cmd s3api get-object-attributes --bucket floci-compat-app --key large/multipart.bin \ + --object-attributes Checksum ObjectParts --output json + assert_success + [ "$(echo "$output" | jq -r '.ObjectParts.TotalPartsCount')" -gt 1 ] + local sizes expected + sizes=$(echo "$output" | jq -r '.ObjectParts.Parts[].Size') + expected=$(sha256_composite_by_sizes "$TOFU_DIR/large-object.bin" $sizes) + [ "$checksum" = "$expected" ] + # GetObjectAttributes reports the composite without the part-count suffix + [ "$(echo "$output" | jq -r '.Checksum.ChecksumSHA256')" = "${expected%-*}" ] +} + +@test "OpenTofu: state holds the composite checksum S3 reports for the large object" { + cd "$TOFU_DIR" + run tofu output -raw large_object_checksum_sha256 + assert_success + local head_checksum + head_checksum=$(aws_cmd s3api head-object --bucket floci-compat-app --key large/multipart.bin \ + --checksum-mode ENABLED --output json | jq -r '.ChecksumSHA256') + [ "$output" = "$head_checksum" ] +} + +@test "OpenTofu: re-planning the large object reports no changes" { + cd "$TOFU_DIR" + run tofu plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode \ + -target=aws_s3_object.large + if [ "$status" -eq 2 ]; then + echo "# drift detected on re-plan:" >&3 + echo "$output" >&3 + fi + [ "$status" -eq 0 ] +} + @test "OpenTofu: SQS queue created" { run aws_cmd sqs get-queue-url --queue-name floci-compat-jobs assert_success diff --git a/compatibility-tests/compat-terraform/main.tf b/compatibility-tests/compat-terraform/main.tf index 457d9abb7b..3784a7fb42 100644 --- a/compatibility-tests/compat-terraform/main.tf +++ b/compatibility-tests/compat-terraform/main.tf @@ -16,6 +16,18 @@ resource "aws_s3_bucket_versioning" "app" { } } +# A 12 MiB file with a declared checksum algorithm: the provider uploads it through the SDK transfer +# manager as a multipart upload (5 MiB parts), so S3 stores a COMPOSITE checksum and a multipart ETag. +# The file is generated by the test setup (see test/*.bats) and is not committed. +resource "aws_s3_object" "large" { + bucket = aws_s3_bucket.app.id + key = "large/multipart.bin" + source = "${path.module}/large-object.bin" + checksum_algorithm = "SHA256" + + depends_on = [aws_s3_bucket_versioning.app] +} + # -- SQS Queue ----------------------------------------------------------------- resource "aws_sqs_queue" "jobs" { name = "floci-compat-jobs" @@ -787,3 +799,7 @@ output "guardduty_detector_id" { output "guardduty_detector_arn" { value = aws_guardduty_detector.compat.arn } + +output "large_object_checksum_sha256" { + value = aws_s3_object.large.checksum_sha256 +} diff --git a/compatibility-tests/compat-terraform/test/terraform.bats b/compatibility-tests/compat-terraform/test/terraform.bats index c2beb5d620..1c5c64f566 100644 --- a/compatibility-tests/compat-terraform/test/terraform.bats +++ b/compatibility-tests/compat-terraform/test/terraform.bats @@ -16,6 +16,9 @@ setup_file() { create_state_backend generate_backend_config + # 12 MiB source for aws_s3_object.large: above the provider's 5 MiB part size, so it goes multipart + head -c $((12 * 1024 * 1024)) /dev/urandom > "$TF_DIR/large-object.bin" + echo "# --- terraform init ---" >&3 run terraform init -backend-config=/tmp/floci-backend.hcl \ -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color @@ -53,6 +56,7 @@ teardown_file() { echo "# --- terraform destroy ---" >&3 terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true + rm -f "$TF_DIR/large-object.bin" } setup() { @@ -66,6 +70,72 @@ setup() { assert_success } +# Base64 of a hex SHA256 digest, the way S3 encodes checksums. +hex_to_b64() { + printf "$(echo "$1" | sed 's/../\\x&/g')" | base64 | tr -d '\n' +} + +# The composite SHA256 S3 stores for a multipart object: cut the local file at the part sizes S3 +# reports, hash each part, hash the concatenated binary digests and append the part count. +sha256_composite_by_sizes() { + local file="$1" + shift + local joined offset=0 count=0 size hex + joined=$(mktemp) + for size in "$@"; do + hex=$(tail -c +$((offset + 1)) "$file" | head -c "$size" | sha256sum | cut -c1-64) + printf "$(echo "$hex" | sed 's/../\\x&/g')" >> "$joined" + offset=$((offset + size)) + count=$((count + 1)) + done + echo "$(hex_to_b64 "$(sha256sum "$joined" | cut -c1-64)")-$count" + rm -f "$joined" +} + +@test "Terraform: large aws_s3_object is multipart-uploaded with the composite SHA256 checksum" { + run aws_cmd s3api head-object --bucket floci-compat-app --key large/multipart.bin \ + --checksum-mode ENABLED --output json + assert_success + local checksum type etag + checksum=$(echo "$output" | jq -r '.ChecksumSHA256') + type=$(echo "$output" | jq -r '.ChecksumType') + etag=$(echo "$output" | jq -r '.ETag') + [ "$type" = "COMPOSITE" ] + [[ "$etag" =~ -[0-9]+\"$ ]] + + run aws_cmd s3api get-object-attributes --bucket floci-compat-app --key large/multipart.bin \ + --object-attributes Checksum ObjectParts --output json + assert_success + [ "$(echo "$output" | jq -r '.ObjectParts.TotalPartsCount')" -gt 1 ] + local sizes expected + sizes=$(echo "$output" | jq -r '.ObjectParts.Parts[].Size') + expected=$(sha256_composite_by_sizes "$TF_DIR/large-object.bin" $sizes) + [ "$checksum" = "$expected" ] + # GetObjectAttributes reports the composite without the part-count suffix + [ "$(echo "$output" | jq -r '.Checksum.ChecksumSHA256')" = "${expected%-*}" ] +} + +@test "Terraform: state holds the composite checksum S3 reports for the large object" { + cd "$TF_DIR" + run terraform output -raw large_object_checksum_sha256 + assert_success + local head_checksum + head_checksum=$(aws_cmd s3api head-object --bucket floci-compat-app --key large/multipart.bin \ + --checksum-mode ENABLED --output json | jq -r '.ChecksumSHA256') + [ "$output" = "$head_checksum" ] +} + +@test "Terraform: re-planning the large object reports no changes" { + cd "$TF_DIR" + run terraform plan -var="endpoint=${FLOCI_ENDPOINT}" -input=false -no-color -detailed-exitcode \ + -target=aws_s3_object.large + if [ "$status" -eq 2 ]; then + echo "# drift detected on re-plan:" >&3 + echo "$output" >&3 + fi + [ "$status" -eq 0 ] +} + @test "Terraform: SQS queue created" { run aws_cmd sqs get-queue-url --queue-name floci-compat-jobs assert_success diff --git a/compatibility-tests/sdk-test-awscli/test/s3.bats b/compatibility-tests/sdk-test-awscli/test/s3.bats index 50914ebe78..a18c2b2694 100644 --- a/compatibility-tests/sdk-test-awscli/test/s3.bats +++ b/compatibility-tests/sdk-test-awscli/test/s3.bats @@ -394,3 +394,172 @@ EOF assert_failure assert_output --partial "NoSuchConfiguration" } + +# Checksum helpers: Base64 SHA256 of a file, and the composite S3 stores for a multipart upload +# (SHA256 over the concatenated binary part digests, suffixed with the part count). +sha256_b64() { + openssl dgst -sha256 -binary "$1" | base64 | tr -d '\n' +} + +sha256_composite() { + local count=$# + for part in "$@"; do openssl dgst -sha256 -binary "$part"; done \ + | openssl dgst -sha256 -binary | base64 | tr -d '\n' + echo "-$count" +} + +@test "S3: multipart upload with SHA256 stores the composite checksum" { + aws_cmd s3api create-bucket --bucket "$BUCKET" >/dev/null + local dir + dir=$(mktemp -d) + head -c $((5 * 1024 * 1024)) /dev/urandom > "$dir/part1" + head -c $((1024 * 1024)) /dev/urandom > "$dir/part2" + local sha1 sha2 composite + sha1=$(sha256_b64 "$dir/part1") + sha2=$(sha256_b64 "$dir/part2") + composite=$(sha256_composite "$dir/part1" "$dir/part2") + + output=$(aws_cmd s3api create-multipart-upload --bucket "$BUCKET" --key "composite.bin" \ + --checksum-algorithm SHA256) + upload_id=$(json_get "$output" '.UploadId') + [ "$(json_get "$output" '.ChecksumAlgorithm')" = "SHA256" ] + [ "$(json_get "$output" '.ChecksumType')" = "COMPOSITE" ] + + output=$(aws_cmd s3api upload-part --bucket "$BUCKET" --key "composite.bin" --upload-id "$upload_id" \ + --part-number 1 --body "$dir/part1" --checksum-sha256 "$sha1") + etag1=$(json_get "$output" '.ETag') + # UploadPart echoes the checksum of the part + [ "$(json_get "$output" '.ChecksumSHA256')" = "$sha1" ] + output=$(aws_cmd s3api upload-part --bucket "$BUCKET" --key "composite.bin" --upload-id "$upload_id" \ + --part-number 2 --body "$dir/part2" --checksum-sha256 "$sha2") + etag2=$(json_get "$output" '.ETag') + + local parts_json + parts_json=$(jq -n --arg e1 "$etag1" --arg s1 "$sha1" --arg e2 "$etag2" --arg s2 "$sha2" \ + '{Parts: [{PartNumber: 1, ETag: $e1, ChecksumSHA256: $s1}, {PartNumber: 2, ETag: $e2, ChecksumSHA256: $s2}]}') + run aws_cmd s3api complete-multipart-upload --bucket "$BUCKET" --key "composite.bin" \ + --upload-id "$upload_id" --multipart-upload "$parts_json" + assert_success + [ "$(json_get "$output" '.ChecksumSHA256')" = "$composite" ] + [ "$(json_get "$output" '.ChecksumType')" = "COMPOSITE" ] + + run aws_cmd s3api head-object --bucket "$BUCKET" --key "composite.bin" --checksum-mode ENABLED + assert_success + [ "$(json_get "$output" '.ChecksumSHA256')" = "$composite" ] + [ "$(json_get "$output" '.ChecksumType')" = "COMPOSITE" ] + + # GetObjectAttributes reports the composite without the "-2" suffix and the ETag without quotes + run aws_cmd s3api get-object-attributes --bucket "$BUCKET" --key "composite.bin" \ + --object-attributes Checksum ObjectParts ETag + assert_success + [ "$(json_get "$output" '.Checksum.ChecksumSHA256')" = "${composite%-2}" ] + [ "$(json_get "$output" '.ObjectParts.TotalPartsCount')" = "2" ] + [ "$(json_get "$output" '.ObjectParts.Parts[0].ChecksumSHA256')" = "$sha1" ] + [[ "$(json_get "$output" '.ETag')" =~ ^[0-9a-f]{32}-2$ ]] + rm -rf "$dir" +} + +@test "S3: complete-multipart-upload without part checksums is rejected on a SHA256 upload" { + aws_cmd s3api create-bucket --bucket "$BUCKET" >/dev/null + local part_file + part_file=$(mktemp) + echo -n "part-one" > "$part_file" + output=$(aws_cmd s3api create-multipart-upload --bucket "$BUCKET" --key "strict.bin" --checksum-algorithm SHA256) + upload_id=$(json_get "$output" '.UploadId') + output=$(aws_cmd s3api upload-part --bucket "$BUCKET" --key "strict.bin" --upload-id "$upload_id" \ + --part-number 1 --body "$part_file" --checksum-sha256 "$(sha256_b64 "$part_file")") + etag1=$(json_get "$output" '.ETag') + + run aws_cmd s3api complete-multipart-upload --bucket "$BUCKET" --key "strict.bin" --upload-id "$upload_id" \ + --multipart-upload "$(jq -n --arg e1 "$etag1" '{Parts: [{PartNumber: 1, ETag: $e1}]}')" + assert_failure + assert_output --partial "InvalidRequest" + assert_output --partial "must include the checksum for each part" + + aws_cmd s3api abort-multipart-upload --bucket "$BUCKET" --key "strict.bin" --upload-id "$upload_id" >/dev/null 2>&1 || true + rm -f "$part_file" +} + +@test "S3: aws s3 cp --checksum-algorithm uploads a large file with a composite checksum" { + aws_cmd s3api create-bucket --bucket "$BUCKET" >/dev/null + local dir + dir=$(mktemp -d) + head -c $((12 * 1024 * 1024)) /dev/urandom > "$dir/large.bin" + # the CLI splits at its default 8 MiB part size, so the composite is over two parts + split -b 8m "$dir/large.bin" "$dir/piece." + local composite + composite=$(sha256_composite "$dir"/piece.*) + [[ "$composite" == *-2 ]] + + run aws_cmd s3 cp "$dir/large.bin" "s3://$BUCKET/large.bin" --checksum-algorithm SHA256 + assert_success + + run aws_cmd s3api head-object --bucket "$BUCKET" --key "large.bin" --checksum-mode ENABLED + assert_success + [ "$(json_get "$output" '.ChecksumSHA256')" = "$composite" ] + [ "$(json_get "$output" '.ChecksumType')" = "COMPOSITE" ] + + run aws_cmd s3 cp "s3://$BUCKET/large.bin" "$dir/roundtrip.bin" + assert_success + same_content "$dir/large.bin" "$dir/roundtrip.bin" + rm -rf "$dir" +} + +# CRC32 (IEEE) checksums as S3 encodes them (Base64 of the big-endian value); python3 ships in the CLI image. +crc32_b64() { + python3 -c 'import sys, zlib, base64 +print(base64.b64encode((zlib.crc32(open(sys.argv[1], "rb").read()) & 0xffffffff).to_bytes(4, "big")).decode())' "$1" +} + +crc32_composite() { + python3 -c 'import sys, zlib, base64 +def crc(data): return (zlib.crc32(data) & 0xffffffff).to_bytes(4, "big") +parts = [open(p, "rb").read() for p in sys.argv[1:]] +print(base64.b64encode(crc(b"".join(crc(p) for p in parts))).decode() + f"-{len(parts)}")' "$@" +} + +same_content() { + [ "$(openssl dgst -sha256 -r "$1" | cut -d" " -f1)" = "$(openssl dgst -sha256 -r "$2" | cut -d" " -f1)" ] +} + +@test "S3: plain aws s3 cp of a large file uploads in parts and stores the CLI's default checksum" { + aws_cmd s3api create-bucket --bucket "$BUCKET" >/dev/null + local dir + dir=$(mktemp -d) + head -c $((12 * 1024 * 1024)) /dev/urandom > "$dir/large.bin" + split -b 8m "$dir/large.bin" "$dir/piece." + + # no --checksum-algorithm: the CLI multipart-uploads at 8 MiB parts with whatever its version declares + run aws_cmd s3 cp "$dir/large.bin" "s3://$BUCKET/large-default.bin" + assert_success + + run aws_cmd s3api head-object --bucket "$BUCKET" --key "large-default.bin" --checksum-mode ENABLED + assert_success + local etag type crc32 + etag=$(json_get "$output" '.ETag') + type=$(json_get "$output" '.ChecksumType') + crc32=$(json_get "$output" '.ChecksumCRC32') + [[ "$etag" =~ -2\"$ ]] + if [ -n "$crc32" ] && [ "$crc32" != "null" ]; then + # current CLIs declare CRC32, which S3 stores as COMPOSITE (or FULL_OBJECT when the CLI asks for it) + if [ "$type" = "COMPOSITE" ]; then + [ "$crc32" = "$(crc32_composite "$dir"/piece.*)" ] + else + [ "$type" = "FULL_OBJECT" ] + [ "$crc32" = "$(crc32_b64 "$dir/large.bin")" ] + fi + else + # a CLI that declares no algorithm gets the CRC64NVME full-object checksum S3 attaches itself + [ "$type" = "FULL_OBJECT" ] + [ -n "$(json_get "$output" '.ChecksumCRC64NVME')" ] + fi + + run aws_cmd s3api get-object-attributes --bucket "$BUCKET" --key "large-default.bin" --object-attributes ObjectParts + assert_success + [ "$(json_get "$output" '.ObjectParts.TotalPartsCount')" = "2" ] + + run aws_cmd s3 cp "s3://$BUCKET/large-default.bin" "$dir/roundtrip.bin" + assert_success + same_content "$dir/large.bin" "$dir/roundtrip.bin" + rm -rf "$dir" +} diff --git a/compatibility-tests/sdk-test-go/tests/s3_multipart_checksum_test.go b/compatibility-tests/sdk-test-go/tests/s3_multipart_checksum_test.go new file mode 100644 index 0000000000..ff95a4ce52 --- /dev/null +++ b/compatibility-tests/sdk-test-go/tests/s3_multipart_checksum_test.go @@ -0,0 +1,226 @@ +package tests + +import ( + "bytes" + "context" + "crypto/md5" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "fmt" + "hash/crc32" + "io" + "math/rand" + "strings" + "testing" + + "floci-sdk-test-go/internal/testutil" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/feature/s3/manager" + "github.com/aws/aws-sdk-go-v2/service/s3" + s3types "github.com/aws/aws-sdk-go-v2/service/s3/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// Multipart uploads through the S3 transfer manager, the code path terraform-provider-aws uses for +// aws_s3_object. S3 stores a COMPOSITE checksum for SHA algorithms (the algorithm applied to the +// concatenated part checksums, suffixed with "-") and reports it on HeadObject, without the +// suffix on GetObjectAttributes. A copy is written as a single object with a FULL_OBJECT checksum. + +const checksumPartSize = 5 * 1024 * 1024 + +func checksumPayload(size int) []byte { + b := make([]byte, size) + rand.New(rand.NewSource(20260903)).Read(b) + return b +} + +func splitParts(data []byte, size int) [][]byte { + var parts [][]byte + for start := 0; start < len(data); start += size { + end := start + size + if end > len(data) { + end = len(data) + } + parts = append(parts, data[start:end]) + } + return parts +} + +func sha256B64(data []byte) string { + d := sha256.Sum256(data) + return base64.StdEncoding.EncodeToString(d[:]) +} + +func sha256Composite(parts [][]byte) string { + var joined []byte + for _, p := range parts { + d := sha256.Sum256(p) + joined = append(joined, d[:]...) + } + return sha256B64(joined) + fmt.Sprintf("-%d", len(parts)) +} + +func crc32Bytes(data []byte) []byte { + v := crc32.ChecksumIEEE(data) + return []byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)} +} + +func crc32Composite(parts [][]byte) string { + var joined []byte + for _, p := range parts { + joined = append(joined, crc32Bytes(p)...) + } + return base64.StdEncoding.EncodeToString(crc32Bytes(joined)) + fmt.Sprintf("-%d", len(parts)) +} + +// crc64Nvme implements CRC-64/NVME (reflected polynomial 0x9a6c9329ac4bc9b5), the checksum S3 +// attaches when a client declares no algorithm. +func crc64Nvme(data []byte) []byte { + var table [256]uint64 + for i := range table { + c := uint64(i) + for j := 0; j < 8; j++ { + if c&1 == 1 { + c = (c >> 1) ^ 0x9a6c9329ac4bc9b5 + } else { + c >>= 1 + } + } + table[i] = c + } + c := ^uint64(0) + for _, b := range data { + c = table[byte(c)^b] ^ (c >> 8) + } + c = ^c + out := make([]byte, 8) + for i := 0; i < 8; i++ { + out[i] = byte(c >> (56 - 8*i)) + } + return out +} + +func TestS3MultipartChecksums(t *testing.T) { + ctx := context.Background() + svc := testutil.S3Client() + bucket := "go-test-multipart-checksums" + payload := checksumPayload(12 * 1024 * 1024) + parts := splitParts(payload, checksumPartSize) + require.Len(t, parts, 3) + uploader := manager.NewUploader(svc, func(u *manager.Uploader) { + u.PartSize = checksumPartSize + }) + keys := []string{"sha256.bin", "default.bin", "sha256-copy.bin"} + + _, err := svc.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)}) + require.NoError(t, err) + t.Cleanup(func() { + for _, key := range keys { + if _, err := svc.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(bucket), Key: aws.String(key)}); err != nil { + t.Logf("cleanup: could not delete s3://%s/%s: %v", bucket, key, err) + } + } + if _, err := svc.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)}); err != nil { + t.Logf("cleanup: could not delete bucket %s: %v", bucket, err) + } + }) + + head := func(t *testing.T, key string) *s3.HeadObjectOutput { + out, err := svc.HeadObject(ctx, &s3.HeadObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), ChecksumMode: s3types.ChecksumModeEnabled, + }) + require.NoError(t, err) + return out + } + + t.Run("SHA256 upload reports the composite checksum", func(t *testing.T) { + key := keys[0] + _, err := uploader.Upload(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(payload), + ChecksumAlgorithm: s3types.ChecksumAlgorithmSha256, + }) + require.NoError(t, err) + + composite := sha256Composite(parts) + h := head(t, key) + assert.Equal(t, composite, aws.ToString(h.ChecksumSHA256)) + assert.Equal(t, s3types.ChecksumTypeComposite, h.ChecksumType) + assert.True(t, strings.HasSuffix(aws.ToString(h.ETag), `-3"`), aws.ToString(h.ETag)) + + attrs, err := svc.GetObjectAttributes(ctx, &s3.GetObjectAttributesInput{ + Bucket: aws.String(bucket), Key: aws.String(key), + ObjectAttributes: []s3types.ObjectAttributes{ + s3types.ObjectAttributesChecksum, s3types.ObjectAttributesObjectParts, s3types.ObjectAttributesEtag, + }, + }) + require.NoError(t, err) + assert.Equal(t, strings.TrimSuffix(composite, "-3"), aws.ToString(attrs.Checksum.ChecksumSHA256), + "GetObjectAttributes omits the part-count suffix") + assert.Equal(t, s3types.ChecksumTypeComposite, attrs.Checksum.ChecksumType) + assert.Equal(t, int32(3), aws.ToInt32(attrs.ObjectParts.TotalPartsCount)) + for i, part := range attrs.ObjectParts.Parts { + assert.Equal(t, sha256B64(parts[i]), aws.ToString(part.ChecksumSHA256), "part %d", i+1) + } + assert.Equal(t, strings.Trim(aws.ToString(h.ETag), `"`), aws.ToString(attrs.ETag), + "GetObjectAttributes returns the ETag without quotes") + }) + + t.Run("default checksum of the uploader matches what S3 stores", func(t *testing.T) { + key := keys[1] + _, err := uploader.Upload(ctx, &s3.PutObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), Body: bytes.NewReader(payload), + }) + require.NoError(t, err) + + // Which algorithm and type the SDK picks depends on its version; whatever it sent, the stored + // value must be the one S3 would compute for that combination. + h := head(t, key) + switch { + case h.ChecksumCRC32 != nil && h.ChecksumType == s3types.ChecksumTypeComposite: + assert.Equal(t, crc32Composite(parts), aws.ToString(h.ChecksumCRC32)) + case h.ChecksumCRC32 != nil && h.ChecksumType == s3types.ChecksumTypeFullObject: + assert.Equal(t, base64.StdEncoding.EncodeToString(crc32Bytes(payload)), aws.ToString(h.ChecksumCRC32)) + case h.ChecksumCRC64NVME != nil: + assert.Equal(t, s3types.ChecksumTypeFullObject, h.ChecksumType) + assert.Equal(t, base64.StdEncoding.EncodeToString(crc64Nvme(payload)), aws.ToString(h.ChecksumCRC64NVME)) + default: + t.Fatalf("unexpected checksum on HeadObject: %+v", h) + } + t.Logf("uploader default: CRC32=%q CRC64NVME=%q type=%s", + aws.ToString(h.ChecksumCRC32), aws.ToString(h.ChecksumCRC64NVME), h.ChecksumType) + + // Downloading with response checksum validation enabled must round-trip the payload. + obj, err := svc.GetObject(ctx, &s3.GetObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(key), ChecksumMode: s3types.ChecksumModeEnabled, + }) + require.NoError(t, err) + body, err := io.ReadAll(obj.Body) + require.NoError(t, err) + obj.Body.Close() + assert.True(t, bytes.Equal(payload, body), "downloaded body differs from the payload") + }) + + t.Run("copy of the multipart object is a single full object", func(t *testing.T) { + source := head(t, keys[0]) + out, err := svc.CopyObject(ctx, &s3.CopyObjectInput{ + Bucket: aws.String(bucket), Key: aws.String(keys[2]), + CopySource: aws.String(bucket + "/" + keys[0]), + }) + require.NoError(t, err) + + sum := md5.Sum(payload) + expectedETag := `"` + hex.EncodeToString(sum[:]) + `"` + assert.Equal(t, sha256B64(payload), aws.ToString(out.CopyObjectResult.ChecksumSHA256)) + assert.Equal(t, s3types.ChecksumTypeFullObject, out.CopyObjectResult.ChecksumType) + assert.Equal(t, expectedETag, aws.ToString(out.CopyObjectResult.ETag)) + assert.NotEqual(t, aws.ToString(source.ETag), aws.ToString(out.CopyObjectResult.ETag)) + + h := head(t, keys[2]) + assert.Equal(t, sha256B64(payload), aws.ToString(h.ChecksumSHA256)) + assert.Equal(t, s3types.ChecksumTypeFullObject, h.ChecksumType) + assert.Equal(t, expectedETag, aws.ToString(h.ETag)) + }) +} diff --git a/compatibility-tests/sdk-test-java/pom.xml b/compatibility-tests/sdk-test-java/pom.xml index 7d7bffb074..14afc79ae0 100644 --- a/compatibility-tests/sdk-test-java/pom.xml +++ b/compatibility-tests/sdk-test-java/pom.xml @@ -88,6 +88,10 @@ software.amazon.awssdk s3 + + software.amazon.awssdk + s3-transfer-manager + software.amazon.awssdk s3control diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java index abbb3d05b3..7c09e3a095 100644 --- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java +++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java @@ -32,6 +32,7 @@ import software.amazon.awssdk.services.fis.FisClient; import software.amazon.awssdk.services.organizations.OrganizationsClient; import software.amazon.awssdk.services.rum.RumClient; import software.amazon.awssdk.services.resourceexplorer2.ResourceExplorer2Client; +import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.endpoints.Endpoint; import software.amazon.awssdk.services.s3control.S3ControlClient; @@ -314,6 +315,19 @@ public final class TestFixtures { .build(); } + /** Async client with the Java-based multipart support enabled (5 MiB threshold and parts), for the transfer manager. */ + public static S3AsyncClient s3MultipartAsyncClient() { + long fiveMiB = 5L * 1024 * 1024; + return S3AsyncClient.builder() + .endpointOverride(ENDPOINT) + .region(REGION) + .credentialsProvider(CREDENTIALS) + .forcePathStyle(true) + .multipartEnabled(true) + .multipartConfiguration(b -> b.thresholdInBytes(fiveMiB).minimumPartSizeInBytes(fiveMiB)) + .build(); + } + /** * S3 client using virtual-hosted style addressing (no forcePathStyle). * diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3MultipartChecksumTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3MultipartChecksumTest.java new file mode 100644 index 0000000000..09cb3a9afa --- /dev/null +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/S3MultipartChecksumTest.java @@ -0,0 +1,373 @@ +package com.floci.test; + +import org.junit.jupiter.api.*; +import software.amazon.awssdk.core.async.AsyncRequestBody; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.services.s3.S3AsyncClient; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.model.ChecksumAlgorithm; +import software.amazon.awssdk.services.s3.model.ChecksumMode; +import software.amazon.awssdk.services.s3.model.ChecksumType; +import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.CompleteMultipartUploadResponse; +import software.amazon.awssdk.services.s3.model.CompletedMultipartUpload; +import software.amazon.awssdk.services.s3.model.CompletedPart; +import software.amazon.awssdk.services.s3.model.CopyObjectRequest; +import software.amazon.awssdk.services.s3.model.CopyObjectResponse; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadRequest; +import software.amazon.awssdk.services.s3.model.CreateMultipartUploadResponse; +import software.amazon.awssdk.services.s3.model.DeleteBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectAttributesRequest; +import software.amazon.awssdk.services.s3.model.GetObjectAttributesResponse; +import software.amazon.awssdk.services.s3.model.HeadObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadObjectResponse; +import software.amazon.awssdk.services.s3.model.ObjectAttributes; +import software.amazon.awssdk.services.s3.model.ObjectPart; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.model.UploadPartRequest; +import software.amazon.awssdk.services.s3.model.UploadPartResponse; +import software.amazon.awssdk.transfer.s3.S3TransferManager; +import software.amazon.awssdk.transfer.s3.model.UploadRequest; + +import java.io.ByteArrayOutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.Random; +import java.util.zip.CRC32; + +import static org.assertj.core.api.Assertions.*; + +/** + * Low-level multipart uploads with the Java SDK v2, the flow of the "checksum of checksums" example + * in the AWS integrity documentation. S3 stores a COMPOSITE checksum for SHA algorithms (the algorithm + * applied to the concatenated part checksums, suffixed with "-"), a FULL_OBJECT one for CRC + * algorithms when requested on CreateMultipartUpload, and writes a copy as a single full object. + */ +@DisplayName("S3 multipart checksums") +@TestMethodOrder(MethodOrderer.OrderAnnotation.class) +class S3MultipartChecksumTest { + + private static final int MIB = 1024 * 1024; + private static final String BUCKET = "sdk-test-multipart-checksums"; + private static final byte[] PART_1 = payload(5 * MIB, 1); + private static final byte[] PART_2 = payload(1 * MIB, 2); + private static final List KEYS = List.of("sha256.bin", "crc32-full-object.bin", "sha256-copy.bin", + "tm-sha256.bin", "tm-default.bin"); + + private static S3Client s3; + + @BeforeAll + static void setup() { + s3 = TestFixtures.s3Client(); + s3.createBucket(CreateBucketRequest.builder().bucket(BUCKET).build()); + } + + @AfterAll + static void cleanup() { + if (s3 == null) { + return; + } + for (String key : KEYS) { + try { + s3.deleteObject(DeleteObjectRequest.builder().bucket(BUCKET).key(key).build()); + } catch (Exception e) { + System.err.printf("cleanup: could not delete s3://%s/%s: %s%n", BUCKET, key, e.getMessage()); + } + } + try { + s3.deleteBucket(DeleteBucketRequest.builder().bucket(BUCKET).build()); + } catch (Exception e) { + System.err.printf("cleanup: could not delete bucket %s: %s%n", BUCKET, e.getMessage()); + } + } + + @Test + @Order(1) + @DisplayName("SHA256 multipart upload returns the composite checksum") + void sha256MultipartUploadReturnsCompositeChecksum() throws NoSuchAlgorithmException { + String key = KEYS.get(0); + CreateMultipartUploadResponse created = s3.createMultipartUpload(CreateMultipartUploadRequest.builder() + .bucket(BUCKET).key(key).checksumAlgorithm(ChecksumAlgorithm.SHA256).build()); + assertThat(created.checksumAlgorithm()).isEqualTo(ChecksumAlgorithm.SHA256); + assertThat(created.checksumType()).isEqualTo(ChecksumType.COMPOSITE); + + List completed = new ArrayList<>(); + byte[][] parts = {PART_1, PART_2}; + for (int i = 0; i < parts.length; i++) { + UploadPartResponse uploaded = s3.uploadPart(UploadPartRequest.builder() + .bucket(BUCKET).key(key).uploadId(created.uploadId()).partNumber(i + 1) + .checksumAlgorithm(ChecksumAlgorithm.SHA256).build(), RequestBody.fromBytes(parts[i])); + // UploadPart echoes the checksum of the part, which the SDK carries into the Complete body + assertThat(uploaded.checksumSHA256()).isEqualTo(base64(sha256(parts[i]))); + completed.add(CompletedPart.builder().partNumber(i + 1).eTag(uploaded.eTag()) + .checksumSHA256(uploaded.checksumSHA256()).build()); + } + + String composite = compositeSha256(parts); + CompleteMultipartUploadResponse done = s3.completeMultipartUpload(CompleteMultipartUploadRequest.builder() + .bucket(BUCKET).key(key).uploadId(created.uploadId()) + .multipartUpload(CompletedMultipartUpload.builder().parts(completed).build()).build()); + assertThat(done.checksumSHA256()).isEqualTo(composite); + assertThat(done.checksumType()).isEqualTo(ChecksumType.COMPOSITE); + + HeadObjectResponse head = s3.headObject(HeadObjectRequest.builder() + .bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED).build()); + assertThat(head.checksumSHA256()).isEqualTo(composite); + assertThat(head.checksumType()).isEqualTo(ChecksumType.COMPOSITE); + assertThat(head.eTag()).endsWith("-2\""); + + GetObjectAttributesResponse attributes = s3.getObjectAttributes(GetObjectAttributesRequest.builder() + .bucket(BUCKET).key(key) + .objectAttributes(ObjectAttributes.CHECKSUM, ObjectAttributes.OBJECT_PARTS, ObjectAttributes.E_TAG) + .build()); + assertThat(attributes.checksum().checksumSHA256()).isEqualTo(composite.replace("-2", "")) + .describedAs("GetObjectAttributes omits the part-count suffix"); + assertThat(attributes.checksum().checksumType()).isEqualTo(ChecksumType.COMPOSITE); + assertThat(attributes.objectParts().totalPartsCount()).isEqualTo(2); + assertThat(attributes.objectParts().parts()).extracting("checksumSHA256") + .containsExactly(base64(sha256(PART_1)), base64(sha256(PART_2))); + assertThat(attributes.eTag()).isEqualTo(head.eTag().replace("\"", "")) + .describedAs("GetObjectAttributes returns the ETag without quotes"); + } + + @Test + @Order(2) + @DisplayName("Complete without a part checksum is rejected on a composite upload") + void completeWithoutPartChecksumsIsRejected() { + String key = "strict.bin"; + CreateMultipartUploadResponse created = s3.createMultipartUpload(CreateMultipartUploadRequest.builder() + .bucket(BUCKET).key(key).checksumAlgorithm(ChecksumAlgorithm.SHA256).build()); + UploadPartResponse uploaded = s3.uploadPart(UploadPartRequest.builder() + .bucket(BUCKET).key(key).uploadId(created.uploadId()).partNumber(1) + .checksumAlgorithm(ChecksumAlgorithm.SHA256).build(), RequestBody.fromBytes(PART_2)); + + assertThatThrownBy(() -> s3.completeMultipartUpload(CompleteMultipartUploadRequest.builder() + .bucket(BUCKET).key(key).uploadId(created.uploadId()) + .multipartUpload(CompletedMultipartUpload.builder() + .parts(CompletedPart.builder().partNumber(1).eTag(uploaded.eTag()).build()).build()) + .build())) + .isInstanceOf(S3Exception.class) + .satisfies(e -> { + S3Exception s3e = (S3Exception) e; + assertThat(s3e.statusCode()).isEqualTo(400); + assertThat(s3e.awsErrorDetails().errorCode()).isEqualTo("InvalidRequest"); + assertThat(s3e.awsErrorDetails().errorMessage()) + .contains("must include the checksum for each part"); + }); + s3.abortMultipartUpload(b -> b.bucket(BUCKET).key(key).uploadId(created.uploadId())); + } + + @Test + @Order(3) + @DisplayName("CRC32 upload with FULL_OBJECT type keeps the whole-object checksum") + void crc32FullObjectUpload() { + String key = KEYS.get(1); + CreateMultipartUploadResponse created = s3.createMultipartUpload(CreateMultipartUploadRequest.builder() + .bucket(BUCKET).key(key).checksumAlgorithm(ChecksumAlgorithm.CRC32) + .checksumType(ChecksumType.FULL_OBJECT).build()); + assertThat(created.checksumType()).isEqualTo(ChecksumType.FULL_OBJECT); + + List completed = new ArrayList<>(); + byte[][] parts = {PART_1, PART_2}; + for (int i = 0; i < parts.length; i++) { + UploadPartResponse uploaded = s3.uploadPart(UploadPartRequest.builder() + .bucket(BUCKET).key(key).uploadId(created.uploadId()).partNumber(i + 1) + .checksumAlgorithm(ChecksumAlgorithm.CRC32).build(), RequestBody.fromBytes(parts[i])); + completed.add(CompletedPart.builder().partNumber(i + 1).eTag(uploaded.eTag()) + .checksumCRC32(uploaded.checksumCRC32()).build()); + } + + byte[] whole = concat(PART_1, PART_2); + String fullCrc32 = base64(crc32(whole)); + CompleteMultipartUploadResponse done = s3.completeMultipartUpload(CompleteMultipartUploadRequest.builder() + .bucket(BUCKET).key(key).uploadId(created.uploadId()) + .checksumType(ChecksumType.FULL_OBJECT).checksumCRC32(fullCrc32) + .multipartUpload(CompletedMultipartUpload.builder().parts(completed).build()).build()); + assertThat(done.checksumCRC32()).isEqualTo(fullCrc32); + assertThat(done.checksumType()).isEqualTo(ChecksumType.FULL_OBJECT); + + HeadObjectResponse head = s3.headObject(HeadObjectRequest.builder() + .bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED).build()); + assertThat(head.checksumCRC32()).isEqualTo(fullCrc32); + assertThat(head.checksumType()).isEqualTo(ChecksumType.FULL_OBJECT); + + GetObjectAttributesResponse attributes = s3.getObjectAttributes(GetObjectAttributesRequest.builder() + .bucket(BUCKET).key(key).objectAttributes(ObjectAttributes.CHECKSUM, ObjectAttributes.OBJECT_PARTS) + .build()); + assertThat(attributes.objectParts().totalPartsCount()).isEqualTo(2); + assertThat(attributes.objectParts().parts()).describedAs("no part checksums for FULL_OBJECT objects").isEmpty(); + } + + @Test + @Order(4) + @DisplayName("A copy of the multipart object is a single full object") + void copyOfMultipartObjectIsASingleFullObject() throws NoSuchAlgorithmException { + HeadObjectResponse source = s3.headObject(HeadObjectRequest.builder() + .bucket(BUCKET).key(KEYS.get(0)).checksumMode(ChecksumMode.ENABLED).build()); + CopyObjectResponse copied = s3.copyObject(CopyObjectRequest.builder() + .sourceBucket(BUCKET).sourceKey(KEYS.get(0)).destinationBucket(BUCKET).destinationKey(KEYS.get(2)) + .build()); + + byte[] whole = concat(PART_1, PART_2); + String expectedETag = "\"" + HexFormat.of().formatHex(MessageDigest.getInstance("MD5").digest(whole)) + "\""; + assertThat(copied.copyObjectResult().checksumSHA256()).isEqualTo(base64(sha256(whole))); + assertThat(copied.copyObjectResult().checksumType()).isEqualTo(ChecksumType.FULL_OBJECT); + assertThat(copied.copyObjectResult().eTag()).isEqualTo(expectedETag).isNotEqualTo(source.eTag()); + + HeadObjectResponse head = s3.headObject(HeadObjectRequest.builder() + .bucket(BUCKET).key(KEYS.get(2)).checksumMode(ChecksumMode.ENABLED).build()); + assertThat(head.checksumSHA256()).isEqualTo(base64(sha256(whole))); + assertThat(head.checksumType()).isEqualTo(ChecksumType.FULL_OBJECT); + assertThat(head.eTag()).isEqualTo(expectedETag); + } + + @Test + @Order(5) + @DisplayName("Transfer manager upload with SHA256 reports the composite checksum") + void transferManagerSha256UploadReportsCompositeChecksum() throws NoSuchAlgorithmException { + String key = KEYS.get(3); + byte[] whole = concat(PART_1, PART_2); + transferManagerUpload(key, whole, ChecksumAlgorithm.SHA256); + + HeadObjectResponse head = s3.headObject(HeadObjectRequest.builder() + .bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED).build()); + GetObjectAttributesResponse attributes = s3.getObjectAttributes(GetObjectAttributesRequest.builder() + .bucket(BUCKET).key(key).objectAttributes(ObjectAttributes.CHECKSUM, ObjectAttributes.OBJECT_PARTS).build()); + assertThat(attributes.objectParts().totalPartsCount()).isGreaterThan(1); + + // Cut the payload at the part sizes S3 reports, as the AWS validation example does, so the test + // does not depend on the part size the SDK chose. + byte[][] parts = sliceByReportedParts(whole, attributes.objectParts().parts()); + String composite = compositeSha256(parts); + assertThat(head.checksumSHA256()).isEqualTo(composite); + assertThat(head.checksumType()).isEqualTo(ChecksumType.COMPOSITE); + assertThat(attributes.checksum().checksumSHA256()).isEqualTo(composite.substring(0, composite.lastIndexOf('-'))); + } + + @Test + @Order(6) + @DisplayName("Transfer manager upload without an algorithm stores what the SDK declares by default") + void transferManagerDefaultChecksum() { + String key = KEYS.get(4); + byte[] whole = concat(PART_1, PART_2); + transferManagerUpload(key, whole, null); + + // Which algorithm and type the SDK picks depends on its version; whatever it sent, the stored + // value must be the one S3 would compute for that combination. + HeadObjectResponse head = s3.headObject(HeadObjectRequest.builder() + .bucket(BUCKET).key(key).checksumMode(ChecksumMode.ENABLED).build()); + if (head.checksumCRC32() != null && head.checksumType() == ChecksumType.COMPOSITE) { + GetObjectAttributesResponse attributes = s3.getObjectAttributes(GetObjectAttributesRequest.builder() + .bucket(BUCKET).key(key).objectAttributes(ObjectAttributes.OBJECT_PARTS).build()); + byte[][] parts = sliceByReportedParts(whole, attributes.objectParts().parts()); + assertThat(head.checksumCRC32()).isEqualTo(compositeCrc32(parts)); + } else if (head.checksumCRC32() != null) { + assertThat(head.checksumType()).isEqualTo(ChecksumType.FULL_OBJECT); + assertThat(head.checksumCRC32()).isEqualTo(base64(crc32(whole))); + } else { + assertThat(head.checksumType()).isEqualTo(ChecksumType.FULL_OBJECT); + assertThat(head.checksumCRC64NVME()).isEqualTo(base64(crc64Nvme(whole))); + } + System.out.printf("transfer manager default: CRC32=%s CRC64NVME=%s type=%s%n", + head.checksumCRC32(), head.checksumCRC64NVME(), head.checksumType()); + } + + private static void transferManagerUpload(String key, byte[] data, ChecksumAlgorithm algorithm) { + try (S3AsyncClient async = TestFixtures.s3MultipartAsyncClient(); + S3TransferManager transferManager = S3TransferManager.builder().s3Client(async).build()) { + transferManager.upload(UploadRequest.builder() + .putObjectRequest(b -> { + b.bucket(BUCKET).key(key); + if (algorithm != null) { + b.checksumAlgorithm(algorithm); + } + }) + .requestBody(AsyncRequestBody.fromBytes(data)) + .build()).completionFuture().join(); + } + } + + private static byte[][] sliceByReportedParts(byte[] whole, List reported) { + byte[][] parts = new byte[reported.size()][]; + int offset = 0; + for (int i = 0; i < reported.size(); i++) { + int size = reported.get(i).size().intValue(); + parts[i] = java.util.Arrays.copyOfRange(whole, offset, offset + size); + offset += size; + } + assertThat(offset).isEqualTo(whole.length); + return parts; + } + + private static String compositeCrc32(byte[]... parts) { + ByteArrayOutputStream joined = new ByteArrayOutputStream(); + for (byte[] part : parts) { + joined.writeBytes(crc32(part)); + } + return base64(crc32(joined.toByteArray())) + "-" + parts.length; + } + + /** CRC-64/NVME (reflected polynomial 0x9a6c9329ac4bc9b5), what S3 attaches when no algorithm is declared. */ + private static byte[] crc64Nvme(byte[] data) { + long[] table = new long[256]; + for (int i = 0; i < 256; i++) { + long c = i; + for (int j = 0; j < 8; j++) { + c = (c & 1) != 0 ? (c >>> 1) ^ 0x9a6c9329ac4bc9b5L : c >>> 1; + } + table[i] = c; + } + long c = -1L; + for (byte b : data) { + c = table[(int) ((c ^ b) & 0xff)] ^ (c >>> 8); + } + c = ~c; + byte[] out = new byte[8]; + for (int i = 0; i < 8; i++) { + out[i] = (byte) (c >>> (56 - 8 * i)); + } + return out; + } + + private static byte[] payload(int size, long seed) { + byte[] data = new byte[size]; + new Random(seed).nextBytes(data); + return data; + } + + private static byte[] sha256(byte[] data) throws NoSuchAlgorithmException { + return MessageDigest.getInstance("SHA-256").digest(data); + } + + private static String compositeSha256(byte[]... parts) throws NoSuchAlgorithmException { + ByteArrayOutputStream joined = new ByteArrayOutputStream(); + for (byte[] part : parts) { + joined.writeBytes(sha256(part)); + } + return base64(sha256(joined.toByteArray())) + "-" + parts.length; + } + + private static byte[] crc32(byte[] data) { + CRC32 crc = new CRC32(); + crc.update(data); + long value = crc.getValue(); + return new byte[]{(byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value}; + } + + private static byte[] concat(byte[] first, byte[] second) { + byte[] out = new byte[first.length + second.length]; + System.arraycopy(first, 0, out, 0, first.length); + System.arraycopy(second, 0, out, first.length, second.length); + return out; + } + + private static String base64(byte[] data) { + return Base64.getEncoder().encodeToString(data); + } +} diff --git a/compatibility-tests/sdk-test-node/package.json b/compatibility-tests/sdk-test-node/package.json index a463e820f5..57d452d1ce 100644 --- a/compatibility-tests/sdk-test-node/package.json +++ b/compatibility-tests/sdk-test-node/package.json @@ -30,6 +30,7 @@ "@aws-sdk/client-sqs": "^3.500.0", "@aws-sdk/client-ssm": "^3.500.0", "@aws-sdk/client-sts": "^3.500.0", + "@aws-sdk/lib-storage": "^3.500.0", "selfsigned": "^5.5.0", "ws": "^8.0.0" }, diff --git a/compatibility-tests/sdk-test-node/tests/s3-multipart-checksum.test.ts b/compatibility-tests/sdk-test-node/tests/s3-multipart-checksum.test.ts new file mode 100644 index 0000000000..fcb280bed7 --- /dev/null +++ b/compatibility-tests/sdk-test-node/tests/s3-multipart-checksum.test.ts @@ -0,0 +1,184 @@ +/** + * Multipart uploads through @aws-sdk/lib-storage, the high-level uploader of the JavaScript SDK. + * S3 stores a COMPOSITE checksum for SHA algorithms (the algorithm applied to the concatenated part + * checksums, suffixed with "-"), reports it on HeadObject and drops the suffix on + * GetObjectAttributes; a copy is written as a single object with a FULL_OBJECT checksum. + */ +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { createHash } from 'node:crypto'; +import { crc32 } from 'node:zlib'; +import { + S3Client, + CreateBucketCommand, + DeleteBucketCommand, + DeleteObjectCommand, + HeadObjectCommand, + GetObjectCommand, + GetObjectAttributesCommand, + CopyObjectCommand, +} from '@aws-sdk/client-s3'; +import { Upload } from '@aws-sdk/lib-storage'; +import { makeClient, uniqueName } from './setup'; + +const MIB = 1024 * 1024; +const PART_SIZE = 5 * MIB; + +/** Deterministic pseudo-random payload (xorshift32), so every run computes the same checksums. */ +function payloadOf(size: number): Buffer { + const out = Buffer.alloc(size); + let x = 20260903; + for (let i = 0; i < size; i += 4) { + x ^= x << 13; x >>>= 0; + x ^= x >>> 17; + x ^= x << 5; x >>>= 0; + out.writeUInt32LE(x, i); + } + return out; +} + +function parts(data: Buffer, size = PART_SIZE): Buffer[] { + const result: Buffer[] = []; + for (let start = 0; start < data.length; start += size) { + result.push(data.subarray(start, Math.min(start + size, data.length))); + } + return result; +} + +const sha256 = (data: Buffer) => createHash('sha256').update(data).digest(); +const md5Hex = (data: Buffer) => createHash('md5').update(data).digest('hex'); +function crc32Bytes(data: Buffer): Buffer { + const out = Buffer.alloc(4); + out.writeUInt32BE(crc32(data) >>> 0); + return out; +} +const composite = (digest: (b: Buffer) => Buffer, pieces: Buffer[]) => + `${digest(Buffer.concat(pieces.map(digest))).toString('base64')}-${pieces.length}`; + +/** CRC-64/NVME (reflected polynomial 0x9a6c9329ac4bc9b5), what S3 attaches when no algorithm is declared. */ +function crc64Nvme(data: Buffer): Buffer { + const poly = 0x9a6c9329ac4bc9b5n; + const mask = 0xffffffffffffffffn; + const table: bigint[] = []; + for (let i = 0; i < 256; i++) { + let c = BigInt(i); + for (let j = 0; j < 8; j++) { + c = c & 1n ? (c >> 1n) ^ poly : c >> 1n; + } + table.push(c); + } + let c = mask; + for (const byte of data) { + c = table[Number((c ^ BigInt(byte)) & 0xffn)] ^ (c >> 8n); + } + c = (~c) & mask; + const out = Buffer.alloc(8); + out.writeBigUInt64BE(c); + return out; +} + +describe('S3 multipart checksums', () => { + const s3 = makeClient(S3Client); + const bucket = uniqueName('node-multipart-checksums'); + const payload = payloadOf(12 * MIB); + const pieces = parts(payload); + const keys = { sha256: 'sha256.bin', byDefault: 'default.bin', copy: 'sha256-copy.bin' }; + + const head = (Key: string) => + s3.send(new HeadObjectCommand({ Bucket: bucket, Key, ChecksumMode: 'ENABLED' })); + + async function upload(Key: string, ChecksumAlgorithm?: 'SHA256') { + await new Upload({ + client: s3, + params: { Bucket: bucket, Key, Body: payload, ...(ChecksumAlgorithm ? { ChecksumAlgorithm } : {}) }, + partSize: PART_SIZE, + queueSize: 2, + }).done(); + } + + beforeAll(async () => { + await s3.send(new CreateBucketCommand({ Bucket: bucket })); + }); + + afterAll(async () => { + for (const Key of Object.values(keys)) { + await s3 + .send(new DeleteObjectCommand({ Bucket: bucket, Key })) + .catch((e) => console.warn(`cleanup: could not delete s3://${bucket}/${Key}: ${e}`)); + } + await s3 + .send(new DeleteBucketCommand({ Bucket: bucket })) + .catch((e) => console.warn(`cleanup: could not delete bucket ${bucket}: ${e}`)); + }); + + it('reports the composite SHA256 checksum of a multipart upload', async () => { + await upload(keys.sha256, 'SHA256'); + const expected = composite(sha256, pieces); + expect(expected.endsWith('-3')).toBe(true); + + const h = await head(keys.sha256); + expect(h.ChecksumSHA256).toBe(expected); + expect(h.ChecksumType).toBe('COMPOSITE'); + expect(h.ETag?.endsWith('-3"')).toBe(true); + + const attrs = await s3.send( + new GetObjectAttributesCommand({ + Bucket: bucket, + Key: keys.sha256, + ObjectAttributes: ['Checksum', 'ObjectParts', 'ETag'], + }) + ); + expect(attrs.Checksum?.ChecksumSHA256).toBe(expected.replace(/-3$/, '')); + expect(attrs.Checksum?.ChecksumType).toBe('COMPOSITE'); + expect(attrs.ObjectParts?.TotalPartsCount).toBe(3); + expect(attrs.ObjectParts?.Parts?.map((p) => p.ChecksumSHA256)).toEqual( + pieces.map((p) => sha256(p).toString('base64')) + ); + // GetObjectAttributes returns the ETag without the quotes HeadObject carries + expect(attrs.ETag).toBe(h.ETag?.replace(/"/g, '')); + }); + + it('stores what the uploader sends by default and validates the download', async () => { + await upload(keys.byDefault); + + // Which algorithm and type the SDK picks depends on its version; whatever it sent, the stored + // value must be the one S3 would compute for that combination. + const h = await head(keys.byDefault); + if (h.ChecksumCRC32 && h.ChecksumType === 'COMPOSITE') { + expect(h.ChecksumCRC32).toBe(composite(crc32Bytes, pieces)); + } else if (h.ChecksumCRC32 && h.ChecksumType === 'FULL_OBJECT') { + expect(h.ChecksumCRC32).toBe(crc32Bytes(payload).toString('base64')); + } else if (h.ChecksumCRC64NVME) { + expect(h.ChecksumType).toBe('FULL_OBJECT'); + expect(h.ChecksumCRC64NVME).toBe(crc64Nvme(payload).toString('base64')); + } else { + throw new Error(`unexpected checksum on HeadObject: ${JSON.stringify(h)}`); + } + + const got = await s3.send( + new GetObjectCommand({ Bucket: bucket, Key: keys.byDefault, ChecksumMode: 'ENABLED' }) + ); + const body = Buffer.from(await got.Body!.transformToByteArray()); + expect(body.equals(payload)).toBe(true); + }); + + it('writes a copy of the multipart object as a single full object', async () => { + const source = await head(keys.sha256); + const copied = await s3.send( + new CopyObjectCommand({ + Bucket: bucket, + Key: keys.copy, + CopySource: `${bucket}/${keys.sha256}`, + }) + ); + const expectedETag = `"${md5Hex(payload)}"`; + expect(copied.CopyObjectResult?.ChecksumSHA256).toBe(sha256(payload).toString('base64')); + expect(copied.CopyObjectResult?.ChecksumType).toBe('FULL_OBJECT'); + expect(copied.CopyObjectResult?.ETag).toBe(expectedETag); + expect(copied.CopyObjectResult?.ETag).not.toBe(source.ETag); + + const h = await head(keys.copy); + expect(h.ChecksumSHA256).toBe(sha256(payload).toString('base64')); + expect(h.ChecksumType).toBe('FULL_OBJECT'); + expect(h.ETag).toBe(expectedETag); + }); +}); diff --git a/compatibility-tests/sdk-test-python/tests/test_s3.py b/compatibility-tests/sdk-test-python/tests/test_s3.py index 2292957d5b..1b2d4360c3 100644 --- a/compatibility-tests/sdk-test-python/tests/test_s3.py +++ b/compatibility-tests/sdk-test-python/tests/test_s3.py @@ -1,8 +1,16 @@ """S3 bucket and object integration tests.""" +import base64 +import hashlib +import random +import zlib + import pytest +from boto3.s3.transfer import TransferConfig from botocore.exceptions import ClientError +MIB = 1024 * 1024 + class TestS3Bucket: """Test S3 bucket operations.""" @@ -330,3 +338,162 @@ class TestS3LargeObject: response = s3_client.head_object(Bucket=test_bucket, Key=key) assert response["ContentLength"] == 25 * 1024 * 1024 + + +class TestS3MultipartChecksums: + """Multipart uploads carry composite checksums, computed as on AWS. + + AWS combines the part-level checksums of a multipart upload into a single object-level value: + the algorithm applied to the concatenated binary part checksums, Base64 encoded, followed by + ``-``. HeadObject/GetObject return that suffixed value, GetObjectAttributes returns + it without the suffix. SHA1/SHA256 uploads are always COMPOSITE, and so are CRC32 uploads + unless FULL_OBJECT is requested on CreateMultipartUpload. + """ + + PART_SIZE = 5 * MIB + TRANSFER_CONFIG = TransferConfig(multipart_threshold=5 * MIB, multipart_chunksize=5 * MIB) + + @staticmethod + def _payload(size=12 * MIB): + return random.Random(20260903).randbytes(size) + + @staticmethod + def _parts(payload, part_size): + return [payload[i:i + part_size] for i in range(0, len(payload), part_size)] + + @staticmethod + def _sha256(data): + return hashlib.sha256(data).digest() + + @staticmethod + def _crc32(data): + return (zlib.crc32(data) & 0xFFFFFFFF).to_bytes(4, "big") + + @classmethod + def _composite(cls, digest, parts): + combined = digest(b"".join(digest(part) for part in parts)) + return base64.b64encode(combined).decode() + f"-{len(parts)}" + + def _upload(self, s3_client, bucket, key, payload, tmp_path, **extra_args): + source = tmp_path / key + source.write_bytes(payload) + s3_client.upload_file( + str(source), bucket, key, + ExtraArgs=extra_args or None, + Config=self.TRANSFER_CONFIG, + ) + + def test_multipart_upload_sha256_reports_composite_checksum(self, s3_client, test_bucket, tmp_path): + """Multipart upload with SHA256 returns the composite checksum, stable across reads.""" + key = "multipart-sha256.bin" + payload = self._payload() + parts = self._parts(payload, self.PART_SIZE) + composite = self._composite(self._sha256, parts) + assert composite.endswith("-3") + + self._upload(s3_client, test_bucket, key, payload, tmp_path, ChecksumAlgorithm="SHA256") + + head = s3_client.head_object(Bucket=test_bucket, Key=key, ChecksumMode="ENABLED") + assert head["ChecksumSHA256"] == composite + assert head["ChecksumType"] == "COMPOSITE" + assert head["ETag"].endswith('-3"') + + # The same value on every read: a client comparing checksums must not see drift + again = s3_client.head_object(Bucket=test_bucket, Key=key, ChecksumMode="ENABLED") + assert again["ChecksumSHA256"] == composite + + attributes = s3_client.get_object_attributes( + Bucket=test_bucket, Key=key, ObjectAttributes=["Checksum", "ObjectParts"] + ) + assert attributes["Checksum"]["ChecksumSHA256"] == composite.rsplit("-", 1)[0] + assert attributes["Checksum"]["ChecksumType"] == "COMPOSITE" + assert attributes["ObjectParts"]["TotalPartsCount"] == 3 + assert [p["ChecksumSHA256"] for p in attributes["ObjectParts"]["Parts"]] == [ + base64.b64encode(self._sha256(part)).decode() for part in parts + ] + + body = s3_client.get_object(Bucket=test_bucket, Key=key)["Body"].read() + assert body == payload + + def test_multipart_upload_default_checksum_is_composite_crc32(self, s3_client, test_bucket, tmp_path): + """Without an explicit algorithm the SDK declares CRC32, which AWS stores as COMPOSITE.""" + key = "multipart-default.bin" + payload = self._payload() + parts = self._parts(payload, self.PART_SIZE) + + self._upload(s3_client, test_bucket, key, payload, tmp_path) + + head = s3_client.head_object(Bucket=test_bucket, Key=key, ChecksumMode="ENABLED") + assert head["ChecksumType"] == "COMPOSITE" + assert head["ChecksumCRC32"] == self._composite(self._crc32, parts) + + attributes = s3_client.get_object_attributes( + Bucket=test_bucket, Key=key, ObjectAttributes=["Checksum", "ObjectParts"] + ) + assert attributes["Checksum"]["ChecksumCRC32"] == head["ChecksumCRC32"].rsplit("-", 1)[0] + assert [p["ChecksumCRC32"] for p in attributes["ObjectParts"]["Parts"]] == [ + base64.b64encode(self._crc32(part)).decode() for part in parts + ] + + def test_single_part_upload_keeps_full_object_checksum(self, s3_client, test_bucket, tmp_path): + """A file below the multipart threshold is a plain PutObject: FULL_OBJECT, no suffix.""" + key = "single-part-sha256.bin" + payload = self._payload(1 * MIB) + + self._upload(s3_client, test_bucket, key, payload, tmp_path, ChecksumAlgorithm="SHA256") + + head = s3_client.head_object(Bucket=test_bucket, Key=key, ChecksumMode="ENABLED") + assert head["ChecksumSHA256"] == base64.b64encode(self._sha256(payload)).decode() + assert head["ChecksumType"] == "FULL_OBJECT" + assert "-" not in head["ETag"] + + def test_copy_of_multipart_object_is_a_single_full_object(self, s3_client, test_bucket, tmp_path): + """CopyObject writes one object: FULL_OBJECT checksum, an MD5 ETag without part count, no ObjectParts.""" + key, copy_key = "multipart-copy-source.bin", "multipart-copy.bin" + payload = self._payload() + self._upload(s3_client, test_bucket, key, payload, tmp_path, ChecksumAlgorithm="SHA256") + source = s3_client.head_object(Bucket=test_bucket, Key=key, ChecksumMode="ENABLED") + assert source["ChecksumType"] == "COMPOSITE" + + result = s3_client.copy_object( + Bucket=test_bucket, Key=copy_key, CopySource={"Bucket": test_bucket, "Key": key} + )["CopyObjectResult"] + full = base64.b64encode(self._sha256(payload)).decode() + assert result["ChecksumSHA256"] == full + assert result["ChecksumType"] == "FULL_OBJECT" + assert result["ETag"] == f'"{hashlib.md5(payload).hexdigest()}"' + assert result["ETag"] != source["ETag"] + + head = s3_client.head_object(Bucket=test_bucket, Key=copy_key, ChecksumMode="ENABLED") + assert (head["ChecksumSHA256"], head["ChecksumType"], head["ETag"]) == (full, "FULL_OBJECT", result["ETag"]) + attributes = s3_client.get_object_attributes( + Bucket=test_bucket, Key=copy_key, ObjectAttributes=["Checksum", "ObjectParts"] + ) + assert attributes["Checksum"]["ChecksumType"] == "FULL_OBJECT" + assert "ObjectParts" not in attributes + + def test_get_object_attributes_etag_has_no_quotes(self, s3_client, test_bucket, tmp_path): + """S3 quotes the ETag everywhere except in GetObjectAttributes.""" + key = "etag-quotes.bin" + self._upload(s3_client, test_bucket, key, self._payload(), tmp_path, ChecksumAlgorithm="SHA256") + + head_etag = s3_client.head_object(Bucket=test_bucket, Key=key)["ETag"] + attributes = s3_client.get_object_attributes(Bucket=test_bucket, Key=key, ObjectAttributes=["ETag"]) + + assert head_etag.startswith('"') and head_etag.endswith('-3"') + assert attributes["ETag"] == head_etag.strip('"') + + def test_download_with_checksum_mode_works_for_composite_and_full_object(self, s3_client, test_bucket, tmp_path): + """botocore validates a full-object checksum on GetObject and skips a composite one (the -N suffix).""" + payload, small = self._payload(), self._payload(1 * MIB) + self._upload(s3_client, test_bucket, "download-composite.bin", payload, tmp_path, ChecksumAlgorithm="SHA256") + self._upload(s3_client, test_bucket, "download-full.bin", small, tmp_path, ChecksumAlgorithm="SHA256") + + composite = s3_client.get_object(Bucket=test_bucket, Key="download-composite.bin", ChecksumMode="ENABLED") + assert composite["ChecksumSHA256"].endswith("-3") + assert composite["ChecksumType"] == "COMPOSITE" + assert composite["Body"].read() == payload + + full = s3_client.get_object(Bucket=test_bucket, Key="download-full.bin", ChecksumMode="ENABLED") + assert full["ChecksumType"] == "FULL_OBJECT" + assert full["Body"].read() == small diff --git a/docs/services/s3.md b/docs/services/s3.md index 6d7a7553ff..2c39ec4b84 100644 --- a/docs/services/s3.md +++ b/docs/services/s3.md @@ -346,12 +346,13 @@ Floci now persists and returns the following object attribute state on S3 object - storage class from `x-amz-storage-class` - checksum metadata for object reads and `GetObjectAttributes` - multipart part manifests for `GetObjectAttributes(ObjectParts)` +- multipart checksums follow the AWS checksum type: `COMPOSITE` (`-`) for SHA1, SHA256 and, by default, CRC32 and CRC32C; `FULL_OBJECT` for CRC64NVME or when `x-amz-checksum-type: FULL_OBJECT` was requested on `CreateMultipartUpload`. The `-N` suffix is returned by `CompleteMultipartUpload`, `HeadObject` and `GetObject`, and omitted by `GetObjectAttributes`, which lists part-level checksums only for `COMPOSITE` objects (a `FULL_OBJECT` multipart object reports its `PartsCount` alone, a single-part object has no `ObjectParts`), as on AWS. `UploadPart` echoes the part checksum (`x-amz-checksum-`) when the upload declared an algorithm, and completing a `COMPOSITE` upload requires the checksum of every part in the `CompleteMultipartUpload` body (`InvalidRequest` otherwise), while `FULL_OBJECT` uploads accept a body without them - canned object ACLs from `x-amz-acl` on `PutObject`, `CopyObject`, and multipart initiation - explicit object SSE headers from `x-amz-server-side-encryption` on `PutObject`, `CopyObject`, and multipart initiation, replayed on `GetObject` and `HeadObject` Current limitations: -- checksum responses focus on SHA-1 and SHA-256 +- checksum algorithms: CRC32, CRC32C, CRC64NVME, SHA1 and SHA256 are supported; the other AWS algorithms (SHA512, MD5, XXHASH3, XXHASH64, XXHASH128) are rejected with `InvalidRequest` - copy-based metadata updates support `x-amz-metadata-directive: REPLACE` for user metadata and content type, but do not yet cover every AWS copy header - explicit ACL grant headers such as `x-amz-grant-read` and `x-amz-grant-full-control` are not modeled yet - cross-account canned ACL variants collapse to the emulator's single synthetic owner where Floci does not model a distinct second principal diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index 928a9e0105..08fa27a58c 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -13,6 +13,8 @@ import io.github.hectorvent.floci.core.common.RequestContext; import io.github.hectorvent.floci.services.cloudtrail.CloudTrailService; import io.github.hectorvent.floci.services.sns.SnsQueryHandler; import io.github.hectorvent.floci.services.s3.model.Bucket; +import io.github.hectorvent.floci.services.s3.model.ChecksumAlgorithm; +import io.github.hectorvent.floci.services.s3.model.ChecksumType; import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesParts; import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesResult; import io.github.hectorvent.floci.services.s3.model.LambdaNotification; @@ -48,6 +50,7 @@ import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; @@ -711,11 +714,16 @@ public class S3Controller { } byte[] partData = decodeAwsChunked(body, contentEncoding, contentSha256); validateChecksumHeaders(httpHeaders, partData, getChecksumAlgorithm(httpHeaders)); - String eTag = s3Service.uploadPart(bucket, key, uploadId, partNumber, partData, + Part part = s3Service.storePart(bucket, key, uploadId, partNumber, partData, httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-algorithm"), httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key"), httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key-MD5")); - Response.ResponseBuilder response = Response.ok().header("ETag", eTag); + Response.ResponseBuilder response = Response.ok().header("ETag", part.getETag()); + // S3 echoes the part checksum only when the upload declared an algorithm. + ChecksumAlgorithm declared = s3Service.getMultipartUpload(bucket, key, uploadId).getChecksumAlgorithm(); + if (declared != null) { + response.header("x-amz-checksum-" + declared.wireValue(), part.getChecksum().valueFor(declared)); + } appendSseCustomerHeaders(response, httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-algorithm"), httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key-MD5")); @@ -1266,6 +1274,7 @@ public class S3Controller { httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key"), httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key-MD5"), getChecksumAlgorithm(httpHeaders), + httpHeaders.getHeaderString("x-amz-checksum-type"), parseInlineTaggingHeader(httpHeaders.getHeaderString("x-amz-tagging"))); String xml = new XmlBuilder() .raw("") @@ -1276,6 +1285,10 @@ public class S3Controller { .end("InitiateMultipartUploadResult") .build(); Response.ResponseBuilder response = Response.ok(xml); + if (upload.getChecksumAlgorithm() != null) { + response.header("x-amz-checksum-algorithm", upload.getChecksumAlgorithm().name()); + response.header("x-amz-checksum-type", upload.getChecksumType().name()); + } appendSseCustomerHeaders(response, upload); return response.build(); } @@ -1297,7 +1310,8 @@ public class S3Controller { if (uploadId != null) { s3Service.authorizeObjectWrite(bucket, key, "s3:PutObject", authorization); - List partNumbers = parseCompleteMultipartBody(new String(body)); + List completedParts = parseCompleteMultipartBody(new String(body, StandardCharsets.UTF_8)); + List partNumbers = completedParts.stream().map(CompletedPart::partNumber).toList(); Response preconditionResponse = checkWritePreconditions(bucket, key, ifMatch, ifNoneMatch); if (preconditionResponse != null) { return preconditionResponse; @@ -1305,7 +1319,7 @@ public class S3Controller { String checksumType = httpHeaders.getHeaderString("x-amz-checksum-type"); S3Checksum expectedChecksum = extractChecksumFromHeaders(httpHeaders); S3Object obj = s3Service.completeMultipartUpload(bucket, key, uploadId, partNumbers, - checksumType, expectedChecksum); + completedPartChecksums(completedParts), checksumType, expectedChecksum); String baseUrl = uriInfo.getBaseUri().toString(); if (baseUrl.endsWith("/")) { baseUrl = baseUrl.substring(0, baseUrl.length() - 1); @@ -1317,6 +1331,7 @@ public class S3Controller { .elem("Bucket", bucket) .elem("Key", key) .elem("ETag", obj.getETag()); + appendChecksumElements(xmlBuilder, obj.getChecksum()); if (obj.getVersionId() != null) { xmlBuilder.elem("VersionId", obj.getVersionId()); } @@ -1468,13 +1483,42 @@ public class S3Controller { return Response.ok(xml.build()).build(); } - private List parseCompleteMultipartBody(String xml) { - List parts = XmlParser.extractAll(xml, "PartNumber"); + private record CompletedPart(int partNumber, S3Checksum checksum) {} + + private List parseCompleteMultipartBody(String xml) { + List> parts = XmlParser.extractGroups(xml, "Part"); if (parts.isEmpty()) { - throw new AwsException("MalformedXML", - "The XML you provided was not well-formed.", 400); + throw malformedCompleteMultipartXml(); } - return parts.stream().map(Integer::parseInt).toList(); + List completedParts = new ArrayList<>(); + for (Map part : parts) { + int partNumber; + try { + partNumber = Integer.parseInt(part.getOrDefault("PartNumber", "").trim()); + } catch (NumberFormatException e) { + throw malformedCompleteMultipartXml(); + } + S3Checksum checksum = new S3Checksum(); + for (ChecksumAlgorithm algorithm : ChecksumAlgorithm.values()) { + checksum.setValueFor(algorithm, part.get("Checksum" + algorithm.name())); + } + completedParts.add(new CompletedPart(partNumber, checksum.hasAnyValue() ? checksum : null)); + } + return completedParts; + } + + private static AwsException malformedCompleteMultipartXml() { + return new AwsException("MalformedXML", "The XML you provided was not well-formed.", 400); + } + + private Map completedPartChecksums(List parts) { + Map checksums = new HashMap<>(); + for (CompletedPart part : parts) { + if (part.checksum() != null) { + checksums.put(part.partNumber(), part.checksum()); + } + } + return checksums; } // --- Versioning Operations --- @@ -2183,18 +2227,23 @@ public class S3Controller { .withGrantFullControl(httpHeaders.getHeaderString("x-amz-grant-full-control")) .withGrantReadAcp(httpHeaders.getHeaderString("x-amz-grant-read-acp")) .withGrantWriteAcp(httpHeaders.getHeaderString("x-amz-grant-write-acp"))); - String xml = new XmlBuilder() + XmlBuilder xmlBuilder = new XmlBuilder() .raw("") .start("CopyObjectResult", AwsNamespaces.S3) .elem("LastModified", ISO_FORMAT.format(copy.getLastModified())) - .elem("ETag", copy.getETag()) - .end("CopyObjectResult") - .build(); - Response.ResponseBuilder response = Response.ok(xml); + .elem("ETag", copy.getETag()); + appendChecksumElements(xmlBuilder, copy.getChecksum()); + String xml = xmlBuilder.end("CopyObjectResult").build(); + Response.ResponseBuilder response = Response.ok(xml).type(MediaType.APPLICATION_XML); appendSseCustomerHeaders(response, copy); return response.build(); } + // GetObjectAttributes is the one S3 response whose ETag comes without the surrounding quotes. + private static String unquoted(String eTag) { + return eTag == null ? null : eTag.replace("\"", ""); + } + private Response handleUploadPartCopy(String copySource, String destBucket, String destKey, String uploadId, int partNumber, HttpHeaders httpHeaders) { CopySourceRef sourceObject = parseCopySource(copySource); @@ -2242,7 +2291,7 @@ public class S3Controller { XmlBuilder xml = new XmlBuilder() .raw("") .start("GetObjectAttributesResponse", AwsNamespaces.S3) - .elem("ETag", result.getETag()); + .elem("ETag", unquoted(result.getETag())); appendChecksum(xml, result.getChecksum()); appendObjectParts(xml, result.getObjectParts()); if (result.getStorageClass() != null) { @@ -2267,22 +2316,33 @@ public class S3Controller { if (checksum == null || !checksum.hasAnyValue()) { return; } - xml.start("Checksum") - .elem("ChecksumCRC32", checksum.getChecksumCRC32()) + xml.start("Checksum"); + appendChecksumElements(xml, checksum); + xml.end("Checksum"); + } + + private void appendChecksumElements(XmlBuilder xml, S3Checksum checksum) { + if (checksum == null || !checksum.hasAnyValue()) { + return; + } + xml.elem("ChecksumCRC32", checksum.getChecksumCRC32()) .elem("ChecksumCRC32C", checksum.getChecksumCRC32C()) .elem("ChecksumCRC64NVME", checksum.getChecksumCRC64NVME()) .elem("ChecksumSHA1", checksum.getChecksumSHA1()) .elem("ChecksumSHA256", checksum.getChecksumSHA256()) - .elem("ChecksumType", checksum.getChecksumType()) - .end("Checksum"); + .elem("ChecksumType", checksum.getChecksumType() != null ? checksum.getChecksumType().name() : null); } private void appendObjectParts(XmlBuilder xml, GetObjectAttributesParts objectParts) { if (objectParts == null) { return; } - xml.start("ObjectParts") - .elem("IsTruncated", objectParts.isTruncated()) + xml.start("ObjectParts"); + if (!objectParts.isPartChecksumsAvailable()) { + xml.elem("PartsCount", objectParts.getPartsCount()).end("ObjectParts"); + return; + } + xml.elem("IsTruncated", objectParts.isTruncated()) .elem("MaxParts", objectParts.getMaxParts()) .elem("NextPartNumberMarker", objectParts.getNextPartNumberMarker()) .elem("PartNumberMarker", objectParts.getPartNumberMarker()); @@ -2320,6 +2380,9 @@ public class S3Controller { if (checksum.getChecksumSHA256() != null) { resp.header("x-amz-checksum-sha256", checksum.getChecksumSHA256()); } + if (checksum.getChecksumType() != null && checksum.hasAnyValue()) { + resp.header("x-amz-checksum-type", checksum.getChecksumType().name()); + } } private Map extractUserMetadata(HttpHeaders httpHeaders) { @@ -2352,7 +2415,7 @@ public class S3Controller { checksum.setChecksumCRC64NVME(crc64nvme); checksum.setChecksumSHA1(sha1); checksum.setChecksumSHA256(sha256); - checksum.setChecksumType("FULL_OBJECT"); + checksum.setChecksumType(ChecksumType.FULL_OBJECT); return checksum; } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index 17f5d39c57..426a527972 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -457,10 +457,10 @@ public class S3Service implements Resettable, ResourceProvider { object.getMetadata().putAll(metadata); } object.setStorageClass(ObjectAttributeName.normalizeStorageClass(effectiveOptions.getStorageClass())); - String validatedChecksumAlgorithm = validateAndNormalizeChecksumAlgorithm(effectiveOptions.getChecksumAlgorithm()); + ChecksumAlgorithm validatedChecksumAlgorithm = ChecksumAlgorithm.fromWireValue(effectiveOptions.getChecksumAlgorithm()); S3Checksum resolvedChecksum = checksum != null ? copyChecksum(checksum) : effectiveOptions.getClientChecksum() != null ? copyChecksum(effectiveOptions.getClientChecksum()) - : buildChecksum(data, parts, false, validatedChecksumAlgorithm); + : S3Checksum.fullObject(validatedChecksumAlgorithm, data); object.setChecksum(resolvedChecksum); object.setParts(copyParts(parts)); object.setContentEncoding(effectiveOptions.getContentEncoding()); @@ -1058,9 +1058,9 @@ public class S3Service implements Resettable, ResourceProvider { result.setObjectSize(object.getSize()); } if (attributes.contains(ObjectAttributeName.CHECKSUM)) { - result.setChecksum(copyChecksum(object.getChecksum())); + result.setChecksum(object.getChecksum() == null ? null : object.getChecksum().forObjectAttributes()); } - if (attributes.contains(ObjectAttributeName.OBJECT_PARTS)) { + if (attributes.contains(ObjectAttributeName.OBJECT_PARTS) && object.getParts() != null && !object.getParts().isEmpty()) { result.setObjectParts(buildObjectParts(object, maxParts, partNumberMarker)); } @@ -1081,9 +1081,16 @@ public class S3Service implements Resettable, ResourceProvider { return object; } + // AWS lists part-level checksums only for composite objects; a full-object multipart object + // reports its part count alone. private GetObjectAttributesParts buildObjectParts(S3Object object, Integer maxParts, Integer partNumberMarker) { List sortedParts = new ArrayList<>(copyParts(object.getParts())); sortedParts.sort(Comparator.comparingInt(Part::getPartNumber)); + if (object.getChecksum() == null || object.getChecksum().getChecksumType() != ChecksumType.COMPOSITE) { + GetObjectAttributesParts countOnly = new GetObjectAttributesParts(); + countOnly.setPartsCount(sortedParts.size()); + return countOnly; + } int max = (maxParts == null || maxParts <= 0) ? 1000 : maxParts; int marker = Math.max(partNumberMarker != null ? partNumberMarker : 0, 0); @@ -1094,6 +1101,7 @@ public class S3Service implements Resettable, ResourceProvider { List returnedParts = visibleParts.stream().limit(max).toList(); GetObjectAttributesParts result = new GetObjectAttributesParts(); + result.setPartChecksumsAvailable(true); result.setMaxParts(max); result.setPartNumberMarker(marker); result.setParts(returnedParts); @@ -2139,6 +2147,17 @@ public class S3Service implements Resettable, ResourceProvider { String contentDisposition, String serverSideEncryption, String acl, String sseCustomerAlgorithm, String sseCustomerKey, String sseCustomerKeyMd5, String checksumAlgorithm, Map tagging) { + return initiateMultipartUpload(bucket, key, contentType, metadata, storageClass, contentDisposition, + serverSideEncryption, acl, sseCustomerAlgorithm, sseCustomerKey, sseCustomerKeyMd5, + checksumAlgorithm, null, tagging); + } + + public MultipartUpload initiateMultipartUpload(String bucket, String key, String contentType, + Map metadata, String storageClass, + String contentDisposition, String serverSideEncryption, String acl, + String sseCustomerAlgorithm, String sseCustomerKey, String sseCustomerKeyMd5, + String checksumAlgorithm, String checksumType, + Map tagging) { ensureBucketExists(bucket); if (acl != null && !acl.isBlank()) { cannedObjectAclXml(acl); @@ -2158,7 +2177,14 @@ public class S3Service implements Resettable, ResourceProvider { upload.setSseCustomerKeyMd5(customerKey.keyMd5()); } upload.setAcl(acl); - upload.setChecksumAlgorithm(validateAndNormalizeChecksumAlgorithm(checksumAlgorithm)); + ChecksumAlgorithm algorithm = ChecksumAlgorithm.fromWireValue(checksumAlgorithm); + ChecksumType requestedChecksumType = ChecksumType.fromWireValue(checksumType); + if (requestedChecksumType != null && algorithm == null) { + throw new AwsException("InvalidRequest", + "The x-amz-checksum-type header can only be used with the x-amz-checksum-algorithm header.", 400); + } + upload.setChecksumAlgorithm(algorithm); + upload.setChecksumType(algorithm == null ? null : algorithm.multipartType(requestedChecksumType)); if (tagging != null && !tagging.isEmpty()) { upload.setTagging(new HashMap<>(tagging)); } @@ -2184,6 +2210,13 @@ public class S3Service implements Resettable, ResourceProvider { public String uploadPart(String bucket, String key, String uploadId, int partNumber, byte[] data, String sseCustomerAlgorithm, String sseCustomerKey, String sseCustomerKeyMd5) { + return storePart(bucket, key, uploadId, partNumber, data, sseCustomerAlgorithm, sseCustomerKey, sseCustomerKeyMd5) + .getETag(); + } + + /** Stores one part and returns it, with the ETag and the checksum the upload's algorithm gives it. */ + public Part storePart(String bucket, String key, String uploadId, int partNumber, byte[] data, + String sseCustomerAlgorithm, String sseCustomerKey, String sseCustomerKeyMd5) { MultipartUpload upload = multipartUploads.get(uploadId); if (upload == null || !upload.getBucket().equals(bucket) || !upload.getKey().equals(key)) { throw new AwsException("NoSuchUpload", @@ -2208,10 +2241,10 @@ public class S3Service implements Resettable, ResourceProvider { String eTag = computeETag(data); Part part = new Part(partNumber, eTag, data.length); - part.setChecksum(buildChecksum(data, List.of(part), true, upload.getChecksumAlgorithm())); + part.setChecksum(S3Checksum.of(upload.getChecksumAlgorithm(), data)); upload.getParts().put(partNumber, part); LOG.debugv("Uploaded part {0} for upload {1} ({2} bytes)", partNumber, uploadId, data.length); - return eTag; + return part; } public String uploadPartCopy(String destBucket, String destKey, String uploadId, int partNumber, @@ -2251,20 +2284,33 @@ public class S3Service implements Resettable, ResourceProvider { public S3Object completeMultipartUpload(String bucket, String key, String uploadId, List partNumbers, String checksumType, S3Checksum expectedChecksum) { + return completeMultipartUpload(bucket, key, uploadId, partNumbers, Map.of(), checksumType, expectedChecksum); + } + + public S3Object completeMultipartUpload(String bucket, String key, String uploadId, List partNumbers, + Map partChecksums, + String checksumType, S3Checksum expectedChecksum) { MultipartUpload upload = multipartUploads.get(uploadId); if (upload == null || !upload.getBucket().equals(bucket) || !upload.getKey().equals(key)) { throw new AwsException("NoSuchUpload", "The specified multipart upload does not exist.", 404); } - // Verify all requested parts exist + ChecksumAlgorithm algorithm = upload.getChecksumAlgorithm() != null ? upload.getChecksumAlgorithm() : ChecksumAlgorithm.CRC64NVME; + ChecksumType storedChecksumType = upload.getChecksumType() != null ? upload.getChecksumType() : ChecksumType.FULL_OBJECT; + + // Verify all requested parts exist and carry the checksums the upload requires for (int num : partNumbers) { - if (!upload.getParts().containsKey(num)) { + Part part = upload.getParts().get(num); + if (part == null) { throw new AwsException("InvalidPart", "One or more of the specified parts could not be found. Part " + num + " is missing.", 400); } + validatePartChecksum(upload.getChecksumAlgorithm(), storedChecksumType, num, part, partChecksums.get(num)); } + validateCompleteChecksumType(algorithm, storedChecksumType, ChecksumType.fromWireValue(checksumType)); + // Concatenate parts in order try { ByteArrayOutputStream combined = new ByteArrayOutputStream(); @@ -2281,21 +2327,18 @@ public class S3Service implements Resettable, ResourceProvider { byte[] allData = combined.toByteArray(); - boolean fullObjectChecksumRequested = "FULL_OBJECT".equalsIgnoreCase(checksumType) - && expectedChecksum != null && expectedChecksum.hasAnyValue(); - if (fullObjectChecksumRequested) { - validateFullObjectChecksum(allData, expectedChecksum); - } - // Composite ETag: MD5 of concatenated part MD5s, suffixed with part count String compositeETag = "\"" + bytesToHex(md.digest()) + "-" + partNumbers.size() + "\""; List completedParts = partNumbers.stream() .map(num -> copyPart(upload.getParts().get(num))) .toList(); - S3Checksum checksum = buildChecksum(allData, completedParts, true, upload.getChecksumAlgorithm()); - if (fullObjectChecksumRequested) { - checksum.setChecksumType("FULL_OBJECT"); + S3Checksum checksum = storedChecksumType == ChecksumType.COMPOSITE + ? S3Checksum.composite(algorithm, completedParts.stream() + .map(part -> part.getChecksum().valueFor(algorithm)).toList()) + : S3Checksum.fullObject(algorithm, allData); + if (expectedChecksum != null && expectedChecksum.hasAnyValue()) { + validateExpectedChecksum(checksum, expectedChecksum); } S3Object object = storeObject(bucket, key, allData, upload.getContentType(), upload.getMetadata(), checksum, completedParts, @@ -2344,6 +2387,10 @@ public class S3Service implements Resettable, ResourceProvider { } public MultipartUpload listParts(String bucket, String key, String uploadId) { + return getMultipartUpload(bucket, key, uploadId); + } + + public MultipartUpload getMultipartUpload(String bucket, String key, String uploadId) { MultipartUpload upload = multipartUploads.get(uploadId); if (upload == null || !upload.getBucket().equals(bucket) || !upload.getKey().equals(key)) { throw new AwsException("NoSuchUpload", @@ -3350,57 +3397,62 @@ public class S3Service implements Resettable, ResourceProvider { } } - public static String validateAndNormalizeChecksumAlgorithm(String algorithm) { - if (algorithm == null || algorithm.isBlank()) { - return null; + private static void validateCompleteChecksumType(ChecksumAlgorithm algorithm, ChecksumType storedType, + ChecksumType requestedType) { + if (requestedType == null) { + return; } - String normalized = algorithm.trim().toUpperCase(java.util.Locale.ROOT); - if (normalized.equals("CRC32") || normalized.equals("CRC32C") || normalized.equals("SHA1") || normalized.equals("SHA256") || normalized.equals("CRC64NVME")) { - return normalized; - } - if (normalized.equals("SHA512") || normalized.equals("MD5") || normalized.equals("XXHASH3") || normalized.equals("XXHASH64") || normalized.equals("XXHASH128")) { - throw new AwsException("InvalidRequest", "The checksum algorithm you specified is a valid AWS checksum algorithm, but is not currently supported by Floci (supported: CRC32, CRC32C, CRC64NVME, SHA1, SHA256).", 400); - } - throw new AwsException("InvalidArgument", "The checksum algorithm you specified is not supported.", 400); - } - - private static void validateFullObjectChecksum(byte[] data, S3Checksum expected) { - if (expected.getChecksumSHA1() != null || expected.getChecksumSHA256() != null) { + if (requestedType == ChecksumType.FULL_OBJECT && !algorithm.supports(ChecksumType.FULL_OBJECT)) { throw new AwsException("InvalidRequest", - "The FULL_OBJECT checksum type is not supported with the SHA1 or SHA256 checksum algorithm. " - + "Full object checksums are only supported with the CRC32, CRC32C, and CRC64NVME checksum algorithms.", - 400); + "The algorithm type you specified in x-amz-checksum- header is invalid.", 400); } - if (expected.getChecksumCRC32() != null && !expected.getChecksumCRC32().equals(S3Checksum.crc32Base64(data))) { - throw new AwsException("BadDigest", "The CRC32 checksum you specified did not match the payload.", 400); - } - if (expected.getChecksumCRC32C() != null && !expected.getChecksumCRC32C().equals(S3Checksum.crc32cBase64(data))) { - throw new AwsException("BadDigest", "The CRC32C checksum you specified did not match the payload.", 400); - } - if (expected.getChecksumCRC64NVME() != null - && !expected.getChecksumCRC64NVME().equals(S3Checksum.crc64NvmeBase64(data))) { - throw new AwsException("BadDigest", "The CRC64NVME checksum you specified did not match the payload.", 400); + if (requestedType != storedType) { + throw new AwsException("InvalidRequest", + "The upload was created using the " + storedType + " checksum mode. " + + "The complete request must use the same checksum mode.", 400); } } - private static S3Checksum buildChecksum(byte[] data, List parts, boolean multipartUpload) { - return buildChecksum(data, parts, multipartUpload, null); + // As on S3: a COMPOSITE upload needs the checksum of every part in the request body, a checksum for + // another algorithm is a BadDigest, a wrong value an InvalidPart. FULL_OBJECT uploads need none. + private static void validatePartChecksum(ChecksumAlgorithm declared, ChecksumType storedType, int partNumber, + Part uploaded, S3Checksum expected) { + if (expected == null || !expected.hasAnyValue()) { + if (declared != null && storedType == ChecksumType.COMPOSITE) { + throw new AwsException("InvalidRequest", "The upload was created using a " + declared.wireValue() + + " checksum. The complete request must include the checksum for each part. It was missing for part " + + partNumber + " in the request.", 400); + } + return; + } + ChecksumAlgorithm algorithm = declared != null && expected.valueFor(declared) != null ? declared : expected.algorithm(); + if (declared != null && algorithm != declared) { + throw new AwsException("BadDigest", "The " + algorithm.wireValue() + " you specified for part " + partNumber + + " did not match what we received.", 400); + } + if (!expected.valueFor(algorithm).equals(uploaded.getChecksum().valueFor(algorithm))) { + throw new AwsException("InvalidPart", + "One or more of the specified parts could not be found. The part may not have been uploaded, " + + "or the specified entity tag may not match the part's entity tag.", 400); + } } - private static S3Checksum buildChecksum(byte[] data, List parts, boolean multipartUpload, String algorithm) { - S3Checksum checksum = new S3Checksum(); - String algo = (algorithm != null) ? algorithm.toUpperCase() : "CRC64NVME"; - switch (algo) { - case "CRC32" -> checksum.setChecksumCRC32(S3Checksum.crc32Base64(data)); - case "CRC32C" -> checksum.setChecksumCRC32C(S3Checksum.crc32cBase64(data)); - case "SHA1" -> checksum.setChecksumSHA1(S3Checksum.sha1Base64(data)); - case "SHA256" -> checksum.setChecksumSHA256(S3Checksum.sha256Base64(data)); - default -> checksum.setChecksumCRC64NVME(S3Checksum.crc64NvmeBase64(data)); + // AWS accepts a composite value with or without its "-N" suffix, but a wrong suffix is a BadDigest. + private static void validateExpectedChecksum(S3Checksum computed, S3Checksum expected) { + for (ChecksumAlgorithm algorithm : ChecksumAlgorithm.values()) { + String expectedValue = expected.valueFor(algorithm); + if (expectedValue == null) { + continue; + } + String computedValue = computed.valueFor(algorithm); + boolean matches = expectedValue.equals(computedValue) + || (computed.getChecksumType() == ChecksumType.COMPOSITE + && expectedValue.equals(S3Checksum.withoutPartCount(computedValue))); + if (!matches) { + throw new AwsException("BadDigest", "The " + algorithm.wireValue() + + " you specified did not match the calculated checksum.", 400); + } } - checksum.setChecksumType(multipartUpload || (parts != null && parts.size() > 1) - ? "COMPOSITE" - : "FULL_OBJECT"); - return checksum; } private static S3Object copyObject(S3Object source) { @@ -3435,17 +3487,7 @@ public class S3Service implements Resettable, ResourceProvider { } private static S3Checksum copyChecksum(S3Checksum source) { - if (source == null) { - return null; - } - S3Checksum copy = new S3Checksum(); - copy.setChecksumCRC32(source.getChecksumCRC32()); - copy.setChecksumCRC32C(source.getChecksumCRC32C()); - copy.setChecksumCRC64NVME(source.getChecksumCRC64NVME()); - copy.setChecksumSHA1(source.getChecksumSHA1()); - copy.setChecksumSHA256(source.getChecksumSHA256()); - copy.setChecksumType(source.getChecksumType()); - return copy; + return source == null ? null : source.copy(); } private static List copyParts(List sourceParts) { @@ -3860,14 +3902,20 @@ public class S3Service implements Resettable, ResourceProvider { ? effectiveOptions.getReplacementTagging() : source.getTags(); + // A copy is written as one object without a part manifest; a composite source gets a + // full-object checksum recomputed with its algorithm, as AWS does. S3Checksum effectiveChecksum = source.getChecksum(); - String copyChecksumAlgorithm = validateAndNormalizeChecksumAlgorithm(effectiveOptions.getChecksumAlgorithm()); + ChecksumAlgorithm copyChecksumAlgorithm = ChecksumAlgorithm.fromWireValue(effectiveOptions.getChecksumAlgorithm()); + if (copyChecksumAlgorithm == null && effectiveChecksum != null + && effectiveChecksum.getChecksumType() == ChecksumType.COMPOSITE) { + copyChecksumAlgorithm = effectiveChecksum.algorithm(); + } if (copyChecksumAlgorithm != null) { effectiveChecksum = null; } S3Object copy = storeObject(destBucket, destKey, source.getData(), effectiveContentType, metadata, - effectiveChecksum, copyChecksumAlgorithm != null ? null : source.getParts(), + effectiveChecksum, null, new PutObjectOptions() .withStorageClass(effectiveStorageClass) .withContentEncoding(effectiveContentEncoding) @@ -3883,9 +3931,10 @@ public class S3Service implements Resettable, ResourceProvider { .withGrantFullControl(effectiveOptions.getGrantFullControl()) .withGrantReadAcp(effectiveOptions.getGrantReadAcp()) .withGrantWriteAcp(effectiveOptions.getGrantWriteAcp()) - .withChecksumAlgorithm(copyChecksumAlgorithm) + .withChecksumAlgorithm(copyChecksumAlgorithm != null ? copyChecksumAlgorithm.name() : null) .withTagging(effectiveTags)); - copy.setETag(source.getETag()); + // A copy is written as one object, so it keeps the ETag storeObject computed (the MD5 of the + // whole content) instead of the source's, which for a multipart source ends in "-N". As on S3. LOG.debugv("Copied object: {0}/{1} -> {2}/{3}", sourceBucket, sourceKey, destBucket, destKey); fireNotifications(destBucket, destKey, "ObjectCreated:Copy", copy); return copy; diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumAlgorithm.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumAlgorithm.java new file mode 100644 index 0000000000..36bb1487ce --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumAlgorithm.java @@ -0,0 +1,100 @@ +package io.github.hectorvent.floci.services.s3.model; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.io.ByteArrayOutputStream; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +/** + * Checksum algorithms Floci supports, with the multipart checksum types AWS allows for each one: + * SHA1 and SHA256 are always {@code COMPOSITE}, CRC64NVME is always {@code FULL_OBJECT}, and + * CRC32 and CRC32C accept both, defaulting to {@code COMPOSITE}. + */ +@RegisterForReflection +public enum ChecksumAlgorithm { + CRC32(Set.of(ChecksumType.COMPOSITE, ChecksumType.FULL_OBJECT)), + CRC32C(Set.of(ChecksumType.COMPOSITE, ChecksumType.FULL_OBJECT)), + CRC64NVME(Set.of(ChecksumType.FULL_OBJECT)), + SHA1(Set.of(ChecksumType.COMPOSITE)), + SHA256(Set.of(ChecksumType.COMPOSITE)); + + /** Algorithms AWS accepts but Floci does not implement yet. */ + private static final Set KNOWN_UNSUPPORTED = Set.of("SHA512", "MD5", "XXHASH3", "XXHASH64", "XXHASH128"); + + private final Set multipartTypes; + + ChecksumAlgorithm(Set multipartTypes) { + this.multipartTypes = multipartTypes; + } + + /** Lowercase name, as AWS spells the algorithm in error messages. */ + public String wireValue() { + return name().toLowerCase(Locale.ROOT); + } + + public boolean supports(ChecksumType type) { + return multipartTypes.contains(type); + } + + /** + * The checksum type a multipart upload with this algorithm ends up with: the requested one when + * the algorithm allows it, otherwise the default (COMPOSITE where supported, else FULL_OBJECT). + */ + public ChecksumType multipartType(ChecksumType requested) { + if (requested == null) { + return supports(ChecksumType.COMPOSITE) ? ChecksumType.COMPOSITE : ChecksumType.FULL_OBJECT; + } + if (!supports(requested)) { + throw new AwsException("InvalidRequest", "The " + requested + " checksum type cannot be used with the " + + wireValue() + " checksum algorithm.", 400); + } + return requested; + } + + /** Base64 checksum of {@code data} with this algorithm. */ + public String compute(byte[] data) { + return switch (this) { + case CRC32 -> S3Checksum.crc32Base64(data); + case CRC32C -> S3Checksum.crc32cBase64(data); + case CRC64NVME -> S3Checksum.crc64NvmeBase64(data); + case SHA1 -> S3Checksum.sha1Base64(data); + case SHA256 -> S3Checksum.sha256Base64(data); + }; + } + + /** + * Composite checksum of a multipart object: this algorithm applied to the concatenated binary + * part checksums, Base64 encoded and suffixed with the part count (for example {@code ...=-3}). + */ + public String composite(List partChecksums) { + ByteArrayOutputStream concatenated = new ByteArrayOutputStream(); + for (String partChecksum : partChecksums) { + concatenated.writeBytes(Base64.getDecoder().decode(partChecksum)); + } + return compute(concatenated.toByteArray()) + "-" + partChecksums.size(); + } + + /** + * Parses an {@code x-amz-checksum-algorithm} value. Returns {@code null} when the header is absent. + */ + public static ChecksumAlgorithm fromWireValue(String value) { + if (value == null || value.isBlank()) { + return null; + } + String normalized = value.trim().toUpperCase(Locale.ROOT); + for (ChecksumAlgorithm algorithm : values()) { + if (algorithm.name().equals(normalized)) { + return algorithm; + } + } + if (KNOWN_UNSUPPORTED.contains(normalized)) { + throw new AwsException("InvalidRequest", "The checksum algorithm you specified is a valid AWS checksum " + + "algorithm, but is not currently supported by Floci (supported: CRC32, CRC32C, CRC64NVME, SHA1, SHA256).", 400); + } + throw new AwsException("InvalidArgument", "The checksum algorithm you specified is not supported.", 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumType.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumType.java new file mode 100644 index 0000000000..2ab185ec42 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumType.java @@ -0,0 +1,32 @@ +package io.github.hectorvent.floci.services.s3.model; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.quarkus.runtime.annotations.RegisterForReflection; + +import java.util.Locale; + +/** The two ways S3 derives an object checksum from a multipart upload. */ +@RegisterForReflection +public enum ChecksumType { + /** The algorithm applied to the concatenated part checksums, suffixed with the part count. */ + COMPOSITE, + /** The algorithm applied to the whole object content. */ + FULL_OBJECT; + + /** + * Parses an {@code x-amz-checksum-type} value, case-insensitively like S3. Returns {@code null} when the + * header is absent; an unknown value is the {@code InvalidRequest} S3 returns for it. + */ + public static ChecksumType fromWireValue(String value) { + if (value == null || value.isBlank()) { + return null; + } + String normalized = value.trim().toUpperCase(Locale.ROOT); + for (ChecksumType type : values()) { + if (type.name().equals(normalized)) { + return type; + } + } + throw new AwsException("InvalidRequest", "Value for x-amz-checksum-type header is invalid.", 400); + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/GetObjectAttributesParts.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/GetObjectAttributesParts.java index 4f6de58511..4a84301694 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/GetObjectAttributesParts.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/GetObjectAttributesParts.java @@ -13,6 +13,7 @@ public class GetObjectAttributesParts { private int nextPartNumberMarker; private int partNumberMarker; private int partsCount; + private boolean partChecksumsAvailable; private List parts = new ArrayList<>(); public boolean isTruncated() { return isTruncated; } @@ -30,6 +31,9 @@ public class GetObjectAttributesParts { public int getPartsCount() { return partsCount; } public void setPartsCount(int partsCount) { this.partsCount = partsCount; } + public boolean isPartChecksumsAvailable() { return partChecksumsAvailable; } + public void setPartChecksumsAvailable(boolean partChecksumsAvailable) { this.partChecksumsAvailable = partChecksumsAvailable; } + public List getParts() { return parts; } public void setParts(List parts) { this.parts = parts; } } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/MultipartUpload.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/MultipartUpload.java index 87fa66b70c..b7df391aac 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/MultipartUpload.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/MultipartUpload.java @@ -21,7 +21,8 @@ public class MultipartUpload { private String sseCustomerAlgorithm; private String sseCustomerKeyMd5; private String acl; - private String checksumAlgorithm; + private ChecksumAlgorithm checksumAlgorithm; + private ChecksumType checksumType; private Map metadata; private Map tagging; private Instant initiated; @@ -72,8 +73,11 @@ public class MultipartUpload { public String getAcl() { return acl; } public void setAcl(String acl) { this.acl = acl; } - public String getChecksumAlgorithm() { return checksumAlgorithm; } - public void setChecksumAlgorithm(String checksumAlgorithm) { this.checksumAlgorithm = checksumAlgorithm; } + public ChecksumAlgorithm getChecksumAlgorithm() { return checksumAlgorithm; } + public void setChecksumAlgorithm(ChecksumAlgorithm checksumAlgorithm) { this.checksumAlgorithm = checksumAlgorithm; } + + public ChecksumType getChecksumType() { return checksumType; } + public void setChecksumType(ChecksumType checksumType) { this.checksumType = checksumType; } public Map getMetadata() { return metadata; } public void setMetadata(Map metadata) { this.metadata = metadata; } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Checksum.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Checksum.java index 08fae8e03e..0af5bd56f3 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Checksum.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Checksum.java @@ -5,12 +5,16 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Base64; +import java.util.List; +import java.util.regex.Pattern; import java.util.zip.CRC32; import java.util.zip.CRC32C; @RegisterForReflection public class S3Checksum { + private static final Pattern PART_COUNT_SUFFIX = Pattern.compile("-\\d+$"); + private static final long CRC64_NVME_POLY = 0x9a6c9329ac4bc9b5L; private static final long[] CRC64_TABLE = buildCrc64Table(); @@ -19,7 +23,7 @@ public class S3Checksum { private String checksumCRC64NVME; private String checksumSHA1; private String checksumSHA256; - private String checksumType; + private ChecksumType checksumType; public String getChecksumCRC32() { return checksumCRC32; } public void setChecksumCRC32(String checksumCRC32) { this.checksumCRC32 = checksumCRC32; } @@ -36,14 +40,90 @@ public class S3Checksum { public String getChecksumSHA256() { return checksumSHA256; } public void setChecksumSHA256(String checksumSHA256) { this.checksumSHA256 = checksumSHA256; } - public String getChecksumType() { return checksumType; } - public void setChecksumType(String checksumType) { this.checksumType = checksumType; } + public ChecksumType getChecksumType() { return checksumType; } + public void setChecksumType(ChecksumType checksumType) { this.checksumType = checksumType; } public boolean hasAnyValue() { return checksumCRC32 != null || checksumCRC32C != null || checksumCRC64NVME != null || checksumSHA1 != null || checksumSHA256 != null; } + public String valueFor(ChecksumAlgorithm algorithm) { + return switch (algorithm) { + case CRC32 -> checksumCRC32; + case CRC32C -> checksumCRC32C; + case CRC64NVME -> checksumCRC64NVME; + case SHA1 -> checksumSHA1; + case SHA256 -> checksumSHA256; + }; + } + + public void setValueFor(ChecksumAlgorithm algorithm, String value) { + switch (algorithm) { + case CRC32 -> checksumCRC32 = value; + case CRC32C -> checksumCRC32C = value; + case CRC64NVME -> checksumCRC64NVME = value; + case SHA1 -> checksumSHA1 = value; + case SHA256 -> checksumSHA256 = value; + } + } + + /** The algorithm whose value is set, or {@code null} when the checksum is empty. */ + public ChecksumAlgorithm algorithm() { + for (ChecksumAlgorithm algorithm : ChecksumAlgorithm.values()) { + if (valueFor(algorithm) != null) { + return algorithm; + } + } + return null; + } + + /** Checksum of {@code data} with no type, as stored for a part. S3 uses CRC64NVME when no algorithm was declared. */ + public static S3Checksum of(ChecksumAlgorithm algorithm, byte[] data) { + ChecksumAlgorithm effective = algorithm != null ? algorithm : ChecksumAlgorithm.CRC64NVME; + S3Checksum checksum = new S3Checksum(); + checksum.setValueFor(effective, effective.compute(data)); + return checksum; + } + + public static S3Checksum fullObject(ChecksumAlgorithm algorithm, byte[] data) { + S3Checksum checksum = of(algorithm, data); + checksum.setChecksumType(ChecksumType.FULL_OBJECT); + return checksum; + } + + public static S3Checksum composite(ChecksumAlgorithm algorithm, List partChecksums) { + S3Checksum checksum = new S3Checksum(); + checksum.setValueFor(algorithm, algorithm.composite(partChecksums)); + checksum.setChecksumType(ChecksumType.COMPOSITE); + return checksum; + } + + public S3Checksum copy() { + S3Checksum copy = new S3Checksum(); + copy.checksumCRC32 = checksumCRC32; + copy.checksumCRC32C = checksumCRC32C; + copy.checksumCRC64NVME = checksumCRC64NVME; + copy.checksumSHA1 = checksumSHA1; + copy.checksumSHA256 = checksumSHA256; + copy.checksumType = checksumType; + return copy; + } + + /** The checksum as GetObjectAttributes reports it: a composite value loses the {@code -N} suffix HeadObject carries. */ + public S3Checksum forObjectAttributes() { + S3Checksum copy = copy(); + if (copy.checksumType == ChecksumType.COMPOSITE) { + ChecksumAlgorithm algorithm = copy.algorithm(); + copy.setValueFor(algorithm, withoutPartCount(copy.valueFor(algorithm))); + } + return copy; + } + + public static String withoutPartCount(String checksum) { + return checksum == null ? null : PART_COUNT_SUFFIX.matcher(checksum).replaceFirst(""); + } + public static String crc32Base64(byte[] data) { CRC32 crc = new CRC32(); crc.update(data); diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java index ddac70f939..d2f1e0fa21 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java @@ -71,7 +71,7 @@ public class S3Object { this.storageClass = "STANDARD"; this.checksum = new S3Checksum(); this.checksum.setChecksumSHA256(S3Checksum.sha256Base64(data)); - this.checksum.setChecksumType("FULL_OBJECT"); + this.checksum.setChecksumType(ChecksumType.FULL_OBJECT); this.parts = new ArrayList<>(); this.tags = new HashMap<>(); } diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ChecksumTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ChecksumTest.java new file mode 100644 index 0000000000..a2210da56b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ChecksumTest.java @@ -0,0 +1,142 @@ +package io.github.hectorvent.floci.services.s3; + +import io.github.hectorvent.floci.core.common.AwsException; +import io.github.hectorvent.floci.services.s3.model.ChecksumAlgorithm; +import io.github.hectorvent.floci.services.s3.model.ChecksumType; +import io.github.hectorvent.floci.services.s3.model.S3Checksum; +import org.junit.jupiter.api.Test; + +import java.nio.charset.StandardCharsets; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.*; + +/** + * Composite vectors were captured from real Amazon S3 (eu-west-1, September 2026): the part checksums are + * what UploadPart returned and the composite values are what CompleteMultipartUpload and HeadObject reported. + */ +class S3ChecksumTest { + + @Test + void compositeSha256MatchesAws() { + assertEquals("rVWtNbadtsaKXJAcgWPWjifHzJaXde/iV4jaJAOdivc=-3", ChecksumAlgorithm.SHA256.composite(List.of( + "lcKa6Boe7a167tUCN5C4OaFygGSYD8MBnBARTrdL+1w=", + "gHjhbUT4oo2tSCtSZJdlKi+jeNXJT+VImqdPXsXvkOc=", + "4l9PQ3zOPZ0oGFvknFX+J4zZwE4WMzO+l3r8XrbWOeM="))); + } + + @Test + void compositeOfSinglePartStillCarriesPartCount() { + assertEquals("D0xEU2q/FgypQljU/eaDWTSRcnDG3KQGOtevJWcmMRY=-1", + ChecksumAlgorithm.SHA256.composite(List.of("n7gWa0Gp88JMie9iljKcv731WbPhWtFVibhxsVB8FAw="))); + } + + @Test + void compositeSha1MatchesAws() { + assertEquals("CBB1y8xhBCot1HoCMQCx18NR2tU=-2", ChecksumAlgorithm.SHA1.composite(List.of( + "1/0x5kkt8+9IA/j+B6LiWtFTdrY=", "H2o2aM+t5OzS5CuqgWtQ90pWCpo="))); + } + + @Test + void compositeCrc32MatchesAws() { + assertEquals("R/nORQ==-2", ChecksumAlgorithm.CRC32.composite(List.of("W0QpDQ==", "anCi7Q=="))); + } + + @Test + void compositeCrc32cMatchesAws() { + assertEquals("ROC8NA==-2", ChecksumAlgorithm.CRC32C.composite(List.of("wMKxiw==", "myWdrQ=="))); + } + + @Test + void withoutPartCountStripsOnlyTheSuffix() { + assertEquals("rVWtNbadtsaKXJAcgWPWjifHzJaXde/iV4jaJAOdivc=", + S3Checksum.withoutPartCount("rVWtNbadtsaKXJAcgWPWjifHzJaXde/iV4jaJAOdivc=-3")); + assertEquals("+SDIDA==", S3Checksum.withoutPartCount("+SDIDA==")); + assertNull(S3Checksum.withoutPartCount(null)); + } + + @Test + void computeDispatchesOnAlgorithm() { + byte[] data = "hello".getBytes(StandardCharsets.UTF_8); + assertEquals(S3Checksum.sha256Base64(data), ChecksumAlgorithm.SHA256.compute(data)); + assertEquals(S3Checksum.sha1Base64(data), ChecksumAlgorithm.SHA1.compute(data)); + assertEquals(S3Checksum.crc32Base64(data), ChecksumAlgorithm.CRC32.compute(data)); + assertEquals(S3Checksum.crc32cBase64(data), ChecksumAlgorithm.CRC32C.compute(data)); + assertEquals(S3Checksum.crc64NvmeBase64(data), ChecksumAlgorithm.CRC64NVME.compute(data)); + } + + @Test + void objectWithoutDeclaredAlgorithmGetsCrc64Nvme() { + byte[] data = "hello".getBytes(StandardCharsets.UTF_8); + S3Checksum checksum = S3Checksum.fullObject(null, data); + assertEquals(ChecksumAlgorithm.CRC64NVME, checksum.algorithm()); + assertEquals(S3Checksum.crc64NvmeBase64(data), checksum.getChecksumCRC64NVME()); + assertEquals(ChecksumType.FULL_OBJECT, checksum.getChecksumType()); + } + + @Test + void objectAttributesViewDropsTheSuffixOfCompositeValuesOnly() { + S3Checksum composite = S3Checksum.composite(ChecksumAlgorithm.CRC32, List.of("W0QpDQ==", "anCi7Q==")); + assertEquals("R/nORQ==-2", composite.getChecksumCRC32()); + assertEquals("R/nORQ==", composite.forObjectAttributes().getChecksumCRC32()); + assertEquals("R/nORQ==-2", composite.getChecksumCRC32(), "the stored checksum is left untouched"); + + S3Checksum fullObject = S3Checksum.fullObject(ChecksumAlgorithm.CRC32, new byte[0]); + assertEquals(fullObject.getChecksumCRC32(), fullObject.forObjectAttributes().getChecksumCRC32()); + } + + @Test + void valueAccessorsFollowTheAlgorithm() { + S3Checksum checksum = new S3Checksum(); + assertNull(checksum.algorithm()); + checksum.setValueFor(ChecksumAlgorithm.CRC32C, "wMKxiw=="); + assertEquals(ChecksumAlgorithm.CRC32C, checksum.algorithm()); + assertEquals("wMKxiw==", checksum.getChecksumCRC32C()); + assertEquals("wMKxiw==", checksum.valueFor(ChecksumAlgorithm.CRC32C)); + assertNull(checksum.valueFor(ChecksumAlgorithm.SHA256)); + } + + @Test + void algorithmHeaderParsingIsCaseInsensitiveAndRejectsUnknownValues() { + assertEquals(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.fromWireValue("sha256")); + assertEquals(ChecksumAlgorithm.CRC64NVME, ChecksumAlgorithm.fromWireValue(" CRC64NVME ")); + assertNull(ChecksumAlgorithm.fromWireValue(null)); + assertNull(ChecksumAlgorithm.fromWireValue(" ")); + + AwsException knownButUnsupported = assertThrows(AwsException.class, () -> ChecksumAlgorithm.fromWireValue("SHA512")); + assertEquals("InvalidRequest", knownButUnsupported.getErrorCode()); + AwsException unknown = assertThrows(AwsException.class, () -> ChecksumAlgorithm.fromWireValue("MURMUR3")); + assertEquals("InvalidArgument", unknown.getErrorCode()); + } + + @Test + void multipartTypeFollowsTheAwsAlgorithmTable() { + assertEquals(ChecksumType.COMPOSITE, ChecksumAlgorithm.SHA256.multipartType(null)); + assertEquals(ChecksumType.COMPOSITE, ChecksumAlgorithm.SHA1.multipartType(null)); + assertEquals(ChecksumType.COMPOSITE, ChecksumAlgorithm.CRC32.multipartType(null)); + assertEquals(ChecksumType.COMPOSITE, ChecksumAlgorithm.CRC32C.multipartType(null)); + assertEquals(ChecksumType.FULL_OBJECT, ChecksumAlgorithm.CRC64NVME.multipartType(null)); + + assertEquals(ChecksumType.FULL_OBJECT, ChecksumAlgorithm.CRC32.multipartType(ChecksumType.FULL_OBJECT)); + assertEquals(ChecksumType.COMPOSITE, ChecksumAlgorithm.CRC32C.multipartType(ChecksumType.COMPOSITE)); + + AwsException shaFullObject = assertThrows(AwsException.class, + () -> ChecksumAlgorithm.SHA256.multipartType(ChecksumType.FULL_OBJECT)); + assertEquals("The FULL_OBJECT checksum type cannot be used with the sha256 checksum algorithm.", + shaFullObject.getMessage()); + AwsException crc64Composite = assertThrows(AwsException.class, + () -> ChecksumAlgorithm.CRC64NVME.multipartType(ChecksumType.COMPOSITE)); + assertEquals("The COMPOSITE checksum type cannot be used with the crc64nvme checksum algorithm.", + crc64Composite.getMessage()); + } + + @Test + void typeHeaderParsingIsCaseInsensitiveAndRejectsUnknownValues() { + assertEquals(ChecksumType.FULL_OBJECT, ChecksumAlgorithm.CRC32.multipartType(ChecksumType.fromWireValue("full_object"))); + assertEquals(ChecksumType.COMPOSITE, ChecksumType.fromWireValue("COMPOSITE")); + assertNull(ChecksumType.fromWireValue(null)); + AwsException unknown = assertThrows(AwsException.class, () -> ChecksumType.fromWireValue("PARTIAL")); + assertEquals("InvalidRequest", unknown.getErrorCode()); + assertEquals("Value for x-amz-checksum-type header is invalid.", unknown.getMessage()); + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java index 270c22f267..69451414ea 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3IntegrationTest.java @@ -106,6 +106,8 @@ class S3IntegrationTest { .then() .statusCode(200) .body(containsString("[0-9a-f]{32}.*")) .body(containsString("STANDARD_IA")) .body(containsString("20")) .body(containsString("")); @@ -217,6 +219,7 @@ class S3IntegrationTest { .header("x-amz-meta-owner", equalTo("team-b")) .header("x-amz-storage-class", equalTo("GLACIER")) .header("x-amz-checksum-sha256", notNullValue()) + .header("x-amz-checksum-type", equalTo("FULL_OBJECT")) .body(equalTo("Hello World from S3!")); // Verify GetObjectAttributes returns the overridden checksum algorithm diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartIntegrationTest.java index 3bd3b61db3..9771ef2acd 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartIntegrationTest.java @@ -25,6 +25,9 @@ class S3MultipartIntegrationTest { private static final String SSE_CUSTOMER_KEY_MD5 = customerKeyMd5(SSE_CUSTOMER_KEY); private static final String WRONG_SSE_CUSTOMER_KEY = Base64.getEncoder().encodeToString("abcdef0123456789abcdef0123456789".getBytes(StandardCharsets.UTF_8)); private static final String WRONG_SSE_CUSTOMER_KEY_MD5 = customerKeyMd5(WRONG_SSE_CUSTOMER_KEY); + private static final String PART_1 = "Part1Data-Hello"; + private static final String PART_2 = "Part2Data-World"; + private static final String COMPOSITE_SHA256 = compositeSha256(PART_1, PART_2); private static String uploadId; @Test @@ -60,24 +63,26 @@ class S3MultipartIntegrationTest { @Order(3) void uploadPart1() { given() - .body("Part1Data-Hello") + .body(PART_1) .when() .put("/" + BUCKET + "/" + KEY + "?uploadId=" + uploadId + "&partNumber=1") .then() .statusCode(200) - .header("ETag", notNullValue()); + .header("ETag", notNullValue()) + .header("x-amz-checksum-sha256", equalTo(S3Checksum.sha256Base64(PART_1.getBytes(StandardCharsets.UTF_8)))); } @Test @Order(4) void uploadPart2() { given() - .body("Part2Data-World") + .body(PART_2) .when() .put("/" + BUCKET + "/" + KEY + "?uploadId=" + uploadId + "&partNumber=2") .then() .statusCode(200) - .header("ETag", notNullValue()); + .header("ETag", notNullValue()) + .header("x-amz-checksum-sha256", equalTo(S3Checksum.sha256Base64(PART_2.getBytes(StandardCharsets.UTF_8)))); } @Test @@ -114,9 +119,9 @@ class S3MultipartIntegrationTest { void completeMultipartUpload() { String completeXml = """ - 1etag1 - 2etag2 - """; + 1etag1%s + 2etag2%s + """.formatted(sha256Base64(PART_1), sha256Base64(PART_2)); given() .contentType("application/xml") @@ -127,7 +132,9 @@ class S3MultipartIntegrationTest { .statusCode(200) .body(containsString("")) - .body(containsString("-2")); // Composite ETag ends with -2 + .body(containsString("-2")) // Composite ETag ends with -2 + .body(containsString("" + COMPOSITE_SHA256 + "")) + .body(containsString("COMPOSITE")); } @Test @@ -142,24 +149,38 @@ class S3MultipartIntegrationTest { .header("x-amz-server-side-encryption", equalTo("AES256")) .header("x-amz-meta-owner", equalTo("team-a")) .header("x-amz-storage-class", equalTo("STANDARD_IA")) - .body(equalTo("Part1Data-HelloPart2Data-World")); + .body(equalTo(PART_1 + PART_2)); + + given() + .header("x-amz-checksum-mode", "ENABLED") + .when() + .head("/" + BUCKET + "/" + KEY) + .then() + .statusCode(200) + .header("x-amz-checksum-sha256", equalTo(COMPOSITE_SHA256)) + .header("x-amz-checksum-type", equalTo("COMPOSITE")); } @Test @Order(10) void getMultipartObjectAttributes() { given() - .header("x-amz-object-attributes", "ObjectParts,Checksum,StorageClass") + .header("x-amz-object-attributes", "ETag,ObjectParts,Checksum,StorageClass") .header("x-amz-max-parts", 1) .when() .get("/" + BUCKET + "/" + KEY + "?attributes") .then() .statusCode(200) .body(containsString("[0-9a-f]{32}-2.*")) .body(containsString("STANDARD_IA")) .body(containsString("")) .body(containsString("2")) - .body(containsString("")); + // GetObjectAttributes reports the composite value without the "-N" suffix + .body(containsString("" + S3Checksum.withoutPartCount(COMPOSITE_SHA256) + "")) + .body(containsString("COMPOSITE")) + .body(containsString("" + S3Checksum.sha256Base64(PART_1.getBytes(StandardCharsets.UTF_8)) + + "")); } @Test @@ -564,6 +585,7 @@ class S3MultipartIntegrationTest { String key = "checksum-mismatch-multipart.bin"; String newUploadId = given() .header("x-amz-checksum-algorithm", "CRC32") + .header("x-amz-checksum-type", "FULL_OBJECT") .when() .post("/" + BUCKET + "/" + key + "?uploads") .then() @@ -610,10 +632,13 @@ class S3MultipartIntegrationTest { String newUploadId = given() .header("x-amz-checksum-algorithm", "CRC32") + .header("x-amz-checksum-type", "FULL_OBJECT") .when() .post("/" + BUCKET + "/" + key + "?uploads") .then() .statusCode(200) + .header("x-amz-checksum-algorithm", equalTo("CRC32")) + .header("x-amz-checksum-type", equalTo("FULL_OBJECT")) .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); given() @@ -659,16 +684,11 @@ class S3MultipartIntegrationTest { .then() .statusCode(200); - String completeXml = """ - - 1etag1 - """; - given() .contentType("application/xml") .header("x-amz-checksum-type", "FULL_OBJECT") .header("x-amz-checksum-sha256", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=") - .body(completeXml) + .body(singlePartCompleteXml("" + sha256Base64("Part1Data-Hello") + "")) .when() .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) .then() @@ -691,10 +711,13 @@ class S3MultipartIntegrationTest { String newUploadId = given() .header("x-amz-checksum-algorithm", "CRC32") + .header("x-amz-checksum-type", "FULL_OBJECT") .when() .post("/" + BUCKET + "/" + key + "?uploads") .then() .statusCode(200) + .header("x-amz-checksum-algorithm", equalTo("CRC32")) + .header("x-amz-checksum-type", equalTo("FULL_OBJECT")) .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); given() @@ -730,8 +753,417 @@ class S3MultipartIntegrationTest { @Test @Order(24) + void initiateMultipartUploadResolvesChecksumType() { + String newUploadId = given() + .header("x-amz-checksum-algorithm", "SHA256") + .when() + .post("/" + BUCKET + "/checksum-type-default.bin?uploads") + .then() + .statusCode(200) + .header("x-amz-checksum-algorithm", equalTo("SHA256")) + .header("x-amz-checksum-type", equalTo("COMPOSITE")) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + given().when().delete("/" + BUCKET + "/checksum-type-default.bin?uploadId=" + newUploadId).then().statusCode(204); + + given() + .header("x-amz-checksum-algorithm", "SHA256") + .header("x-amz-checksum-type", "FULL_OBJECT") + .when() + .post("/" + BUCKET + "/checksum-type-invalid.bin?uploads") + .then() + .statusCode(400) + .body(containsString("InvalidRequest")) + .body(containsString("The FULL_OBJECT checksum type cannot be used with the sha256 checksum algorithm.")); + + given() + .header("x-amz-checksum-algorithm", "CRC64NVME") + .header("x-amz-checksum-type", "COMPOSITE") + .when() + .post("/" + BUCKET + "/checksum-type-invalid.bin?uploads") + .then() + .statusCode(400) + .body(containsString("InvalidRequest")); + + // S3 validates the type header on its own, and only accepts it next to an algorithm + given() + .header("x-amz-checksum-type", "PARTIAL") + .when() + .post("/" + BUCKET + "/checksum-type-invalid.bin?uploads") + .then() + .statusCode(400) + .body(containsString("Value for x-amz-checksum-type header is invalid.")); + + given() + .header("x-amz-checksum-type", "FULL_OBJECT") + .when() + .post("/" + BUCKET + "/checksum-type-invalid.bin?uploads") + .then() + .statusCode(400) + .body(containsString("The x-amz-checksum-type header can only be used with the x-amz-checksum-algorithm header.")); + } + + @Test + @Order(25) + void completeMultipartUploadRejectsFullObjectTypeOnCompositeUpload() { + String key = "checksum-mode-mismatch.bin"; + String data = "Part1Data-Hello"; + String newUploadId = given() + .header("x-amz-checksum-algorithm", "CRC32") + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .header("x-amz-checksum-type", equalTo("COMPOSITE")) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + given() + .body(data) + .when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=1") + .then() + .statusCode(200); + + given() + .contentType("application/xml") + .header("x-amz-checksum-type", "FULL_OBJECT") + .header("x-amz-checksum-crc32", S3Checksum.crc32Base64(data.getBytes(StandardCharsets.UTF_8))) + .body(singlePartCompleteXml("" + S3Checksum.crc32Base64(data.getBytes(StandardCharsets.UTF_8)) + "")) + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(400) + .body(containsString("InvalidRequest")) + .body(containsString("The upload was created using the COMPOSITE checksum mode.")); + + given().when().delete("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId).then().statusCode(204); + } + + @Test + @Order(26) + void completeMultipartUploadRejectsMismatchedCompositeChecksum() { + String key = "composite-mismatch-multipart.bin"; + String newUploadId = given() + .header("x-amz-checksum-algorithm", "SHA256") + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + given() + .body("Part1Data-Hello") + .when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=1") + .then() + .statusCode(200); + + given() + .contentType("application/xml") + .header("x-amz-checksum-type", "COMPOSITE") + .header("x-amz-checksum-sha256", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=-1") + .body(singlePartCompleteXml("" + sha256Base64("Part1Data-Hello") + "")) + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(400) + .body(containsString("BadDigest")) + .body(containsString("The sha256 you specified did not match the calculated checksum.")); + + given().when().delete("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId).then().statusCode(204); + } + + @Test + @Order(27) + void completeMultipartUploadAcceptsMatchingCompositeChecksumAndPartChecksums() { + String key = "composite-match-multipart.bin"; + String newUploadId = given() + .header("x-amz-checksum-algorithm", "SHA256") + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + String part1Sha256 = S3Checksum.sha256Base64(PART_1.getBytes(StandardCharsets.UTF_8)); + String part2Sha256 = S3Checksum.sha256Base64(PART_2.getBytes(StandardCharsets.UTF_8)); + given() + .header("x-amz-checksum-sha256", part1Sha256) + .body(PART_1) + .when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=1") + .then() + .statusCode(200); + given() + .header("x-amz-checksum-sha256", part2Sha256) + .body(PART_2) + .when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=2") + .then() + .statusCode(200); + + String completeXml = """ + + %setag11 + %setag22 + """.formatted(part1Sha256, part2Sha256); + + given() + .contentType("application/xml") + .header("x-amz-checksum-type", "COMPOSITE") + .header("x-amz-checksum-sha256", COMPOSITE_SHA256) + .body(completeXml) + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(200) + .body(containsString("" + COMPOSITE_SHA256 + "")) + .body(containsString("COMPOSITE")); + + given() + .header("x-amz-checksum-mode", "ENABLED") + .when() + .get("/" + BUCKET + "/" + key) + .then() + .statusCode(200) + .header("x-amz-checksum-sha256", equalTo(COMPOSITE_SHA256)) + .header("x-amz-checksum-type", equalTo("COMPOSITE")); + } + + @Test + @Order(28) + void completeMultipartUploadRejectsMismatchedPartChecksum() { + String key = "bad-part-checksum-multipart.bin"; + String newUploadId = given() + .header("x-amz-checksum-algorithm", "SHA256") + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + given() + .body("Part1Data-Hello") + .when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=1") + .then() + .statusCode(200); + + String completeXml = """ + + 1etag1 + AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= + """; + + given() + .contentType("application/xml") + .body(completeXml) + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(400) + .body(containsString("InvalidPart")); + + given().when().delete("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId).then().statusCode(204); + } + + @Test + @Order(29) + void completeMultipartUploadWithCrc64NvmeReportsFullObjectChecksum() { + String key = "crc64-multipart.bin"; + String newUploadId = given() + .header("x-amz-checksum-algorithm", "CRC64NVME") + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .header("x-amz-checksum-type", equalTo("FULL_OBJECT")) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + given().body(PART_1).when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=1") + .then().statusCode(200); + given().body(PART_2).when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=2") + .then().statusCode(200); + + String fullObjectCrc64 = S3Checksum.crc64NvmeBase64((PART_1 + PART_2).getBytes(StandardCharsets.UTF_8)); + given() + .contentType("application/xml") + .body(""" + + 1etag1 + 2etag2 + """) + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(200) + .body(containsString("" + fullObjectCrc64 + "")) + .body(containsString("FULL_OBJECT")); + + given() + .header("x-amz-checksum-mode", "ENABLED") + .when() + .head("/" + BUCKET + "/" + key) + .then() + .statusCode(200) + .header("x-amz-checksum-crc64nvme", equalTo(fullObjectCrc64)) + .header("x-amz-checksum-type", equalTo("FULL_OBJECT")); + } + + @Test + @Order(30) + void copyOfMultipartObjectReportsFullObjectChecksum() { + given() + .header("x-amz-copy-source", "/" + BUCKET + "/" + KEY) + .when() + .put("/" + BUCKET + "/composite-copy.bin") + .then() + .statusCode(200) + .body(containsString("CopyObjectResult")) + .body(containsString("" + S3Checksum.sha256Base64((PART_1 + PART_2).getBytes(StandardCharsets.UTF_8)) + + "")) + .body(containsString("FULL_OBJECT")); + + given() + .header("x-amz-checksum-mode", "ENABLED") + .when() + .head("/" + BUCKET + "/composite-copy.bin") + .then() + .statusCode(200) + .header("x-amz-checksum-sha256", equalTo(S3Checksum.sha256Base64((PART_1 + PART_2).getBytes(StandardCharsets.UTF_8)))) + .header("x-amz-checksum-type", equalTo("FULL_OBJECT")); + + given() + .header("x-amz-object-attributes", "ObjectParts,Checksum") + .when() + .get("/" + BUCKET + "/composite-copy.bin?attributes") + .then() + .statusCode(200) + .body(containsString("FULL_OBJECT")) + .body(not(containsString(""))); + } + + @Test + @Order(31) + void completeMultipartUploadRejectsNonNumericPartNumber() { + String key = "malformed-complete.bin"; + String newUploadId = given() + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + given() + .contentType("application/xml") + .body("oneetag1") + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(400) + .body(containsString("MalformedXML")); + + given().when().delete("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId).then().statusCode(204); + } + + @Test + @Order(32) + void uploadPartEchoesNoChecksumWhenTheUploadDeclaredNoAlgorithm() { + String key = "no-algorithm-part.bin"; + String newUploadId = given() + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .header("x-amz-checksum-algorithm", nullValue()) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + given() + .body(PART_1) + .when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=1") + .then() + .statusCode(200) + .header("ETag", notNullValue()) + .header("x-amz-checksum-crc64nvme", nullValue()) + .header("x-amz-checksum-sha256", nullValue()); + + given().when().delete("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId).then().statusCode(204); + } + + @Test + @Order(33) + void completeMultipartUploadRequiresPartChecksumsOnCompositeUploads() { + String key = "missing-part-checksums.bin"; + String newUploadId = given() + .header("x-amz-checksum-algorithm", "SHA256") + .when() + .post("/" + BUCKET + "/" + key + "?uploads") + .then() + .statusCode(200) + .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId"); + + given() + .body(PART_1) + .when() + .put("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId + "&partNumber=1") + .then() + .statusCode(200); + + given() + .contentType("application/xml") + .body(singlePartCompleteXml("")) + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(400) + .body(containsString("InvalidRequest")) + .body(containsString("The upload was created using a sha256 checksum. The complete request must include " + + "the checksum for each part. It was missing for part 1 in the request.")); + + given() + .contentType("application/xml") + .body(singlePartCompleteXml("" + S3Checksum.crc32Base64(PART_1.getBytes(StandardCharsets.UTF_8)) + "")) + .when() + .post("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId) + .then() + .statusCode(400) + .body(containsString("BadDigest")) + .body(containsString("The crc32 you specified for part 1 did not match what we received.")); + + given().when().delete("/" + BUCKET + "/" + key + "?uploadId=" + newUploadId).then().statusCode(204); + } + + @Test + @Order(34) + void copyOfMultipartObjectGetsItsOwnEtag() { + given() + .header("x-amz-copy-source", "/" + BUCKET + "/" + KEY) + .when() + .put("/" + BUCKET + "/copy-of-multipart.bin") + .then() + .statusCode(200) + .contentType("application/xml") + // the copy is a single object: a plain MD5 ETag, not the "-2" of the multipart source + .body(matchesPattern("(?s).*"[0-9a-f]{32}".*")); + + given() + .when() + .head("/" + BUCKET + "/copy-of-multipart.bin") + .then() + .statusCode(200) + .header("ETag", matchesPattern("\"[0-9a-f]{32}\"")); + } + + @Test + @Order(40) void cleanUp() { + given().when().delete("/" + BUCKET + "/copy-of-multipart.bin").then().statusCode(204); given().when().delete("/" + BUCKET + "/" + KEY).then().statusCode(204); + given().when().delete("/" + BUCKET + "/composite-match-multipart.bin").then().statusCode(204); + given().when().delete("/" + BUCKET + "/crc64-multipart.bin").then().statusCode(204); + given().when().delete("/" + BUCKET + "/composite-copy.bin").then().statusCode(204); given().when().delete("/" + BUCKET + "/tagged-multipart.bin").then().statusCode(204); given().when().delete("/" + BUCKET + "/source-for-copy.bin").then().statusCode(204); given().when().delete("/" + BUCKET + "/copy-dest.bin").then().statusCode(204); @@ -742,6 +1174,30 @@ class S3MultipartIntegrationTest { given().when().delete("/" + BUCKET).then().statusCode(204); } + private static String singlePartCompleteXml(String checksumElement) { + return """ + + 1etag1%s + """.formatted(checksumElement); + } + + private static String sha256Base64(String data) { + return S3Checksum.sha256Base64(data.getBytes(StandardCharsets.UTF_8)); + } + + private static String compositeSha256(String... parts) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + MessageDigest composite = MessageDigest.getInstance("SHA-256"); + for (String part : parts) { + composite.update(digest.digest(part.getBytes(StandardCharsets.UTF_8))); + } + return Base64.getEncoder().encodeToString(composite.digest()) + "-" + parts.length; + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException("SHA-256 is not available", e); + } + } + private static String customerKeyMd5(String customerKey) { try { byte[] md5 = MessageDigest.getInstance("MD5").digest(Base64.getDecoder().decode(customerKey)); diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartServiceTest.java index 43c87124e6..25df685009 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3MultipartServiceTest.java @@ -2,9 +2,12 @@ package io.github.hectorvent.floci.services.s3; import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.storage.InMemoryStorage; +import io.github.hectorvent.floci.services.s3.model.ChecksumAlgorithm; +import io.github.hectorvent.floci.services.s3.model.ChecksumType; import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesResult; import io.github.hectorvent.floci.services.s3.model.MultipartUpload; import io.github.hectorvent.floci.services.s3.model.ObjectAttributeName; +import io.github.hectorvent.floci.services.s3.model.S3Checksum; import io.github.hectorvent.floci.services.s3.model.S3Object; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -12,6 +15,10 @@ import org.junit.jupiter.api.io.TempDir; import java.nio.charset.StandardCharsets; import java.nio.file.Path; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Base64; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; @@ -91,7 +98,10 @@ class S3MultipartServiceTest { assertEquals("part1part2", new String(fetched.getData())); // Composite ETag should end with -2 (number of parts) assertTrue(result.getETag().endsWith("-2\""), "ETag should be composite: " + result.getETag()); - assertEquals("COMPOSITE", result.getChecksum().getChecksumType()); + // Without a checksum algorithm AWS attaches the default CRC64NVME full-object checksum + assertEquals(ChecksumType.FULL_OBJECT, result.getChecksum().getChecksumType()); + assertEquals(S3Checksum.crc64NvmeBase64("part1part2".getBytes(StandardCharsets.UTF_8)), + result.getChecksum().getChecksumCRC64NVME()); } @Test @@ -181,22 +191,284 @@ class S3MultipartServiceTest { @Test void getObjectAttributesReturnsMultipartParts() { - MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "parts.bin", "application/octet-stream"); + MultipartUpload upload = initiate("parts.bin", "SHA256", null); s3Service.uploadPart("test-bucket", "parts.bin", upload.getUploadId(), 1, "abc".getBytes(StandardCharsets.UTF_8)); s3Service.uploadPart("test-bucket", "parts.bin", upload.getUploadId(), 2, "def".getBytes(StandardCharsets.UTF_8)); - s3Service.completeMultipartUpload("test-bucket", "parts.bin", upload.getUploadId(), List.of(1, 2), null, null); + s3Service.completeMultipartUpload("test-bucket", "parts.bin", upload.getUploadId(), List.of(1, 2), + partChecksums(ChecksumAlgorithm.SHA256, "abc".getBytes(StandardCharsets.UTF_8), "def".getBytes(StandardCharsets.UTF_8)), null, null); GetObjectAttributesResult attributes = s3Service.getObjectAttributes("test-bucket", "parts.bin", null, Set.of(ObjectAttributeName.OBJECT_PARTS, ObjectAttributeName.CHECKSUM), 1, 0); assertNotNull(attributes.getChecksum()); - assertEquals("COMPOSITE", attributes.getChecksum().getChecksumType()); + assertEquals(ChecksumType.COMPOSITE, attributes.getChecksum().getChecksumType()); assertNotNull(attributes.getObjectParts()); + assertTrue(attributes.getObjectParts().isPartChecksumsAvailable()); assertEquals(2, attributes.getObjectParts().getPartsCount()); assertEquals(1, attributes.getObjectParts().getParts().size()); assertTrue(attributes.getObjectParts().isTruncated()); assertEquals(1, attributes.getObjectParts().getNextPartNumberMarker()); - assertNotNull(attributes.getObjectParts().getParts().get(0).getChecksum().getChecksumCRC64NVME()); + assertEquals(S3Checksum.sha256Base64("abc".getBytes(StandardCharsets.UTF_8)), + attributes.getObjectParts().getParts().get(0).getChecksum().getChecksumSHA256()); + } + + @Test + void getObjectAttributesReportsOnlyThePartCountForFullObjectChecksums() { + MultipartUpload upload = s3Service.initiateMultipartUpload("test-bucket", "full-parts.bin", "application/octet-stream"); + s3Service.uploadPart("test-bucket", "full-parts.bin", upload.getUploadId(), 1, "abc".getBytes(StandardCharsets.UTF_8)); + s3Service.uploadPart("test-bucket", "full-parts.bin", upload.getUploadId(), 2, "def".getBytes(StandardCharsets.UTF_8)); + s3Service.completeMultipartUpload("test-bucket", "full-parts.bin", upload.getUploadId(), List.of(1, 2), null, null); + + GetObjectAttributesResult attributes = s3Service.getObjectAttributes("test-bucket", "full-parts.bin", null, + Set.of(ObjectAttributeName.OBJECT_PARTS, ObjectAttributeName.CHECKSUM), null, null); + + assertEquals(ChecksumType.FULL_OBJECT, attributes.getChecksum().getChecksumType()); + assertEquals(2, attributes.getObjectParts().getPartsCount()); + assertFalse(attributes.getObjectParts().isPartChecksumsAvailable()); + assertTrue(attributes.getObjectParts().getParts().isEmpty()); + } + + @Test + void getObjectAttributesOmitsObjectPartsForSinglePartObjects() { + s3Service.putObject("test-bucket", "single.txt", "hello".getBytes(StandardCharsets.UTF_8), "text/plain", null); + + GetObjectAttributesResult attributes = s3Service.getObjectAttributes("test-bucket", "single.txt", null, + Set.of(ObjectAttributeName.OBJECT_PARTS, ObjectAttributeName.CHECKSUM), null, null); + + assertEquals(ChecksumType.FULL_OBJECT, attributes.getChecksum().getChecksumType()); + assertNull(attributes.getObjectParts()); + } + + @Test + void completeMultipartUploadReturnsCompositeSha256Checksum() { + byte[] part1 = "Part1Data-Hello".getBytes(StandardCharsets.UTF_8); + byte[] part2 = "Part2Data-World".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("sha256.bin", "SHA256", null); + s3Service.uploadPart("test-bucket", "sha256.bin", upload.getUploadId(), 1, part1); + s3Service.uploadPart("test-bucket", "sha256.bin", upload.getUploadId(), 2, part2); + + S3Object result = s3Service.completeMultipartUpload("test-bucket", "sha256.bin", + upload.getUploadId(), List.of(1, 2), partChecksums(ChecksumAlgorithm.SHA256, part1, part2), null, null); + + String expected = compositeSha256(part1, part2); + assertTrue(expected.endsWith("-2")); + assertEquals(expected, result.getChecksum().getChecksumSHA256()); + assertEquals(ChecksumType.COMPOSITE, result.getChecksum().getChecksumType()); + assertEquals(S3Checksum.sha256Base64(part1), result.getParts().get(0).getChecksum().getChecksumSHA256()); + assertEquals(S3Checksum.sha256Base64(part2), result.getParts().get(1).getChecksum().getChecksumSHA256()); + + S3Object head = s3Service.getObjectMetadata("test-bucket", "sha256.bin", null); + assertEquals(expected, head.getChecksum().getChecksumSHA256()); + + GetObjectAttributesResult attributes = s3Service.getObjectAttributes("test-bucket", "sha256.bin", null, + Set.of(ObjectAttributeName.CHECKSUM), null, null); + assertEquals(S3Checksum.withoutPartCount(expected), attributes.getChecksum().getChecksumSHA256()); + assertEquals(ChecksumType.COMPOSITE, attributes.getChecksum().getChecksumType()); + } + + @Test + void singlePartMultipartUploadStillReturnsCompositeChecksum() { + byte[] data = "only-part".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("single.bin", "SHA256", null); + s3Service.uploadPart("test-bucket", "single.bin", upload.getUploadId(), 1, data); + + S3Object result = s3Service.completeMultipartUpload("test-bucket", "single.bin", + upload.getUploadId(), List.of(1), partChecksums(ChecksumAlgorithm.SHA256, data), null, null); + + assertEquals(compositeSha256(data), result.getChecksum().getChecksumSHA256()); + assertTrue(result.getChecksum().getChecksumSHA256().endsWith("-1")); + assertEquals(ChecksumType.COMPOSITE, result.getChecksum().getChecksumType()); + } + + @Test + void completeMultipartUploadReturnsCompositeCrc32Checksum() { + byte[] part1 = "crc-part-1".getBytes(StandardCharsets.UTF_8); + byte[] part2 = "crc-part-2".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("crc32.bin", "CRC32", null); + s3Service.uploadPart("test-bucket", "crc32.bin", upload.getUploadId(), 1, part1); + s3Service.uploadPart("test-bucket", "crc32.bin", upload.getUploadId(), 2, part2); + + S3Object result = s3Service.completeMultipartUpload("test-bucket", "crc32.bin", + upload.getUploadId(), List.of(1, 2), partChecksums(ChecksumAlgorithm.CRC32, part1, part2), null, null); + + byte[] partChecksums = concat(Base64.getDecoder().decode(S3Checksum.crc32Base64(part1)), + Base64.getDecoder().decode(S3Checksum.crc32Base64(part2))); + assertEquals(S3Checksum.crc32Base64(partChecksums) + "-2", result.getChecksum().getChecksumCRC32()); + assertEquals(ChecksumType.COMPOSITE, result.getChecksum().getChecksumType()); + } + + @Test + void completeMultipartUploadKeepsCrc64NvmeAsFullObjectChecksum() { + byte[] part1 = "crc64-part-1".getBytes(StandardCharsets.UTF_8); + byte[] part2 = "crc64-part-2".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("crc64.bin", "CRC64NVME", null); + assertEquals(ChecksumType.FULL_OBJECT, upload.getChecksumType()); + s3Service.uploadPart("test-bucket", "crc64.bin", upload.getUploadId(), 1, part1); + s3Service.uploadPart("test-bucket", "crc64.bin", upload.getUploadId(), 2, part2); + + S3Object result = s3Service.completeMultipartUpload("test-bucket", "crc64.bin", + upload.getUploadId(), List.of(1, 2), null, null); + + assertEquals(S3Checksum.crc64NvmeBase64(concat(part1, part2)), result.getChecksum().getChecksumCRC64NVME()); + assertEquals(ChecksumType.FULL_OBJECT, result.getChecksum().getChecksumType()); + } + + @Test + void completeMultipartUploadHonorsFullObjectTypeRequestedAtInitiation() { + byte[] part1 = "full-part-1".getBytes(StandardCharsets.UTF_8); + byte[] part2 = "full-part-2".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("crc32-full.bin", "CRC32", "FULL_OBJECT"); + s3Service.uploadPart("test-bucket", "crc32-full.bin", upload.getUploadId(), 1, part1); + s3Service.uploadPart("test-bucket", "crc32-full.bin", upload.getUploadId(), 2, part2); + + S3Object result = s3Service.completeMultipartUpload("test-bucket", "crc32-full.bin", + upload.getUploadId(), List.of(1, 2), null, null); + + assertEquals(S3Checksum.crc32Base64(concat(part1, part2)), result.getChecksum().getChecksumCRC32()); + assertEquals(ChecksumType.FULL_OBJECT, result.getChecksum().getChecksumType()); + } + + @Test + void initiateMultipartUploadRejectsIncompatibleChecksumType() { + AwsException sha = assertThrows(AwsException.class, () -> initiate("bad-sha.bin", "SHA256", "FULL_OBJECT")); + assertEquals("InvalidRequest", sha.getErrorCode()); + AwsException crc64 = assertThrows(AwsException.class, () -> initiate("bad-crc64.bin", "CRC64NVME", "COMPOSITE")); + assertEquals("InvalidRequest", crc64.getErrorCode()); + assertEquals(ChecksumType.COMPOSITE, initiate("crc32c.bin", "CRC32C", null).getChecksumType()); + assertNull(initiate("no-algorithm.bin", null, null).getChecksumType()); + + AwsException typeAlone = assertThrows(AwsException.class, () -> initiate("type-alone.bin", null, "FULL_OBJECT")); + assertEquals("InvalidRequest", typeAlone.getErrorCode()); + assertEquals("The x-amz-checksum-type header can only be used with the x-amz-checksum-algorithm header.", + typeAlone.getMessage()); + AwsException unknownType = assertThrows(AwsException.class, () -> initiate("unknown-type.bin", null, "PARTIAL")); + assertEquals("InvalidRequest", unknownType.getErrorCode()); + assertEquals("Value for x-amz-checksum-type header is invalid.", unknownType.getMessage()); + } + + @Test + void completeMultipartUploadValidatesClientCompositeChecksum() { + byte[] part1 = "Part1Data-Hello".getBytes(StandardCharsets.UTF_8); + byte[] part2 = "Part2Data-World".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("validated.bin", "SHA256", null); + s3Service.uploadPart("test-bucket", "validated.bin", upload.getUploadId(), 1, part1); + s3Service.uploadPart("test-bucket", "validated.bin", upload.getUploadId(), 2, part2); + String composite = compositeSha256(part1, part2); + + S3Checksum wrong = new S3Checksum(); + wrong.setChecksumSHA256("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=-2"); + AwsException mismatch = assertThrows(AwsException.class, () -> s3Service.completeMultipartUpload( + "test-bucket", "validated.bin", upload.getUploadId(), List.of(1, 2), partChecksums(ChecksumAlgorithm.SHA256, part1, part2), "COMPOSITE", wrong)); + assertEquals("BadDigest", mismatch.getErrorCode()); + + S3Checksum wrongPartCount = new S3Checksum(); + wrongPartCount.setChecksumSHA256(S3Checksum.withoutPartCount(composite) + "-5"); + assertEquals("BadDigest", assertThrows(AwsException.class, () -> s3Service.completeMultipartUpload( + "test-bucket", "validated.bin", upload.getUploadId(), List.of(1, 2), partChecksums(ChecksumAlgorithm.SHA256, part1, part2), null, wrongPartCount)).getErrorCode()); + + S3Checksum withoutSuffix = new S3Checksum(); + withoutSuffix.setChecksumSHA256(S3Checksum.withoutPartCount(composite)); + S3Object result = s3Service.completeMultipartUpload("test-bucket", "validated.bin", + upload.getUploadId(), List.of(1, 2), partChecksums(ChecksumAlgorithm.SHA256, part1, part2), "COMPOSITE", withoutSuffix); + assertEquals(composite, result.getChecksum().getChecksumSHA256()); + } + + @Test + void completeMultipartUploadRejectsChecksumTypeDifferentFromInitiation() { + byte[] data = "crc-data".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("crc32-mode.bin", "CRC32", null); + s3Service.uploadPart("test-bucket", "crc32-mode.bin", upload.getUploadId(), 1, data); + S3Checksum fullObject = new S3Checksum(); + fullObject.setChecksumCRC32(S3Checksum.crc32Base64(data)); + + AwsException error = assertThrows(AwsException.class, () -> s3Service.completeMultipartUpload( + "test-bucket", "crc32-mode.bin", upload.getUploadId(), List.of(1), partChecksums(ChecksumAlgorithm.CRC32, data), "FULL_OBJECT", fullObject)); + + assertEquals("InvalidRequest", error.getErrorCode()); + assertTrue(error.getMessage().contains("COMPOSITE checksum mode"), error.getMessage()); + } + + @Test + void completeMultipartUploadRejectsMismatchedPartChecksum() { + byte[] data = "part-data".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("bad-part.bin", "SHA256", null); + s3Service.uploadPart("test-bucket", "bad-part.bin", upload.getUploadId(), 1, data); + S3Checksum wrongPart = new S3Checksum(); + wrongPart.setChecksumSHA256("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="); + + AwsException error = assertThrows(AwsException.class, () -> s3Service.completeMultipartUpload( + "test-bucket", "bad-part.bin", upload.getUploadId(), List.of(1), Map.of(1, wrongPart), null, null)); + assertEquals("InvalidPart", error.getErrorCode()); + + S3Checksum rightPart = new S3Checksum(); + rightPart.setChecksumSHA256(S3Checksum.sha256Base64(data)); + S3Object result = s3Service.completeMultipartUpload("test-bucket", "bad-part.bin", + upload.getUploadId(), List.of(1), Map.of(1, rightPart), null, null); + assertEquals(compositeSha256(data), result.getChecksum().getChecksumSHA256()); + } + + @Test + void completeMultipartUploadRequiresEveryPartChecksumOnCompositeUploads() { + byte[] part1 = "Part1Data-Hello".getBytes(StandardCharsets.UTF_8); + byte[] part2 = "Part2Data-World".getBytes(StandardCharsets.UTF_8); + MultipartUpload upload = initiate("strict.bin", "SHA256", null); + s3Service.uploadPart("test-bucket", "strict.bin", upload.getUploadId(), 1, part1); + s3Service.uploadPart("test-bucket", "strict.bin", upload.getUploadId(), 2, part2); + + AwsException none = assertThrows(AwsException.class, () -> s3Service.completeMultipartUpload( + "test-bucket", "strict.bin", upload.getUploadId(), List.of(1, 2), null, null)); + assertEquals("InvalidRequest", none.getErrorCode()); + assertEquals("The upload was created using a sha256 checksum. The complete request must include the checksum " + + "for each part. It was missing for part 1 in the request.", none.getMessage()); + + AwsException second = assertThrows(AwsException.class, () -> s3Service.completeMultipartUpload( + "test-bucket", "strict.bin", upload.getUploadId(), List.of(1, 2), partChecksums(ChecksumAlgorithm.SHA256, part1), null, null)); + assertTrue(second.getMessage().endsWith("It was missing for part 2 in the request."), second.getMessage()); + + S3Checksum otherAlgorithm = new S3Checksum(); + otherAlgorithm.setChecksumCRC32(S3Checksum.crc32Base64(part1)); + AwsException other = assertThrows(AwsException.class, () -> s3Service.completeMultipartUpload( + "test-bucket", "strict.bin", upload.getUploadId(), List.of(1, 2), + Map.of(1, otherAlgorithm, 2, S3Checksum.of(ChecksumAlgorithm.SHA256, part2)), null, null)); + assertEquals("BadDigest", other.getErrorCode()); + assertEquals("The crc32 you specified for part 1 did not match what we received.", other.getMessage()); + + S3Object result = s3Service.completeMultipartUpload("test-bucket", "strict.bin", upload.getUploadId(), + List.of(1, 2), partChecksums(ChecksumAlgorithm.SHA256, part1, part2), null, null); + assertEquals(compositeSha256(part1, part2), result.getChecksum().getChecksumSHA256()); + } + + private static Map partChecksums(ChecksumAlgorithm algorithm, byte[]... parts) { + Map checksums = new HashMap<>(); + for (int i = 0; i < parts.length; i++) { + checksums.put(i + 1, S3Checksum.of(algorithm, parts[i])); + } + return checksums; + } + + private MultipartUpload initiate(String key, String checksumAlgorithm, String checksumType) { + return s3Service.initiateMultipartUpload("test-bucket", key, null, null, null, null, null, null, + null, null, null, checksumAlgorithm, checksumType, null); + } + + private static String compositeSha256(byte[]... parts) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + MessageDigest composite = MessageDigest.getInstance("SHA-256"); + for (byte[] part : parts) { + composite.update(digest.digest(part)); + } + return Base64.getEncoder().encodeToString(composite.digest()) + "-" + parts.length; + } catch (NoSuchAlgorithmException e) { + throw new IllegalStateException(e); + } + } + + private static byte[] concat(byte[] first, byte[] second) { + byte[] result = new byte[first.length + second.length]; + System.arraycopy(first, 0, result, 0, first.length); + System.arraycopy(second, 0, result, first.length, second.length); + return result; } } diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java index 6a97f097a3..77d3be2145 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java @@ -4,6 +4,7 @@ import io.github.hectorvent.floci.core.common.AwsException; import io.github.hectorvent.floci.core.common.RegionResolver; import io.github.hectorvent.floci.core.storage.InMemoryStorage; import io.github.hectorvent.floci.services.lambda.model.InvocationType; +import io.github.hectorvent.floci.services.s3.model.ChecksumType; import io.github.hectorvent.floci.services.s3.model.FilterRule; import io.github.hectorvent.floci.services.s3.model.GetObjectAttributesResult; import io.github.hectorvent.floci.services.s3.model.LambdaNotification; @@ -19,6 +20,9 @@ import org.junit.jupiter.api.io.TempDir; import java.nio.charset.StandardCharsets; import java.nio.file.Files; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HexFormat; import java.nio.file.Path; import java.util.List; import java.util.Map; @@ -396,7 +400,7 @@ class S3ServiceTest { assertEquals("team-a", head.getMetadata().get("owner")); assertNotNull(head.getChecksum()); assertNotNull(head.getChecksum().getChecksumCRC64NVME()); - assertEquals("FULL_OBJECT", head.getChecksum().getChecksumType()); + assertEquals(ChecksumType.FULL_OBJECT, head.getChecksum().getChecksumType()); assertEquals(stored.getETag(), head.getETag()); } @@ -480,6 +484,29 @@ class S3ServiceTest { assertEquals("dest", copy.getMetadata().get("owner")); } + @Test + void copyOfMultipartObjectGetsTheEtagOfTheWholeContent() throws NoSuchAlgorithmException { + s3Service.createBucket("test-bucket", "us-east-1"); + byte[] part1 = "Part1Data-Hello".getBytes(StandardCharsets.UTF_8); + byte[] part2 = "Part2Data-World".getBytes(StandardCharsets.UTF_8); + var upload = s3Service.initiateMultipartUpload("test-bucket", "multipart.bin", "application/octet-stream"); + s3Service.uploadPart("test-bucket", "multipart.bin", upload.getUploadId(), 1, part1); + s3Service.uploadPart("test-bucket", "multipart.bin", upload.getUploadId(), 2, part2); + S3Object source = s3Service.completeMultipartUpload("test-bucket", "multipart.bin", upload.getUploadId(), + List.of(1, 2), null, null); + assertTrue(source.getETag().endsWith("-2\""), source.getETag()); + + S3Object copy = s3Service.copyObject("test-bucket", "multipart.bin", "test-bucket", "multipart-copy.bin"); + + byte[] whole = new byte[part1.length + part2.length]; + System.arraycopy(part1, 0, whole, 0, part1.length); + System.arraycopy(part2, 0, whole, part1.length, part2.length); + String expected = "\"" + HexFormat.of().formatHex(MessageDigest.getInstance("MD5").digest(whole)) + "\""; + assertEquals(expected, copy.getETag()); + assertNotEquals(source.getETag(), copy.getETag()); + assertEquals(expected, s3Service.getObject("test-bucket", "multipart-copy.bin").getETag()); + } + @Test void copyObjectWithNonASCIIKey() { s3Service.createBucket("test-bucket", "us-east-1");