Light, fluffy, and always free - The AWS Local Emulator alternative
fix(s3): reject aws-chunked S3 uploads whose trailing checksum mismatches (#5176)
Matt Van Horn37e66ee371a1
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStream.java b/src/main/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStream.javaindex 107f30465e..03f61d75d4 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStream.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStream.java@@ -1,32 +1,47 @@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 java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.nio.charset.StandardCharsets;+import java.util.Locale;/*** Decodes an aws-chunked body as it is read, so a streaming upload is never held whole. Each chunk* header ({@code hex-size[;chunk-signature=...]}) is consumed and only the chunk data comes out, up- * to the final empty chunk and the trailer lines and empty line after it. Chunk signatures and- * trailing checksums are not checked, as they were not when the body was decoded in one piece. A- * body that breaks the framing or ends early fails with S3's {@code IncompleteBody}.+ * to the final empty chunk and the trailer lines and empty line after it. Chunk signatures are not+ * checked. Only the trailing checksum named up front is kept, so the caller can compare it once+ * the body has been read; any other {@code x-amz-checksum-*} line is recorded as undeclared and+ * every other trailer line is discarded. A body that breaks the framing or ends early fails with+ * S3's {@code IncompleteBody}.*/final class AwsChunkedInputStream extends InputStream {// A chunk header or trailer line is a size, a signature and a few separators; anything longer// is not framing.private static final int MAX_LINE_LENGTH = 8192;+ private static final String CHECKSUM_PREFIX = "x-amz-checksum-";private final InputStream in;+ private final ChecksumAlgorithm trailerAlgorithm;+ private String trailerChecksum;+ private ChecksumAlgorithm undeclaredTrailer;+ private boolean undeclaredChecksum;private long remainingInChunk;private boolean finished;AwsChunkedInputStream(InputStream in) {+ this(in, null);+ }++ /** {@code trailerAlgorithm} is the checksum {@code x-amz-trailer} named, or null when it named none. */+ AwsChunkedInputStream(InputStream in, ChecksumAlgorithm trailerAlgorithm) {this.in = new BufferedInputStream(in);+ this.trailerAlgorithm = trailerAlgorithm;}@Override@@ -60,6 +75,27 @@ final class AwsChunkedInputStream extends InputStream {in.close();}+ /**+ * The declared trailing checksum, once the body has been read to completion. Null before then,+ * and when that line was not sent.+ */+ String trailerChecksum() {+ return trailerChecksum;+ }++ /**+ * The first {@code x-amz-checksum-*} trailer whose name is not the declared one, when that name+ * is a checksum this service knows. Null when there was none.+ */+ ChecksumAlgorithm undeclaredTrailer() {+ return undeclaredTrailer;+ }++ /** Whether a checksum trailer arrived that {@code x-amz-trailer} did not name. */+ boolean hasUndeclaredChecksum() {+ return undeclaredChecksum;+ }+/** Reads the next chunk header; false once the final chunk and its trailer are consumed. */private boolean nextChunk() throws IOException {if (finished) {@@ -82,15 +118,39 @@ final class AwsChunkedInputStream extends InputStream {return true;}// The final chunk: trailer lines such as x-amz-checksum-crc32, if any, then the empty line- // that ends the body.+ // that ends the body. Only the declared checksum is retained.String trailer = readLine();while (!trailer.isEmpty()) {+ int colon = trailer.indexOf(':');+ if (colon > 0) {+ retainTrailer(trailer.substring(0, colon).trim().toLowerCase(Locale.ROOT),+ trailer.substring(colon + 1).trim());+ }trailer = readLine();}finished = true;return false;}+ /** Keeps the declared checksum line. Any other checksum line is undeclared; the rest are dropped. */+ private void retainTrailer(String name, String value) {+ if (!name.startsWith(CHECKSUM_PREFIX)) {+ return;+ }+ if (trailerAlgorithm != null && name.equals(checksumHeader(trailerAlgorithm))) {+ trailerChecksum = value;+ return;+ }+ undeclaredChecksum = true;+ if (undeclaredTrailer == null) {+ undeclaredTrailer = ChecksumAlgorithm.fromChecksumHeader(name);+ }+ }++ private static String checksumHeader(ChecksumAlgorithm algorithm) {+ return CHECKSUM_PREFIX + algorithm.wireValue();+ }+private void readLineBreak() throws IOException {int next = in.read();if (next == '\r') {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.javaindex bc4e341426..41360155a7 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@@ -850,7 +850,8 @@ public class S3Controller {copySource, bucket, key, uploadId, partNumber, httpHeaders, authorization);}Part part = s3Service.storePart(bucket, key, uploadId, partNumber,- decodedBody(body, contentEncoding, contentSha256), uploadChecksums(httpHeaders, uriInfo),+ decodedBody(body, contentEncoding, contentSha256, trailerHeader(httpHeaders, uriInfo)),+ uploadChecksums(httpHeaders, uriInfo),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"));@@ -891,7 +892,8 @@ public class S3Controller {String sseCustomerKeyMd5 = httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key-MD5");String cannedAcl = httpHeaders.getHeaderString("x-amz-acl");s3Service.authorizePutObject(bucket, key, authorization);- S3Object obj = s3Service.putObject(bucket, key, decodedBody(body, contentEncoding, contentSha256),+ S3Object obj = s3Service.putObject(bucket, key,+ decodedBody(body, contentEncoding, contentSha256, trailerHeader(httpHeaders, uriInfo)),uploadChecksums(httpHeaders, uriInfo), contentType, extractUserMetadata(httpHeaders, uriInfo),new PutObjectOptions().withStorageClass(httpHeaders.getHeaderString("x-amz-storage-class"))@@ -2105,22 +2107,29 @@ public class S3Controller {// --- AWS Chunked Decoding ---/**- * The object data of an upload body, read as it arrives. A streaming payload is decoded from its- * aws-chunked framing on the way through. A Content-Encoding naming aws-chunked without that- * declaration does not guarantee framing, so that body is read whole and kept as sent when it- * does not decode.+ * The object data of an upload body, read as it arrives. A streaming payload, and any aws-chunked+ * body that declares {@code x-amz-trailer}, is decoded from its framing on the way through so the+ * trailing checksum can be checked. A Content-Encoding naming aws-chunked without either of those+ * does not guarantee framing, so that body is read whole and kept as sent when it does not decode.*/- private InputStream decodedBody(InputStream body, String contentEncoding, String contentSha256) {+ private InputStream decodedBody(InputStream body, String contentEncoding, String contentSha256,+ String trailer) {InputStream raw = body != null ? body : InputStream.nullInputStream();- if (declaresStreamingPayload(contentSha256)) {- return new AwsChunkedInputStream(raw);+ boolean awsChunked = contentEncoding != null+ && contentEncoding.toLowerCase(Locale.ROOT).contains("aws-chunked");+ if (declaresStreamingPayload(contentSha256) || (awsChunked && trailer != null && !trailer.isBlank())) {+ return new AwsChunkedInputStream(raw, trailerChecksumAlgorithm(trailer));}- if (contentEncoding != null && contentEncoding.toLowerCase(Locale.ROOT).contains("aws-chunked")) {+ if (awsChunked) {return new ByteArrayInputStream(decodeAwsChunked(readWholeBody(raw), contentEncoding, contentSha256));}return raw;}+ private static String trailerHeader(HttpHeaders httpHeaders, UriInfo uriInfo) {+ return resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-trailer");+ }+/** The whole of a body that is small by nature, such as a subresource's XML, or must be read whole to be decoded. */private static byte[] readWholeBody(InputStream body) {if (body == null) {@@ -3161,7 +3170,22 @@ public class S3Controller {claimed.put(algorithm, value);}}- return new UploadChecksums(httpHeaders.getHeaderString("Content-MD5"), claimed);+ return new UploadChecksums(httpHeaders.getHeaderString("Content-MD5"), claimed,+ trailerChecksumAlgorithm(resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-trailer")));+ }++ /** The checksum algorithm an {@code x-amz-trailer} value names, as {@code x-amz-checksum-crc32}. */+ private static ChecksumAlgorithm trailerChecksumAlgorithm(String trailer) {+ if (trailer == null || trailer.isBlank()) {+ return null;+ }+ for (String name : trailer.split(",")) {+ ChecksumAlgorithm algorithm = ChecksumAlgorithm.fromChecksumHeader(name.trim());+ if (algorithm != null) {+ return algorithm;+ }+ }+ return null;}static boolean isWebsiteRequest(HttpHeaders httpHeaders, UriInfo uriInfo) {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.javaindex e07019ec87..bdae4fc76d 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@@ -659,15 +659,12 @@ public class S3Service implements Resettable, ResourceProvider {// A checksum the client sent is stored as sent; otherwise the declared algorithm's, or CRC64NVME.ChecksumAlgorithm computed = effectiveOptions.getClientChecksum() != null ? null: declared != null ? declared : ChecksumAlgorithm.CRC64NVME;- Set<ChecksumAlgorithm> algorithms = EnumSet.noneOf(ChecksumAlgorithm.class);- algorithms.addAll(checksums.algorithms());- if (computed != null) {- algorithms.add(computed);- }- DigestingInputStream digests = new DigestingInputStream(body, algorithms);+ DigestingInputStream digests = new DigestingInputStream(body,+ digestAlgorithms(checksums, computed));Path staged = stageBody(digests);try {checksums.verify(digests.md5(), digests::checksum);+ verifyChunkedTrailers(body, digests, checksums);S3Checksum checksum = null;if (computed != null) {checksum = new S3Checksum();@@ -3881,12 +3878,12 @@ public class S3Service implements Resettable, ResourceProvider {sseCustomerAlgorithm, sseCustomerKey, sseCustomerKeyMd5);}ChecksumAlgorithm algorithm = declared != null ? declared : ChecksumAlgorithm.CRC64NVME;- Set<ChecksumAlgorithm> algorithms = EnumSet.of(algorithm);- algorithms.addAll(checksums.algorithms());- DigestingInputStream digests = new DigestingInputStream(body, algorithms);+ DigestingInputStream digests = new DigestingInputStream(body,+ digestAlgorithms(checksums, algorithm));Path staged = stageBody(digests);try {checksums.verify(digests.md5(), digests::checksum);+ verifyChunkedTrailers(body, digests, checksums);S3Checksum partChecksum = new S3Checksum();partChecksum.setValueFor(algorithm, digests.checksum(algorithm));return withMultipartOperationLock(bucket, uploadId, () -> {@@ -3918,7 +3915,7 @@ public class S3Service implements Resettable, ResourceProvider {* with EntityTooLarge once it outgrows the largest array the JDK allocates.*/private static byte[] readVerified(InputStream body, UploadChecksums checksums, String upload) {- DigestingInputStream digests = new DigestingInputStream(body, checksums.algorithms());+ DigestingInputStream digests = new DigestingInputStream(body, digestAlgorithms(checksums, null));ByteArrayOutputStream out = new ByteArrayOutputStream();byte[] buffer = new byte[64 * 1024];try {@@ -3930,9 +3927,33 @@ public class S3Service implements Resettable, ResourceProvider {throw new UncheckedIOException("Failed to read the upload body", e);}checksums.verify(digests.md5(), digests::checksum);+ verifyChunkedTrailers(body, digests, checksums);return out.toByteArray();}+ /**+ * Algorithms hashed as a body is read. A trailing checksum is hashed only when+ * {@code x-amz-trailer} named it, which is the only trailer line that is checked.+ */+ private static Set<ChecksumAlgorithm> digestAlgorithms(UploadChecksums checksums, ChecksumAlgorithm stored) {+ Set<ChecksumAlgorithm> algorithms = EnumSet.noneOf(ChecksumAlgorithm.class);+ algorithms.addAll(checksums.algorithms());+ if (stored != null) {+ algorithms.add(stored);+ }+ if (checksums.trailerAlgorithm() != null) {+ algorithms.add(checksums.trailerAlgorithm());+ }+ return algorithms;+ }++ private static void verifyChunkedTrailers(InputStream body, DigestingInputStream digests,+ UploadChecksums checksums) {+ if (body instanceof AwsChunkedInputStream chunked) {+ checksums.verifyTrailers(chunked, digests::checksum);+ }+ }+/*** Writes a streamed body to a new file under the staging directory and returns it. The file is* deleted if the body fails partway, so on return the caller owns it.diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/UploadChecksums.java b/src/main/java/io/github/hectorvent/floci/services/s3/UploadChecksums.javaindex 28cdcc5bf5..1d27112400 100644--- a/src/main/java/io/github/hectorvent/floci/services/s3/UploadChecksums.java+++ b/src/main/java/io/github/hectorvent/floci/services/s3/UploadChecksums.java@@ -13,17 +13,24 @@ import java.util.function.Function;/*** The integrity headers an upload body is checked against: Content-MD5 and the x-amz-checksum-** values. A malformed Content-MD5 is rejected before any of the body is read; the digests are- * compared once it has been.+ * compared once it has been. {@code trailerAlgorithm} is the checksum named by {@code x-amz-trailer}+ * when that header names an {@code x-amz-checksum-*} value.*/-record UploadChecksums(String contentMd5, Map<ChecksumAlgorithm, String> claimed) {+record UploadChecksums(String contentMd5, Map<ChecksumAlgorithm, String> claimed,+ ChecksumAlgorithm trailerAlgorithm) {/** No integrity headers, as for the part an UploadPartCopy reads from another object. */- static final UploadChecksums NONE = new UploadChecksums(null, Map.of());+ static final UploadChecksums NONE = new UploadChecksums(null, Map.of(), null);// The order the checksums have always been checked in, so a body failing several reports the same one.private static final List<ChecksumAlgorithm> CHECK_ORDER = List.of(ChecksumAlgorithm.SHA1,ChecksumAlgorithm.SHA256, ChecksumAlgorithm.CRC32, ChecksumAlgorithm.CRC32C, ChecksumAlgorithm.CRC64NVME);+ /** A request that does not declare a trailing checksum. */+ UploadChecksums(String contentMd5, Map<ChecksumAlgorithm, String> claimed) {+ this(contentMd5, claimed, null);+ }+UploadChecksums {claimed = Map.copyOf(claimed);}@@ -48,12 +55,36 @@ record UploadChecksums(String contentMd5, Map<ChecksumAlgorithm, String> claimedfor (ChecksumAlgorithm algorithm : CHECK_ORDER) {String claimedValue = claimed.get(algorithm);if (claimedValue != null && !claimedValue.equals(actualChecksum.apply(algorithm))) {- throw new AwsException("BadDigest", "The " + algorithm.name()- + " checksum you specified did not match the payload.", 400);+ throw checksumMismatch(algorithm);}}}+ /**+ * Compares the trailing checksum named by {@code x-amz-trailer} to the decoded body.+ * {@code x-amz-trailer-signature} is not a checksum and is ignored. A declared trailer whose+ * checksum line is missing, or any other {@code x-amz-checksum-*} line, fails the same way as+ * a value that does not match.+ */+ void verifyTrailers(AwsChunkedInputStream chunked, Function<ChecksumAlgorithm, String> actualChecksum) {+ String claimedValue = chunked.trailerChecksum();+ if (trailerAlgorithm != null+ && (claimedValue == null || !claimedValue.equals(actualChecksum.apply(trailerAlgorithm)))) {+ throw checksumMismatch(trailerAlgorithm);+ }+ if (chunked.hasUndeclaredChecksum()) {+ ChecksumAlgorithm reported = chunked.undeclaredTrailer() != null+ ? chunked.undeclaredTrailer() : trailerAlgorithm;+ throw checksumMismatch(reported);+ }+ }++ private static AwsException checksumMismatch(ChecksumAlgorithm algorithm) {+ String name = algorithm != null ? algorithm.name() : "checksum";+ return new AwsException("BadDigest",+ "The " + name + " you specified did not match the calculated checksum.", 400);+ }+private byte[] expectedMd5() {byte[] expected;try {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.javaindex 36bb1487ce..29f2f5f7ce 100644--- 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@@ -78,10 +78,36 @@ public enum ChecksumAlgorithm {return compute(concatenated.toByteArray()) + "-" + partChecksums.size();}+ /**+ * The algorithm an {@code x-amz-checksum-*} header name refers to, or {@code null} when the+ * name is not one this service knows.+ */+ public static ChecksumAlgorithm fromChecksumHeader(String headerName) {+ String prefix = "x-amz-checksum-";+ if (headerName == null || headerName.length() <= prefix.length()+ || !headerName.regionMatches(true, 0, prefix, 0, prefix.length())) {+ return null;+ }+ return lookup(headerName.substring(prefix.length()));+ }+/*** Parses an {@code x-amz-checksum-algorithm} value. Returns {@code null} when the header is absent.*/public static ChecksumAlgorithm fromWireValue(String value) {+ ChecksumAlgorithm algorithm = lookup(value);+ if (algorithm != null || value == null || value.isBlank()) {+ return algorithm;+ }+ String normalized = value.trim().toUpperCase(Locale.ROOT);+ 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);+ }++ private static ChecksumAlgorithm lookup(String value) {if (value == null || value.isBlank()) {return null;}@@ -91,10 +117,6 @@ public enum ChecksumAlgorithm {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);+ return null;}}diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStreamTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStreamTest.javaindex a18282a093..45da38cd39 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStreamTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/AwsChunkedInputStreamTest.java@@ -1,6 +1,7 @@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 org.junit.jupiter.api.Test;import java.io.ByteArrayInputStream;@@ -27,6 +28,48 @@ class AwsChunkedInputStreamTest {+ "x-amz-trailer-signature:ghi\r\n\r\n"));}+ @Test+ void retainsOnlyTheDeclaredChecksumTrailer() throws IOException {+ StringBuilder framed = new StringBuilder("5\r\nhello\r\n0\r\n");+ for (int i = 0; i < 1000; i++) {+ framed.append("x-amz-trailer-signature:").append(i).append("\r\n");+ }+ framed.append("x-amz-checksum-crc32:NhCmhg==\r\n\r\n");++ try (AwsChunkedInputStream in = new AwsChunkedInputStream(+ new ByteArrayInputStream(framed.toString().getBytes(StandardCharsets.US_ASCII)),+ ChecksumAlgorithm.CRC32)) {+ assertEquals("hello", new String(in.readAllBytes(), StandardCharsets.US_ASCII));+ assertEquals("NhCmhg==", in.trailerChecksum());+ assertNull(in.undeclaredTrailer());+ assertFalse(in.hasUndeclaredChecksum());+ }+ }++ @Test+ void recordsAChecksumTrailerOtherThanTheDeclaredOne() throws IOException {+ try (AwsChunkedInputStream in = new AwsChunkedInputStream(new ByteArrayInputStream(+ ("5\r\nhello\r\n0\r\nx-amz-checksum-crc32:NhCmhg==\r\n"+ + "x-amz-checksum-sha256:abc\r\n\r\n").getBytes(StandardCharsets.US_ASCII)),+ ChecksumAlgorithm.CRC32)) {+ assertEquals("hello", new String(in.readAllBytes(), StandardCharsets.US_ASCII));+ assertEquals("NhCmhg==", in.trailerChecksum());+ assertEquals(ChecksumAlgorithm.SHA256, in.undeclaredTrailer());+ assertTrue(in.hasUndeclaredChecksum());+ }+ }++ @Test+ void aChecksumTrailerWithNoDeclaredAlgorithmIsUndeclared() throws IOException {+ try (AwsChunkedInputStream in = new AwsChunkedInputStream(new ByteArrayInputStream(+ "5\r\nhello\r\n0\r\nx-amz-checksum-crc32:NhCmhg==\r\n\r\n".getBytes(StandardCharsets.US_ASCII)))) {+ assertEquals("hello", new String(in.readAllBytes(), StandardCharsets.US_ASCII));+ assertNull(in.trailerChecksum());+ assertEquals(ChecksumAlgorithm.CRC32, in.undeclaredTrailer());+ assertTrue(in.hasUndeclaredChecksum());+ }+ }+@Testvoid acceptsBareLineFeeds() throws IOException {assertEquals("hello", decode("5\nhello\n0\n\n"));diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AwsChunkedIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AwsChunkedIntegrationTest.javaindex d06e96ffb2..64b157cff7 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3AwsChunkedIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AwsChunkedIntegrationTest.java@@ -161,6 +161,7 @@ class S3AwsChunkedIntegrationTest {given().header("x-amz-content-sha256", "STREAMING-AWS4-ECDSA-P256-SHA256-PAYLOAD-TRAILER")+ .header("x-amz-trailer", "x-amz-checksum-crc32").body("5;chunk-signature=abc\r\nhello\r\n0;chunk-signature=def\r\n"+ "x-amz-checksum-crc32:NhCmhg==\r\nx-amz-trailer-signature:ghi\r\n\r\n").when()@@ -171,6 +172,111 @@ class S3AwsChunkedIntegrationTest {given().when().get("/" + bucket + "/object.txt").then().statusCode(200).body(equalTo("hello"));}+ @Test+ void putObject_trailingChecksumMismatch_isBadDigestAndNotStored() {+ String bucket = createBucket("chunked-bad-digest");++ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(400)+ .body(containsString("<Code>BadDigest</Code>"))+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));++ assertObjectAbsent(bucket, "object.txt");+ }++ @Test+ void putObject_trailingChecksumMatch_storesTheDecodedPayload() {+ String bucket = createBucket("chunked-good-digest");++ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:DUoRhQ==\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(200);++ given().when().get("/" + bucket + "/object.txt").then().statusCode(200).body(equalTo("hello world"));+ }++ @Test+ void putObject_declaredTrailerMissingFromTheBody_isBadDigestAndNotStored() {+ String bucket = createBucket("chunked-trailer-missing");+ for (String body : new String[] {+ "b\r\nhello world\r\n0\r\nx-amz-checksum-crc32c:AAAAAA==\r\n\r\n",+ "b\r\nhello world\r\n0\r\n\r\n"}) {+ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body(body)+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(400)+ .body(containsString("<Code>BadDigest</Code>"))+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));+ }++ assertObjectAbsent(bucket, "object.txt");+ }++ @Test+ void uploadPart_trailingChecksumMismatch_isBadDigestAndNoPartIsStored() {+ String bucket = createBucket("chunked-part-digest");+ String uploadId = given()+ .when().post("/" + bucket + "/object.txt?uploads")+ .then().statusCode(200)+ .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");++ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt?partNumber=1&uploadId=" + uploadId)+ .then()+ .statusCode(400)+ .body(containsString("<Code>BadDigest</Code>"))+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));++ given()+ .when().get("/" + bucket + "/object.txt?uploadId=" + uploadId)+ .then().statusCode(200)+ .body(not(containsString("<Part>")));+ }++ @Test+ void uploadPart_trailingChecksumMatch_storesThePart() {+ String bucket = createBucket("chunked-part-ok");+ String uploadId = given()+ .when().post("/" + bucket + "/object.txt?uploads")+ .then().statusCode(200)+ .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");++ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:DUoRhQ==\r\n"+ + "x-amz-trailer-signature:ghi\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt?partNumber=1&uploadId=" + uploadId)+ .then()+ .statusCode(200);++ given()+ .when().get("/" + bucket + "/object.txt?uploadId=" + uploadId)+ .then().statusCode(200)+ .body(containsString("<Part>"))+ .body(containsString("<Size>11</Size>"));+ }+@Testvoid uploadPart_malformedBody_isIncompleteBodyAndNoPartIsStored() {String bucket = createBucket("chunked-part");@@ -195,6 +301,109 @@ class S3AwsChunkedIntegrationTest {.body(not(containsString("<Part>")));}+ @Test+ void putObject_chunkedBodyWithoutATrailer_storesTheDecodedPayload() {+ String bucket = createBucket("chunked-no-trailer");++ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .body("5\r\nhello\r\n0\r\nx-amz-trailer-signature:ghi\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(200);++ given().when().get("/" + bucket + "/object.txt").then().statusCode(200).body(equalTo("hello"));+ }++ @Test+ void putObject_undeclaredChecksumTrailer_isBadDigestAndNotStored() {+ String bucket = createBucket("chunked-undeclared");++ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:DUoRhQ==\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(400)+ .body(containsString("<Code>BadDigest</Code>"))+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));++ given()+ .header("x-amz-content-sha256", STREAMING_UNSIGNED)+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:DUoRhQ==\r\n"+ + "x-amz-checksum-sha256:abc\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(400)+ .body(containsString("<Code>BadDigest</Code>"))+ .body(containsString("The SHA256 you specified did not match the calculated checksum."));++ assertObjectAbsent(bucket, "object.txt");+ }++ @Test+ void putObject_awsChunkedTrailerWithoutStreamingSha256_rejectsAMismatchedTrailer() {+ String bucket = createBucket("chunked-lenient-trailer");++ given()+ .header("Content-Encoding", "aws-chunked")+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(400)+ .body(containsString("<Code>BadDigest</Code>"))+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));++ assertObjectAbsent(bucket, "object.txt");+ }++ @Test+ void putObject_awsChunkedTrailerWithoutStreamingSha256_storesAMatchingTrailer() {+ String bucket = createBucket("chunked-lenient-ok");++ given()+ .header("Content-Encoding", "aws-chunked")+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:DUoRhQ==\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt")+ .then()+ .statusCode(200);++ given().when().get("/" + bucket + "/object.txt").then().statusCode(200).body(equalTo("hello world"));+ }++ @Test+ void uploadPart_awsChunkedTrailerWithoutStreamingSha256_rejectsAMismatchedTrailer() {+ String bucket = createBucket("chunked-part-lenient");+ String uploadId = given()+ .when().post("/" + bucket + "/object.txt?uploads")+ .then().statusCode(200)+ .extract().xmlPath().getString("InitiateMultipartUploadResult.UploadId");++ given()+ .header("Content-Encoding", "aws-chunked")+ .header("x-amz-trailer", "x-amz-checksum-crc32")+ .body("b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n")+ .when()+ .put("/" + bucket + "/object.txt?partNumber=1&uploadId=" + uploadId)+ .then()+ .statusCode(400)+ .body(containsString("<Code>BadDigest</Code>"))+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));++ given()+ .when().get("/" + bucket + "/object.txt?uploadId=" + uploadId)+ .then().statusCode(200)+ .body(not(containsString("<Part>")));+ }+// Without a streaming x-amz-content-sha256, a Content-Encoding naming aws-chunked does not// mean the body is framed, so a body that is not framed is stored as sent.@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ChecksumTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ChecksumTest.javaindex da002ea710..a9ec8b3ea0 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ChecksumTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ChecksumTest.java@@ -255,6 +255,13 @@ class S3ChecksumTest {assertEquals("InvalidRequest", knownButUnsupported.getErrorCode());AwsException unknown = assertThrows(AwsException.class, () -> ChecksumAlgorithm.fromWireValue("MURMUR3"));assertEquals("InvalidArgument", unknown.getErrorCode());++ assertEquals(ChecksumAlgorithm.CRC32, ChecksumAlgorithm.fromChecksumHeader("x-amz-checksum-crc32"));+ assertEquals(ChecksumAlgorithm.SHA256, ChecksumAlgorithm.fromChecksumHeader("X-Amz-Checksum-SHA256"));+ assertNull(ChecksumAlgorithm.fromChecksumHeader("x-amz-checksum-sha512"));+ assertNull(ChecksumAlgorithm.fromChecksumHeader("x-amz-checksum-murmur3"));+ assertNull(ChecksumAlgorithm.fromChecksumHeader("x-amz-trailer-signature"));+ assertNull(ChecksumAlgorithm.fromChecksumHeader(null));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.javaindex 6492b41a12..23b7a30a68 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3PresignedChecksumIntegrationTest.java@@ -52,7 +52,7 @@ class S3PresignedChecksumIntegrationTest {.then().statusCode(400).body(containsString("BadDigest"))- .body(containsString("The CRC32 checksum you specified did not match the payload."));+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));// Xác nhận object không được lưu vào storagegiven()@@ -137,7 +137,7 @@ class S3PresignedChecksumIntegrationTest {.then().statusCode(400).body(containsString("BadDigest"))- .body(containsString("The SHA256 checksum you specified did not match the payload."));+ .body(containsString("The SHA256 you specified did not match the calculated checksum."));}@Test@@ -170,7 +170,7 @@ class S3PresignedChecksumIntegrationTest {.then().statusCode(400).body(containsString("BadDigest"))- .body(containsString("The CRC32 checksum you specified did not match the payload."));+ .body(containsString("The CRC32 you specified did not match the calculated checksum."));}@Testdiff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3StreamedUploadTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3StreamedUploadTest.javaindex 2b4162da7d..613dd02305 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3StreamedUploadTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3StreamedUploadTest.java@@ -42,6 +42,17 @@ class S3StreamedUploadTest {private static final byte[] BODY = "a body that arrives as a stream".getBytes(StandardCharsets.UTF_8);private static final UploadChecksums NO_CHECKSUMS = new UploadChecksums(null, Map.of());+ private static final String CHUNKED_MISMATCH =+ "b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:AAAAAA==\r\n\r\n";+ private static final String CHUNKED_MATCH =+ "b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:DUoRhQ==\r\n\r\n";+ private static final String CHUNKED_EXTRA =+ "b\r\nhello world\r\n0\r\nx-amz-checksum-crc32:DUoRhQ==\r\nx-amz-checksum-sha256:abc\r\n\r\n";+ private static final String CHUNKED_PLAIN = "b\r\nhello world\r\n0\r\nx-amz-trailer-signature:ghi\r\n\r\n";+ private static final String TRAILER_MISMATCH =+ "The CRC32 you specified did not match the calculated checksum.";+ private static final String UNDECLARED_TRAILER =+ "The SHA256 you specified did not match the calculated checksum.";@TempDirPath tempDir;@@ -304,6 +315,102 @@ class S3StreamedUploadTest {}}+ @Test+ void aChunkedTrailerChecksumIsCheckedBeforeTheObjectOrPartIsStored() {+ byte[] payload = "hello world".getBytes(StandardCharsets.US_ASCII);+ UploadChecksums declared = new UploadChecksums(null, Map.of(), ChecksumAlgorithm.CRC32);++ for (S3Service service : List.of(s3Service, memoryService())) {+ AwsException error = assertThrows(AwsException.class, () -> service.putObject("bucket", "bad.txt",+ chunked(CHUNKED_MISMATCH), declared, "text/plain", Map.of(), new PutObjectOptions()));+ assertEquals("BadDigest", error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ assertEquals(TRAILER_MISMATCH, error.getMessage());+ assertEquals("NoSuchKey", assertThrows(AwsException.class,+ () -> service.headObject("bucket", "bad.txt")).getErrorCode());++ S3Object stored = service.putObject("bucket", "good.txt", chunked(CHUNKED_MATCH), declared,+ "text/plain", Map.of(), new PutObjectOptions());+ assertEquals(payload.length, stored.getSize());+ assertArrayEquals(payload, service.getObject("bucket", "good.txt").getData());++ MultipartUpload upload = service.initiateMultipartUpload("bucket", "part.bin", null);+ assertEquals("BadDigest", assertThrows(AwsException.class, () -> service.storePart("bucket", "part.bin",+ upload.getUploadId(), 1, chunked(CHUNKED_MISMATCH), declared, null, null, null)).getErrorCode());+ assertTrue(service.getMultipartUpload("bucket", "part.bin", upload.getUploadId()).getParts().isEmpty());++ Part part = service.storePart("bucket", "part.bin", upload.getUploadId(), 1, chunked(CHUNKED_MATCH),+ declared, null, null, null);+ assertEquals(payload.length, part.getSize());+ assertEquals(1, service.getMultipartUpload("bucket", "part.bin", upload.getUploadId()).getParts().size());+ }+ assertNothingStaged();+ }++ @Test+ void aDeclaredTrailerMissingFromTheChunkIsNotStored() {+ UploadChecksums declared = new UploadChecksums(null, Map.of(), ChecksumAlgorithm.CRC32);++ for (S3Service service : List.of(s3Service, memoryService())) {+ for (String framed : List.of(+ "b\r\nhello world\r\n0\r\nx-amz-checksum-crc32c:AAAAAA==\r\n\r\n",+ "b\r\nhello world\r\n0\r\n\r\n")) {+ AwsException error = assertThrows(AwsException.class, () -> service.putObject("bucket", "missing.txt",+ chunked(framed), declared, "text/plain", Map.of(), new PutObjectOptions()));+ assertEquals("BadDigest", error.getErrorCode());+ assertEquals(TRAILER_MISMATCH, error.getMessage());+ assertEquals("NoSuchKey", assertThrows(AwsException.class,+ () -> service.headObject("bucket", "missing.txt")).getErrorCode());+ }+ }+ assertNothingStaged();+ }++ @Test+ void aChunkedUploadWithoutATrailerIsStored() {+ byte[] payload = "hello world".getBytes(StandardCharsets.US_ASCII);++ for (S3Service service : List.of(s3Service, memoryService())) {+ S3Object stored = service.putObject("bucket", "plain.txt",+ new AwsChunkedInputStream(new ByteArrayInputStream(CHUNKED_PLAIN.getBytes(StandardCharsets.US_ASCII))),+ NO_CHECKSUMS, "text/plain", Map.of(), new PutObjectOptions());++ assertEquals(payload.length, stored.getSize());+ assertArrayEquals(payload, service.getObject("bucket", "plain.txt").getData());+ }+ assertNothingStaged();+ }++ @Test+ void anUndeclaredChecksumTrailerIsNotStored() {+ UploadChecksums declared = new UploadChecksums(null, Map.of(), ChecksumAlgorithm.CRC32);++ for (S3Service service : List.of(s3Service, memoryService())) {+ AwsException extra = assertThrows(AwsException.class, () -> service.putObject("bucket", "extra.txt",+ chunked(CHUNKED_EXTRA), declared, "text/plain", Map.of(), new PutObjectOptions()));+ assertEquals("BadDigest", extra.getErrorCode());+ assertEquals(400, extra.getHttpStatus());+ assertEquals(UNDECLARED_TRAILER, extra.getMessage());++ AwsException undeclared = assertThrows(AwsException.class, () -> service.putObject("bucket", "none.txt",+ new AwsChunkedInputStream(new ByteArrayInputStream(CHUNKED_MATCH.getBytes(StandardCharsets.US_ASCII))),+ NO_CHECKSUMS, "text/plain", Map.of(), new PutObjectOptions()));+ assertEquals("BadDigest", undeclared.getErrorCode());+ assertEquals(TRAILER_MISMATCH, undeclared.getMessage());++ assertEquals("NoSuchKey", assertThrows(AwsException.class,+ () -> service.headObject("bucket", "extra.txt")).getErrorCode());+ assertEquals("NoSuchKey", assertThrows(AwsException.class,+ () -> service.headObject("bucket", "none.txt")).getErrorCode());++ MultipartUpload upload = service.initiateMultipartUpload("bucket", "part.bin", null);+ assertEquals("BadDigest", assertThrows(AwsException.class, () -> service.storePart("bucket", "part.bin",+ upload.getUploadId(), 1, chunked(CHUNKED_EXTRA), declared, null, null, null)).getErrorCode());+ assertTrue(service.getMultipartUpload("bucket", "part.bin", upload.getUploadId()).getParts().isEmpty());+ }+ assertNothingStaged();+ }+@Testvoid memoryModeReadsTheStreamIntoTheBytePaths() {S3Service memory = memoryService();@@ -373,6 +480,11 @@ class S3StreamedUploadTest {}}+ private static AwsChunkedInputStream chunked(String framed) {+ return new AwsChunkedInputStream(new ByteArrayInputStream(framed.getBytes(StandardCharsets.US_ASCII)),+ ChecksumAlgorithm.CRC32);+ }+/** A body the write should never get to reading. */private static InputStream unreadable() {return new InputStream() {