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,52 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class DigestingInputStreamTest {
@Test
void aBodyOfExactlyItsLimitIsReadWhole() throws IOException {
DigestingInputStream body = new DigestingInputStream(
new ByteArrayInputStream("0123456789".getBytes(StandardCharsets.UTF_8)), List.of(), 10);
assertArrayEquals("0123456789".getBytes(StandardCharsets.UTF_8), body.readAllBytes());
assertEquals(10, body.size());
}
@Test
void aBodyThatRunsPastItsLimitIsEntityTooLarge() {
DigestingInputStream body = new DigestingInputStream(
new ByteArrayInputStream("0123456789A".getBytes(StandardCharsets.UTF_8)), List.of(), 10);
AwsException error = assertThrows(AwsException.class, body::readAllBytes);
assertEquals("EntityTooLarge", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("Your proposed upload exceeds the maximum allowed size", error.getMessage());
// Only the bytes read so far are known, so only the limit is named.
assertEquals(Map.of("MaxSizeAllowed", 10L), error.getExtendedData());
}
@Test
void aSingleByteReadPastTheLimitIsEntityTooLarge() throws IOException {
DigestingInputStream body = new DigestingInputStream(
new ByteArrayInputStream("ab".getBytes(StandardCharsets.UTF_8)), List.of(), 1);
assertEquals('a', body.read());
AwsException error = assertThrows(AwsException.class, body::read);
assertEquals("EntityTooLarge", error.getErrorCode());
assertEquals(1, body.size());
}
}
@@ -16,6 +16,10 @@ class S3AwsChunkedIntegrationTest {
private static final String STREAMING_UNSIGNED = "STREAMING-UNSIGNED-PAYLOAD-TRAILER";
private static final String INCOMPLETE_BODY_MESSAGE =
"You did not provide the number of bytes specified by the Content-Length HTTP header.";
private static final String ENTITY_TOO_LARGE_MESSAGE = "Your proposed upload exceeds the maximum allowed size";
// S3 names the size proposed and the most allowed, in this order, between the message and the request id.
private static final String ENTITY_TOO_LARGE_SIZES =
"</Message><ProposedSize>5368709121</ProposedSize><MaxSizeAllowed>5368709120</MaxSizeAllowed><RequestId>";
@Test
void putObject_chunkShorterThanItsDeclaredSize_isIncompleteBodyAndNotStored() {
@@ -301,6 +305,60 @@ class S3AwsChunkedIntegrationTest {
.body(not(containsString("<Part>")));
}
@Test
void putObject_declaringMoreThanFiveGibibytes_isEntityTooLargeAndNotStored() {
String bucket = createBucket("chunked-too-large");
given()
.header("x-amz-content-sha256", STREAMING_UNSIGNED)
.header("Content-Encoding", "aws-chunked")
.header("x-amz-decoded-content-length", "5368709121")
.body("5\r\nhello\r\n0\r\n\r\n")
.when()
.put("/" + bucket + "/object.txt")
.then()
.statusCode(400)
.body(containsString("<Code>EntityTooLarge</Code>"))
.body(containsString("<Message>" + ENTITY_TOO_LARGE_MESSAGE + ENTITY_TOO_LARGE_SIZES));
assertObjectAbsent(bucket, "object.txt");
given()
.header("x-amz-content-sha256", STREAMING_UNSIGNED)
.header("Content-Encoding", "aws-chunked")
.header("x-amz-decoded-content-length", "5")
.body("5\r\nhello\r\n0\r\n\r\n")
.when()
.put("/" + bucket + "/object.txt")
.then()
.statusCode(200);
}
@Test
void uploadPart_declaringMoreThanFiveGibibytes_isEntityTooLargeAndNoPartIsStored() {
String bucket = createBucket("chunked-part-too-large");
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("Content-Encoding", "aws-chunked")
.header("x-amz-decoded-content-length", "5368709121")
.body("5\r\nhello\r\n0\r\n\r\n")
.when()
.put("/" + bucket + "/object.txt?partNumber=1&uploadId=" + uploadId)
.then()
.statusCode(400)
.body(containsString("<Code>EntityTooLarge</Code>"))
.body(containsString("<Message>" + ENTITY_TOO_LARGE_MESSAGE + ENTITY_TOO_LARGE_SIZES));
given()
.when().get("/" + bucket + "/object.txt?uploadId=" + uploadId)
.then().statusCode(200)
.body(not(containsString("<Part>")));
}
@Test
void putObject_chunkedBodyWithoutATrailer_storesTheDecodedPayload() {
String bucket = createBucket("chunked-no-trailer");
@@ -0,0 +1,67 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import jakarta.ws.rs.core.HttpHeaders;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class S3ControllerDeclaredSizeTest {
private static final long LIMIT = S3Service.MAX_PUT_OBJECT_SIZE;
private static final String STREAMING = "STREAMING-UNSIGNED-PAYLOAD-TRAILER";
private static HttpHeaders headers(String contentLength, String decodedContentLength) {
HttpHeaders headers = mock(HttpHeaders.class);
when(headers.getHeaderString("Content-Length")).thenReturn(contentLength);
when(headers.getHeaderString("x-amz-decoded-content-length")).thenReturn(decodedContentLength);
return headers;
}
@Test
void aBodyOverTheLimitIsEntityTooLargeBeforeItIsRead() {
AwsException error = assertThrows(AwsException.class, () -> S3Controller.requireDeclaredSizeWithin(
headers(String.valueOf(LIMIT + 1), null), null, "UNSIGNED-PAYLOAD", LIMIT));
assertEquals("EntityTooLarge", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("Your proposed upload exceeds the maximum allowed size", error.getMessage());
assertEquals(Map.of("ProposedSize", LIMIT + 1, "MaxSizeAllowed", LIMIT), error.getExtendedData());
}
@Test
void aBodyOfExactlyTheLimitIsAccepted() {
assertDoesNotThrow(() -> S3Controller.requireDeclaredSizeWithin(
headers(String.valueOf(LIMIT), null), null, "UNSIGNED-PAYLOAD", LIMIT));
}
@Test
void anAwsChunkedBodyIsMeasuredByItsDecodedLengthNotItsFraming() {
// The framing takes the Content-Length past the limit while the data is exactly the limit.
assertDoesNotThrow(() -> S3Controller.requireDeclaredSizeWithin(
headers(String.valueOf(LIMIT + 4096), String.valueOf(LIMIT)), "aws-chunked", STREAMING, LIMIT));
assertDoesNotThrow(() -> S3Controller.requireDeclaredSizeWithin(
headers(String.valueOf(LIMIT + 4096), String.valueOf(LIMIT)), null, STREAMING, LIMIT));
assertThrows(AwsException.class, () -> S3Controller.requireDeclaredSizeWithin(
headers("100", String.valueOf(LIMIT + 1)), "aws-chunked", STREAMING, LIMIT));
assertThrows(AwsException.class, () -> S3Controller.requireDeclaredSizeWithin(
headers("100", String.valueOf(LIMIT + 1)), "gzip, aws-chunked", "UNSIGNED-PAYLOAD", LIMIT));
}
@Test
void aBodyThatDeclaresNoUsableSizeIsLeftToTheLimitAsItIsRead() {
assertDoesNotThrow(() -> S3Controller.requireDeclaredSizeWithin(
headers(null, null), null, "UNSIGNED-PAYLOAD", LIMIT));
assertDoesNotThrow(() -> S3Controller.requireDeclaredSizeWithin(
headers(String.valueOf(LIMIT + 1), null), "aws-chunked", STREAMING, LIMIT));
assertDoesNotThrow(() -> S3Controller.requireDeclaredSizeWithin(
headers("100", "not-a-size"), "aws-chunked", STREAMING, LIMIT));
}
}
@@ -0,0 +1,150 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
/**
* Uploads sent with {@code Expect: 100-continue} over a raw connection, since an HTTP client library
* hides whether the connection was kept or closed.
*/
@QuarkusTest
class S3ExpectContinueIntegrationTest {
@Test
void putObject_rejectedBeforeItsBodyIsSent_closesTheConnection() throws IOException {
String bucket = createBucket("expect-too-large");
try (Socket socket = connect()) {
send(socket, "PUT /" + bucket + "/big.bin HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Content-Encoding: aws-chunked\r\n"
+ "x-amz-content-sha256: STREAMING-UNSIGNED-PAYLOAD-TRAILER\r\n"
+ "x-amz-decoded-content-length: 5368709121\r\n"
+ "Content-Length: 100\r\n"
+ "Expect: 100-continue\r\n"
+ "\r\n");
ResponseHead head = readHead(socket.getInputStream());
assertEquals(400, head.status());
assertEquals("close", head.header("connection"));
// Reading to the end returns only once Floci closes the connection.
assertThat(readToEnd(socket), containsString("<Code>EntityTooLarge</Code>"));
}
}
@Test
void putObject_toAMissingBucketBeforeItsBodyIsSent_closesTheConnection() throws IOException {
try (Socket socket = connect()) {
send(socket, "PUT /missing-" + UUID.randomUUID() + "/object.txt HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Content-Length: 5\r\n"
+ "Expect: 100-continue\r\n"
+ "\r\n");
ResponseHead head = readHead(socket.getInputStream());
assertEquals(404, head.status());
assertEquals("close", head.header("connection"));
assertThat(readToEnd(socket), containsString("<Code>NoSuchBucket</Code>"));
}
}
@Test
void putObject_whoseBodyIsReadAfterContinue_keepsTheConnection() throws IOException {
String bucket = createBucket("expect-kept");
try (Socket socket = connect()) {
InputStream in = socket.getInputStream();
send(socket, "PUT /" + bucket + "/object.txt HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "Content-Length: 5\r\n"
+ "Expect: 100-continue\r\n"
+ "\r\n");
assertEquals(100, readHead(in).status());
send(socket, "hello");
ResponseHead stored = readHead(in);
assertEquals(200, stored.status());
assertNull(stored.header("connection"));
readBody(in, stored);
send(socket, "GET /" + bucket + "/object.txt HTTP/1.1\r\n"
+ "Host: localhost\r\n"
+ "\r\n");
ResponseHead read = readHead(in);
assertEquals(200, read.status());
assertEquals("hello", readBody(in, read));
}
}
private static Socket connect() throws IOException {
Socket socket = new Socket("localhost", RestAssured.port);
// A connection Floci leaves open fails the read instead of leaving it waiting.
socket.setSoTimeout(10_000);
return socket;
}
private static void send(Socket socket, String text) throws IOException {
OutputStream out = socket.getOutputStream();
out.write(text.getBytes(StandardCharsets.ISO_8859_1));
out.flush();
}
private static ResponseHead readHead(InputStream in) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
int matched = 0;
while (matched < 4) {
int next = in.read();
if (next < 0) {
throw new IOException("connection closed before the response head ended");
}
bytes.write(next);
matched = next == "\r\n\r\n".charAt(matched) ? matched + 1 : (next == '\r' ? 1 : 0);
}
String[] lines = bytes.toString(StandardCharsets.ISO_8859_1).split("\r\n");
Map<String, String> headers = new HashMap<>();
for (int i = 1; i < lines.length; i++) {
int colon = lines[i].indexOf(':');
headers.put(lines[i].substring(0, colon).trim().toLowerCase(Locale.ROOT), lines[i].substring(colon + 1).trim());
}
return new ResponseHead(Integer.parseInt(lines[0].split(" ")[1]), headers);
}
private static String readBody(InputStream in, ResponseHead head) throws IOException {
int length = Integer.parseInt(head.header("content-length"));
return new String(in.readNBytes(length), StandardCharsets.UTF_8);
}
private static String readToEnd(Socket socket) throws IOException {
return new String(socket.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
}
private static String createBucket(String prefix) {
String bucket = prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
given().when().put("/" + bucket).then().statusCode(200);
return bucket;
}
private record ResponseHead(int status, Map<String, String> headers) {
String header(String name) {
return headers.get(name);
}
}
}
@@ -569,7 +569,9 @@ class S3MultipartServiceTest {
assertEquals("EntityTooLarge", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("Your proposed upload exceeds the maximum allowed object size.", error.getMessage());
assertEquals("Your proposed upload exceeds the maximum allowed size", error.getMessage());
assertEquals(Map.of("ProposedSize", (long) Integer.MAX_VALUE, "MaxSizeAllowed", Integer.MAX_VALUE - 8L),
error.getExtendedData());
assertNull(upload.getParts().get(2), "a rejected part is not recorded");
s3Service.uploadPart("test-bucket", "huge.bin", upload.getUploadId(), 1, new byte[16]);
assertEquals(16, upload.getParts().get(1).getSize(), "re-uploading a part replaces its size in the total");
@@ -0,0 +1,46 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class S3ServiceReadWithinTest {
@Test
void aBodyOfExactlyItsLimitIsReadWhole() {
List<Long> tooLarge = new ArrayList<>();
byte[] read = S3Service.readWithin(body("0123456789"), 10, tooLarge::add);
assertArrayEquals("0123456789".getBytes(StandardCharsets.UTF_8), read);
assertTrue(tooLarge.isEmpty());
}
@Test
void aBodyThatRunsPastItsLimitIsEntityTooLargeNamingOnlyTheLimit() {
List<Long> tooLarge = new ArrayList<>();
AwsException error = assertThrows(AwsException.class,
() -> S3Service.readWithin(body("0123456789A"), 10, tooLarge::add));
assertEquals("EntityTooLarge", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("Your proposed upload exceeds the maximum allowed size", error.getMessage());
assertEquals(Map.of("MaxSizeAllowed", 10L), error.getExtendedData());
assertEquals(List.of(11L), tooLarge);
}
private static ByteArrayInputStream body(String text) {
return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8));
}
}
@@ -284,7 +284,9 @@ class S3StreamedUploadTest {
assertEquals("EntityTooLarge", error.getErrorCode());
assertEquals(400, error.getHttpStatus());
assertEquals("Your proposed upload exceeds the maximum allowed object size.", error.getMessage());
assertEquals("Your proposed upload exceeds the maximum allowed size", error.getMessage());
assertEquals(Map.of("ProposedSize", overLimit, "MaxSizeAllowed", S3Service.MAX_PART_SIZE),
error.getExtendedData());
}
assertTrue(s3Service.getMultipartUpload("bucket", "copy.bin", upload.getUploadId()).getParts().isEmpty());
assertNothingStaged();