fix(s3): reject a PutObject or UploadPart over 5 GiB (#5469)

S3 takes at most 5 GB in one PutObject and 5 GiB in one part (User
Guide, "Uploading objects" and the multipart upload limits table), but
Floci only enforced that for UploadPartCopy. Since PutObject and
UploadPart stream to disk, the only cap was
FLOCI_PROTOCOLS_MAX_REQUEST_SIZE, so raising it past 5120 MB, as
docs/services/s3.md says to for 5 GiB uploads, let a single request
store any size up to the new limit.

A request that declares more than 5 GiB of data, in Content-Length or,
for an aws-chunked body, x-amz-decoded-content-length (its
Content-Length also counts the framing), now fails with EntityTooLarge
before any of its body is read. A body that declares no size, or less
than it sends, fails the same way once it passes 5 GiB: the stream that
digests a body on its way to disk counts it against the limit, while
memory mode already stops at about 2 GiB. PutObject's "5 GB" is taken
as 5 GiB, as CopyObject's is.

The error is now the one S3 sends, as S3's answer to an oversized
UploadPart logged in aws/aws-cli#5420 and an AWS-validated LocalStack
capture record it: the message "Your proposed upload exceeds the maximum
allowed size", not the error table's description, and the ProposedSize
and MaxSizeAllowed fields, ProposedSize left out when a body passes the
limit as it is read, since its whole size is then not known. It is built
in one place and shared with UploadPartCopy and the memory-mode cap,
which sent the table's wording and named neither size; the memory-mode
cap names the most memory mode can hold.

A client that sent Expect: 100-continue never sends a body it was not
told to continue with, so answering it before reading the body left the
connection waiting for that body and reading the client's next request
as it (#5291). Such an answer now says Connection: close and the
connection is closed after it, which covers this rejection as well as
NoSuchBucket or a failed precondition.

An aws-chunked body sent without a streaming x-amz-content-sha256 or an
x-amz-trailer is read whole to be decoded. That read now fails with
EntityTooLarge once it passes what one array holds, through the bounded
read memory mode uses, instead of running the heap out of memory.

Telling an aws-chunked body from its Content-Encoding is now one helper,
which the four places that repeated the check use too.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-11 21:47:48 -05:00
1 parent 233253334d
commit 6d2aaba6a6
12 files changed
+564 -35

No files matched your search

@@ -0,0 +1,49 @@
package io.github.hectorvent.floci.core.common;
import io.quarkus.vertx.http.runtime.CurrentVertxRequest;
import io.vertx.core.http.HttpHeaders;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpVersion;
import io.vertx.ext.web.RoutingContext;
import jakarta.ws.rs.container.ContainerRequestContext;
import jakarta.ws.rs.container.ContainerResponseContext;
import jakarta.ws.rs.container.ContainerResponseFilter;
import jakarta.ws.rs.ext.Provider;
/**
* Closes the connection after answering a request that sent {@code Expect: 100-continue} before any
* of its body arrived, as when an upload is rejected on its headers alone. The client never sends a
* body it was not told to continue with, so a connection kept open would read the client's next
* request as that body. The response says {@code Connection: close}, so the client does not reuse it
* either.
*/
@Provider
public class ExpectContinueConnectionFilter implements ContainerResponseFilter {
private final CurrentVertxRequest currentVertxRequest;
public ExpectContinueConnectionFilter(CurrentVertxRequest currentVertxRequest) {
this.currentVertxRequest = currentVertxRequest;
}
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
RoutingContext context = currentVertxRequest.getCurrent();
if (context == null || !awaitsUnsentBody(context.request())) {
return;
}
responseContext.getHeaders().putSingle(HttpHeaders.CONNECTION.toString(), HttpHeaders.CLOSE.toString());
context.addEndHandler(ended -> context.request().connection().close());
}
/**
* Whether the request is waiting to be told to continue before it sends its body. An HTTP/2
* connection carries other requests, so it is never closed for one of them.
*/
private static boolean awaitsUnsentBody(HttpServerRequest request) {
return request.version() != HttpVersion.HTTP_2
&& request.headers().contains(HttpHeaders.EXPECT, HttpHeaders.CONTINUE, true)
&& !request.isEnded()
&& request.bytesRead() == 0;
}
}
@@ -15,18 +15,21 @@ import java.util.Map;
/**
* Passes an upload body through while computing its MD5, the checksums it is checked against or
* stored with, and its size, so a body can be validated and stored without being held whole.
* stored with, and its size, so a body can be validated and stored without being held whole. A body
* that runs past the most its request may upload fails with EntityTooLarge, whatever size it declared.
*/
final class DigestingInputStream extends FilterInputStream {
private final MessageDigest md5;
private final Map<ChecksumAlgorithm, S3Checksum.Calculator> calculators = new EnumMap<>(ChecksumAlgorithm.class);
private final Map<ChecksumAlgorithm, String> checksums = new EnumMap<>(ChecksumAlgorithm.class);
private final long maxSize;
private byte[] md5Digest;
private long size;
DigestingInputStream(InputStream in, Collection<ChecksumAlgorithm> algorithms) {
DigestingInputStream(InputStream in, Collection<ChecksumAlgorithm> algorithms, long maxSize) {
super(in);
this.maxSize = maxSize;
try {
this.md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
@@ -106,6 +109,9 @@ final class DigestingInputStream extends FilterInputStream {
}
private void update(byte[] buffer, int offset, int length) {
if (size + length > maxSize) {
throw S3Service.entityTooLarge(maxSize);
}
md5.update(buffer, offset, length);
for (S3Checksum.Calculator calculator : calculators.values()) {
calculator.update(buffer, offset, length);
@@ -847,6 +847,7 @@ public class S3Controller {
return handleUploadPartCopy(
copySource, bucket, key, uploadId, partNumber, httpHeaders, authorization);
}
requireDeclaredSizeWithin(httpHeaders, contentEncoding, contentSha256, S3Service.MAX_PART_SIZE);
Part part = s3Service.storePart(bucket, key, uploadId, partNumber,
decodedBody(body, contentEncoding, contentSha256, trailerHeader(httpHeaders, uriInfo)),
uploadChecksums(httpHeaders, uriInfo),
@@ -890,6 +891,7 @@ 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);
requireDeclaredSizeWithin(httpHeaders, contentEncoding, contentSha256, S3Service.MAX_PUT_OBJECT_SIZE);
S3Object obj = s3Service.putObject(bucket, key,
decodedBody(body, contentEncoding, contentSha256, trailerHeader(httpHeaders, uriInfo)),
uploadChecksums(httpHeaders, uriInfo), contentType, extractUserMetadata(httpHeaders, uriInfo),
@@ -2163,27 +2165,55 @@ public class S3Controller {
* 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.
* does not guarantee framing, so that body is read whole, failing with EntityTooLarge past the most
* one array holds, and kept as sent when it does not decode.
*/
private InputStream decodedBody(InputStream body, String contentEncoding, String contentSha256,
String trailer) {
InputStream raw = body != null ? body : InputStream.nullInputStream();
boolean awsChunked = contentEncoding != null
&& contentEncoding.toLowerCase(Locale.ROOT).contains("aws-chunked");
boolean awsChunked = namesAwsChunked(contentEncoding);
if (declaresStreamingPayload(contentSha256) || (awsChunked && trailer != null && !trailer.isBlank())) {
return new AwsChunkedInputStream(raw, trailerChecksumAlgorithm(trailer));
}
if (awsChunked) {
return new ByteArrayInputStream(decodeAwsChunked(readWholeBody(raw), contentEncoding, contentSha256));
byte[] whole = S3Service.readWithin(raw, S3Service.MAX_IN_MEMORY_OBJECT_SIZE, readSoFar -> LOG.warnv(
"Rejecting an aws-chunked body of more than {0} bytes: sent without a streaming x-amz-content-sha256 or an x-amz-trailer, it is read whole to be decoded",
S3Service.MAX_IN_MEMORY_OBJECT_SIZE));
return new ByteArrayInputStream(decodeAwsChunked(whole, contentEncoding, contentSha256));
}
return raw;
}
/**
* Rejects an upload that declares more data than {@code maxSize} before any of it is read. An
* aws-chunked body declares its data in {@code x-amz-decoded-content-length}, since its
* Content-Length also counts the framing. A body that declares no size, or a size that is not a
* number, is held to the limit as it is read.
*/
static void requireDeclaredSizeWithin(HttpHeaders httpHeaders, String contentEncoding, String contentSha256,
long maxSize) {
boolean awsChunked = declaresStreamingPayload(contentSha256) || namesAwsChunked(contentEncoding);
String declared = httpHeaders.getHeaderString(awsChunked ? "x-amz-decoded-content-length" : "Content-Length");
if (declared == null) {
return;
}
long size;
try {
size = Long.parseLong(declared.trim());
} catch (NumberFormatException ignored) {
// Not a size, so nothing is known before the body is read, which is held to the limit as it arrives.
return;
}
if (size > maxSize) {
throw S3Service.entityTooLarge(size, maxSize);
}
}
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. */
/** The whole of a body that is small by nature, such as a subresource's XML. */
private static byte[] readWholeBody(InputStream body) {
if (body == null) {
return new byte[0];
@@ -2201,8 +2231,7 @@ public class S3Controller {
*/
private byte[] decodeAwsChunked(byte[] body, String contentEncoding, String contentSha256) {
boolean declaresStreamingPayload = declaresStreamingPayload(contentSha256);
boolean isAwsChunked = declaresStreamingPayload || (contentEncoding != null
&& contentEncoding.toLowerCase(Locale.ROOT).contains("aws-chunked"));
boolean isAwsChunked = declaresStreamingPayload || namesAwsChunked(contentEncoding);
if (!isAwsChunked) {
return body;
}
@@ -2257,6 +2286,11 @@ public class S3Controller {
}
}
/** Whether a Content-Encoding names aws-chunked, alone or with other codings. */
private static boolean namesAwsChunked(String contentEncoding) {
return contentEncoding != null && contentEncoding.toLowerCase(Locale.ROOT).contains("aws-chunked");
}
/** Whether x-amz-content-sha256 declares a streaming payload, which is always aws-chunked. */
static boolean declaresStreamingPayload(String contentSha256) {
return "STREAMING-AWS4-HMAC-SHA256-PAYLOAD".equals(contentSha256)
@@ -3401,8 +3435,15 @@ public class S3Controller {
xmlBuilder.elem("Condition", condition);
}
// S3 InvalidArgument responses carry ArgumentName and ArgumentValue so the SDK can
// surface which input was rejected. They travel through AwsException.extendedData.
// surface which input was rejected, and EntityTooLarge the proposed and allowed sizes.
// They travel through AwsException.extendedData.
if (e.getExtendedData() != null) {
for (String sizeField : List.of("ProposedSize", "MaxSizeAllowed")) {
Object size = e.getExtendedData().get(sizeField);
if (size != null) {
xmlBuilder.elem(sizeField, size.toString());
}
}
Object resource = e.getExtendedData().get("Resource");
if (resource != null) {
xmlBuilder.elem("Resource", resource.toString());
@@ -4290,8 +4331,7 @@ public class S3Controller {
if (contentSha256 != null && contentSha256.startsWith("STREAMING-")) {
return true;
}
String contentEncoding = httpHeaders.getHeaderString("Content-Encoding");
if (contentEncoding != null && contentEncoding.toLowerCase(Locale.ROOT).contains("aws-chunked")) {
if (namesAwsChunked(httpHeaders.getHeaderString("Content-Encoding"))) {
return true;
}
if (httpHeaders.getHeaderString("x-amz-decoded-content-length") != null
@@ -85,6 +85,7 @@ import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.LongConsumer;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -220,7 +221,7 @@ public class S3Service implements Resettable, ResourceProvider {
return locks;
}
// Memory mode keeps an object in one byte array; this is the largest the JDK reliably allocates.
private static final long MAX_IN_MEMORY_OBJECT_SIZE = Integer.MAX_VALUE - 8;
static final long MAX_IN_MEMORY_OBJECT_SIZE = Integer.MAX_VALUE - 8;
// Directory under .multipart where a streamed part or object body is written before it is
// published. Upload IDs are UUIDs, so it never collides with an upload's own directory, and the
// sweep at startup and reset clears it with them.
@@ -633,7 +634,8 @@ public class S3Service implements Resettable, ResourceProvider {
* it in memory in the disk-backed modes. Everything the request alone decides is checked before
* any of the body is read, so a write that cannot succeed fails without transferring it. The body
* is staged on disk with its ETag and checksum worked out as it arrives, then moved into place
* like an assembled multipart object.
* like an assembled multipart object. A body of more than 5 GiB, the most S3 takes in one
* PutObject, fails with EntityTooLarge as soon as it passes that.
*/
S3Object putObject(String bucketName, String key, InputStream body, UploadChecksums checksums,
String contentType, Map<String, String> metadata, PutObjectOptions options) {
@@ -661,7 +663,7 @@ public class S3Service implements Resettable, ResourceProvider {
ChecksumAlgorithm computed = effectiveOptions.getClientChecksum() != null ? null
: declared != null ? declared : ChecksumAlgorithm.CRC64NVME;
DigestingInputStream digests = new DigestingInputStream(body,
digestAlgorithms(checksums, computed));
digestAlgorithms(checksums, computed), MAX_PUT_OBJECT_SIZE);
Path staged = stageBody(digests);
try {
checksums.verify(digests.md5(), digests::checksum);
@@ -2303,6 +2305,28 @@ public class S3Service implements Resettable, ResourceProvider {
// The most one part of a multipart upload can hold, per S3's multipart upload limits.
static final long MAX_PART_SIZE = 5L * 1024 * 1024 * 1024;
// The User Guide's "up to 5 GB" in one PutObject, read as 5 GiB like CopyObject's 5 GB limit;
// a larger object is uploaded in parts.
static final long MAX_PUT_OBJECT_SIZE = 5L * 1024 * 1024 * 1024;
/**
* The message of S3's {@code EntityTooLarge} error as S3 sends it, which is not the wording of the
* error code table's description.
*/
static final String ENTITY_TOO_LARGE_MESSAGE = "Your proposed upload exceeds the maximum allowed size";
/** S3's error for an upload over the most it takes, naming the size proposed and the most allowed. */
static AwsException entityTooLarge(long proposedSize, long maxSizeAllowed) {
return new AwsException("EntityTooLarge", ENTITY_TOO_LARGE_MESSAGE, 400,
Map.of("ProposedSize", proposedSize, "MaxSizeAllowed", maxSizeAllowed));
}
/** The same error for a body that ran past the most allowed before its whole size was known. */
static AwsException entityTooLarge(long maxSizeAllowed) {
return new AwsException("EntityTooLarge", ENTITY_TOO_LARGE_MESSAGE, 400,
Map.of("MaxSizeAllowed", maxSizeAllowed));
}
static void requireCopyableSize(S3Object source) {
if (source.getSize() > MAX_COPY_OBJECT_SOURCE_SIZE) {
throw new AwsException("InvalidRequest",
@@ -3898,7 +3922,9 @@ public class S3Service implements Resettable, ResourceProvider {
* body is staged outside the upload's directory and outside any lock, so parts of one upload still
* arrive in parallel and a slow client never holds up the bucket's other multipart operations. Only
* once it has passed its checks is it moved into the upload and its record published, under the
* upload's lock, so an upload aborted or completed meanwhile fails the part with NoSuchUpload.
* upload's lock, so an upload aborted or completed meanwhile fails the part with NoSuchUpload. A
* body of more than 5 GiB, the most one part holds, fails with EntityTooLarge as soon as it
* passes that.
*/
Part storePart(String bucket, String key, String uploadId, int partNumber, InputStream body,
UploadChecksums checksums,
@@ -3920,7 +3946,7 @@ public class S3Service implements Resettable, ResourceProvider {
}
ChecksumAlgorithm algorithm = declared != null ? declared : ChecksumAlgorithm.CRC64NVME;
DigestingInputStream digests = new DigestingInputStream(body,
digestAlgorithms(checksums, algorithm));
digestAlgorithms(checksums, algorithm), MAX_PART_SIZE);
Path staged = stageBody(digests);
try {
checksums.verify(digests.md5(), digests::checksum);
@@ -3956,19 +3982,36 @@ 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, digestAlgorithms(checksums, null));
// The memory cap is lower than the most S3 takes in one body, so it is the limit here.
DigestingInputStream digests = new DigestingInputStream(body, digestAlgorithms(checksums, null),
Long.MAX_VALUE);
byte[] data = readWithin(digests, MAX_IN_MEMORY_OBJECT_SIZE,
readSoFar -> warnTooLargeForMemory(upload, readSoFar));
checksums.verify(digests.md5(), digests::checksum);
verifyChunkedTrailers(body, digests, checksums);
return data;
}
/**
* Reads all of {@code body} into one array, failing with EntityTooLarge once it passes
* {@code maxSize}, after telling {@code tooLarge} how many bytes it had read by then.
*/
static byte[] readWithin(InputStream body, long maxSize, LongConsumer tooLarge) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[64 * 1024];
try {
for (int read = digests.read(buffer); read >= 0; read = digests.read(buffer)) {
requireFitsInMemory(upload, (long) out.size() + read);
for (int read = body.read(buffer); read >= 0; read = body.read(buffer)) {
long readSoFar = (long) out.size() + read;
if (readSoFar > maxSize) {
tooLarge.accept(readSoFar);
// The rest of the body is not read, so its whole size is not known to name.
throw entityTooLarge(maxSize);
}
out.write(buffer, 0, read);
}
} catch (IOException e) {
throw new UncheckedIOException("Failed to read the upload body", e);
}
checksums.verify(digests.md5(), digests::checksum);
verifyChunkedTrailers(body, digests, checksums);
return out.toByteArray();
}
@@ -4065,8 +4108,7 @@ public class S3Service implements Resettable, ResourceProvider {
copySourceSseCustomerHeaders.keyMd5());
CopySourceRange range = CopySourceRange.parse(copySourceRange, source.getSize());
if (range.length() > MAX_PART_SIZE) {
throw new AwsException("EntityTooLarge",
"Your proposed upload exceeds the maximum allowed object size.", 400);
throw entityTooLarge(range.length(), MAX_PART_SIZE);
}
return storePart(destBucket, destKey, uploadId, partNumber,
new ByteRangeInputStream(read.body(), range.first(), range.length()), UploadChecksums.NONE,
@@ -4261,17 +4303,22 @@ public class S3Service implements Resettable, ResourceProvider {
/**
* Rejects an upload that memory mode could not hold in one byte array, with the error S3 gives an
* object over its size limit, so it fails at the part that crosses the limit instead of running
* the heap out of memory or overflowing the array size at completion.
* object over its size limit, naming the upload's size and the most memory mode holds, so it fails
* at the part that crosses the limit instead of running the heap out of memory or overflowing the
* array size at completion.
*/
private static void requireFitsInMemory(String upload, long uploadSize) {
if (uploadSize > MAX_IN_MEMORY_OBJECT_SIZE) {
LOG.warnv("{0} would hold {1} bytes, over the {2} an object can have in memory storage mode; set FLOCI_STORAGE_SERVICES_S3_MODE=persistent for larger objects",
upload, uploadSize, MAX_IN_MEMORY_OBJECT_SIZE);
throw new AwsException("EntityTooLarge", "Your proposed upload exceeds the maximum allowed object size.", 400);
warnTooLargeForMemory(upload, uploadSize);
throw entityTooLarge(uploadSize, MAX_IN_MEMORY_OBJECT_SIZE);
}
}
private static void warnTooLargeForMemory(String upload, long uploadSize) {
LOG.warnv("{0} would hold {1} bytes, over the {2} an object can have in memory storage mode; set FLOCI_STORAGE_SERVICES_S3_MODE=persistent for larger objects",
upload, uploadSize, MAX_IN_MEMORY_OBJECT_SIZE);
}
/**
* Copies the in-memory bytes of {@code parts}, in order, into one array sized to the total
* upload. The total is measured on the arrays being copied, so it holds whatever the records say.