mirror of
https://github.com/floci-io/floci.git
synced 2026-12-03 10:17:48 -05:00
* fix(s3): return composite checksums for multipart uploads CompleteMultipartUpload stored the checksum of the whole object but labelled it COMPOSITE, so clients that recompute the composite value from the part checksums, as the AWS documentation describes, never matched it. Follow the AWS checksum type rules, verified against real S3: - SHA1/SHA256 are always COMPOSITE, CRC32/CRC32C default to COMPOSITE and CRC64NVME is always FULL_OBJECT. x-amz-checksum-type on CreateMultipartUpload selects FULL_OBJECT for CRC32/CRC32C; incompatible combinations fail with InvalidRequest, and the response echoes x-amz-checksum-algorithm/-type. - The composite value is the algorithm applied to the concatenated binary part checksums, Base64 encoded, with a "-<part count>" suffix. It is returned by CompleteMultipartUpload, HeadObject and GetObject (with x-amz-checksum-type), while GetObjectAttributes omits the suffix, as AWS does. - A checksum sent on CompleteMultipartUpload is validated against the stored type: a mismatching value is a BadDigest (the composite is accepted with or without its suffix), a checksum type different from the one the upload was created with is an InvalidRequest, per-part checksums in the request body that do not match the uploaded parts are an InvalidPart, and a COMPOSITE upload completed without the checksum of every part is an InvalidRequest (FULL_OBJECT uploads need none, as on S3). A non-numeric PartNumber is a MalformedXML instead of a 500. - UploadPart echoes the part checksum (x-amz-checksum-<algorithm>) when the upload declared an algorithm, as S3 does; without one no header is returned. - CopyObject writes a single object without a part manifest; a composite source gets a full-object checksum recomputed with its algorithm, and CopyObjectResult carries the checksum elements, matching AWS. - GetObjectAttributes lists part-level checksums only for COMPOSITE objects: a FULL_OBJECT multipart object reports its PartsCount alone and a single-part object has no ObjectParts element. The algorithm and type rules live in two new enums, ChecksumAlgorithm and ChecksumType, parsed once from the request headers; S3Checksum builds the full-object, composite and GetObjectAttributes views of a checksum. The boto3 compatibility suite gains multipart upload_file cases for SHA256 and for the SDK's default CRC32, asserting the composite value and the part list. The S3 docs drop the stale note that checksum responses focus on SHA-1 and SHA-256 (CRC32, CRC32C and CRC64NVME have been supported since #877) and list the AWS algorithms Floci rejects. * fix(s3): return the GetObjectAttributes ETag without quotes S3 returns the ETag element of GetObjectAttributes without the surrounding quotes that HeadObject, ListParts and CompleteMultipartUpload keep. Verified against real S3 with the same object: head_object gives "af3c...-3" while get_object_attributes gives af3c...-3, and the AWS CLI reference shows the same in its get-object-attributes example. Floci echoed the quoted value, so a client comparing both saw different strings on Floci and equal ones nowhere. * fix(s3): give a copied object its own ETag CopyObject kept the ETag of the source, so the copy of a multipart object carried the "<md5-of-md5s>-N" value of its parts. S3 writes a copy as a single object and returns the MD5 of the whole content as its ETag, in CopyObjectResult and HeadObject alike (verified against real S3: source "af3c...-3", copy "a5f04f..."). The copy now keeps the ETag storeObject computes. * fix(s3): send CopyObjectResult as application/xml The CopyObject response carried Content-Type: text/plain;charset=UTF-8 for an XML body. S3 labels it application/xml like every other XML response. * test(s3): cover multipart checksums in every SDK compatibility suite Each SDK implements flexible checksums differently, so the multipart flows are exercised per client rather than once: the Go transfer manager (what terraform-provider-aws uses), @aws-sdk/lib-storage for Node, the Java SDK v2 both low-level and through S3TransferManager on the multipart-enabled async client, the AWS CLI (s3api, aws s3 cp --checksum-algorithm and a plain aws s3 cp that goes multipart on its own) and boto3. Every case asserts the composite or full-object value computed in the test itself, the UploadPart echo, the suffix-less GetObjectAttributes checksum and unquoted ETag, the rejected Complete without part checksums, and the copy of a multipart object as a single full object with its own ETag. The default algorithm cases accept whatever the SDK version declares (CRC32 composite or full object, or none) and check the stored value against it. * test(terraform): upload a large aws_s3_object with Terraform and OpenTofu The IaC suites created buckets but never an object, so the code path that surfaced the composite checksum bug, an aws_s3_object above the provider's part size uploaded through the SDK transfer manager, was not covered. Both suites now upload a 12 MiB file generated by the test setup with checksum_algorithm SHA256 and check that HeadObject reports a COMPOSITE checksum equal to the composite computed locally over the part sizes GetObjectAttributes lists, that the state attribute holds the same value, and that re-planning the object shows no drift. compat-opentofu moves to the same aws-cli image as compat-terraform (2.34.32): 2.15 predates the S3 checksum type and cannot show ChecksumType in its output. * fix(s3): reject x-amz-checksum-type without a checksum algorithm CreateMultipartUpload only parsed x-amz-checksum-type when an algorithm was declared, so a type sent on its own, valid or not, was silently ignored. S3 validates the header regardless: an unknown value is InvalidRequest "Value for x-amz-checksum-type header is invalid." and a valid one without an algorithm is InvalidRequest "The x-amz-checksum-type header can only be used with the x-amz-checksum-algorithm header." (both verified against real S3). * test(s3): log cleanup failures in the multipart checksum compat tests The Java, Node and Go cases swallowed errors while deleting their objects and bucket. They now report what could not be deleted and why, so a leftover is diagnosable instead of silent. --------- Co-authored-by: Mihai Blidaru <mihai.blidaru@lynxfctech.com>
185 lines
6.7 KiB
TypeScript
185 lines
6.7 KiB
TypeScript
/**
|
|
* 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 "-<parts>"), 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);
|
|
});
|
|
});
|