fix(s3): report EntityTooSmall for a presigned POST below the content-length-range minimum (#5154)

* fix(s3): report EntityTooSmall for a presigned POST below the content-length-range minimum

A browser POST whose body is shorter than the policy's content-length-range
minimum was refused with EntityTooLarge, "Your proposed upload exceeds the
maximum allowed size". Refuse it with EntityTooSmall, "Your proposed upload
is smaller than the minimum allowed object size", S3's documented error for
an upload below the minimum. A body above the maximum still gets
EntityTooLarge.

* fix(s3): match the real S3 wording for an undersized POST

* ci: retrigger

* fix(s3): name the proposed and allowed sizes on a presigned POST size error

S3 answers a presigned POST outside its content-length-range with the
proposed size and the bound it broke: ProposedSize and MinSizeAllowed on
EntityTooSmall, ProposedSize and MaxSizeAllowed on EntityTooLarge, as
LocalStack's AWS-validated test_post_object_policy_validation_size
capture records (tests/aws/services/s3/test_s3.snapshot.json, recorded
2026-02-21). Both errors now carry them, and the S3 error XML renders
MinSizeAllowed next to the two size fields it already did.

The too-large branch now uses the shared EntityTooLarge error from
#5469, whose message has no trailing full stop, as the same capture
shows; the POST path was the one place still sending "...allowed
size.". The too-small error is built next to it.

* fix(s3): fail a presigned POST policy whose content-length-range is not a number

A content-length-range bound that is a string but not a number, such as
["content-length-range", "test", "10"], was read as 0, so the upload was
accepted whenever its size fit the other bound. S3 fails the condition
instead: 403 AccessDenied, "Invalid according to Policy: Policy
Condition failed: ["content-length-range", "test", "10"]", while bounds
written as strings holding numbers, ["content-length-range", "5", "10"],
are accepted (LocalStack's AWS-validated
test_post_object_policy_validation_size capture, recorded 2026-02-21).

Both bounds are now read before any size is compared, and a bound that
is neither a number nor a string holding one fails the condition, quoted
back as JSON. A number too large for a long fails the same way, as the
same digits written as a string already did, instead of wrapping:
18446744073709551615 read as -1 and refused every upload as too large.
The policy-failure message is now built in one place for the eq,
starts-with and exact-match conditions too, their wording unchanged.

The size tests post through one helper instead of repeating the form.

---------

Co-authored-by: Priamo <pgermosen@gmail.com>
This commit is contained in:
jwoa95andPriamo authored and GitHub committed 2026-10-12 08:48:32 -04:00
1 parent fd9bee7499
commit 58bad471f3
3 files changed
+161 -35

No files matched your search

@@ -79,6 +79,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
@@ -3435,10 +3436,10 @@ public class S3Controller {
xmlBuilder.elem("Condition", condition);
}
// S3 InvalidArgument responses carry ArgumentName and ArgumentValue so the SDK can
// surface which input was rejected, and EntityTooLarge the proposed and allowed sizes.
// They travel through AwsException.extendedData.
// surface which input was rejected, and EntityTooSmall and EntityTooLarge the proposed and
// allowed sizes. They travel through AwsException.extendedData.
if (e.getExtendedData() != null) {
for (String sizeField : List.of("ProposedSize", "MaxSizeAllowed")) {
for (String sizeField : List.of("ProposedSize", "MinSizeAllowed", "MaxSizeAllowed")) {
Object size = e.getExtendedData().get(sizeField);
if (size != null) {
xmlBuilder.elem(sizeField, size.toString());
@@ -3855,9 +3856,7 @@ public class S3Controller {
actualValue = fields.get(lookupKey);
}
if (actualValue == null || !actualValue.equals(expectedValue)) {
throw new AwsException("AccessDenied",
"Invalid according to Policy: Policy Condition failed: "
+ "[\"eq\", \"$" + fieldName + "\", \"" + expectedValue + "\"]", 403);
throw policyConditionFailed("[\"eq\", \"$" + fieldName + "\", \"" + expectedValue + "\"]");
}
}
}
@@ -3869,11 +3868,13 @@ public class S3Controller {
}
String operator = condition.get(0).asText().toLowerCase(Locale.ROOT);
if ("content-length-range".equals(operator)) {
long min = condition.get(1).asLong();
long max = condition.get(2).asLong();
if (contentLength < min || contentLength > max) {
throw new AwsException("EntityTooLarge",
"Your proposed upload exceeds the maximum allowed size.", 400);
long min = contentLengthBound(condition, 1);
long max = contentLengthBound(condition, 2);
if (contentLength < min) {
throw S3Service.entityTooSmall(contentLength, min);
}
if (contentLength > max) {
throw S3Service.entityTooLarge(contentLength, max);
}
} else if ("eq".equals(operator)) {
String fieldRef = condition.get(1).asText();
@@ -3881,9 +3882,7 @@ public class S3Controller {
String fieldName = fieldRef.startsWith("$") ? fieldRef.substring(1) : fieldRef;
String actualValue = resolveFieldValue(fieldName.toLowerCase(Locale.ROOT), bucket, fields);
if (actualValue == null || !actualValue.equals(expectedValue)) {
throw new AwsException("AccessDenied",
"Invalid according to Policy: Policy Condition failed: "
+ "[\"eq\", \"$" + fieldName + "\", \"" + expectedValue + "\"]", 403);
throw policyConditionFailed("[\"eq\", \"$" + fieldName + "\", \"" + expectedValue + "\"]");
}
} else if ("starts-with".equals(operator)) {
String fieldRef = condition.get(1).asText();
@@ -3891,13 +3890,45 @@ public class S3Controller {
String fieldName = fieldRef.startsWith("$") ? fieldRef.substring(1) : fieldRef;
String actualValue = resolveFieldValue(fieldName.toLowerCase(Locale.ROOT), bucket, fields);
if (actualValue == null || !actualValue.startsWith(prefix)) {
throw new AwsException("AccessDenied",
"Invalid according to Policy: Policy Condition failed: "
+ "[\"starts-with\", \"$" + fieldName + "\", \"" + prefix + "\"]", 403);
throw policyConditionFailed("[\"starts-with\", \"$" + fieldName + "\", \"" + prefix + "\"]");
}
}
}
/**
* One bound of a content-length-range condition: a number that fits in a long, any fraction dropped,
* or a string holding a whole number that does. Any other bound fails the condition, as S3 answers
* {@code ["content-length-range", "test", "10"]}.
*/
private static long contentLengthBound(JsonNode condition, int index) {
JsonNode bound = condition.get(index);
if (bound.isNumber() && bound.canConvertToLong()) {
return bound.longValue();
}
if (bound.isTextual()) {
try {
return Long.parseLong(bound.textValue());
} catch (NumberFormatException e) {
throw policyConditionFailed(policyConditionText(condition));
}
}
throw policyConditionFailed(policyConditionText(condition));
}
/** A policy condition as S3 quotes it in an error: its elements as JSON, comma-separated. */
private static String policyConditionText(JsonNode condition) {
StringJoiner elements = new StringJoiner(", ", "[", "]");
for (JsonNode element : condition) {
elements.add(element.toString());
}
return elements.toString();
}
private static AwsException policyConditionFailed(String condition) {
return new AwsException("AccessDenied",
"Invalid according to Policy: Policy Condition failed: " + condition, 403);
}
private static String resolveFieldValue(String fieldName, String bucket, Map<String, String> fields) {
if ("bucket".equals(fieldName)) {
return bucket;
@@ -2327,6 +2327,18 @@ public class S3Service implements Resettable, ResourceProvider {
Map.of("MaxSizeAllowed", maxSizeAllowed));
}
/**
* The message of S3's {@code EntityTooSmall} error as S3 sends it, which, like
* {@link #ENTITY_TOO_LARGE_MESSAGE}, is not the wording of the error code table's description.
*/
static final String ENTITY_TOO_SMALL_MESSAGE = "Your proposed upload is smaller than the minimum allowed size";
/** S3's error for an upload under the least it takes, naming the size proposed and the least allowed. */
static AwsException entityTooSmall(long proposedSize, long minSizeAllowed) {
return new AwsException("EntityTooSmall", ENTITY_TOO_SMALL_MESSAGE, 400,
Map.of("ProposedSize", proposedSize, "MinSizeAllowed", minSizeAllowed));
}
static void requireCopyableSize(S3Object source) {
if (source.getSize() > MAX_COPY_OBJECT_SOURCE_SIZE) {
throw new AwsException("InvalidRequest",
@@ -1,6 +1,7 @@
package io.github.hectorvent.floci.services.s3;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
@@ -254,26 +255,87 @@ class S3PresignedPostIntegrationTest {
// Create data that exceeds the max content-length-range of 10 bytes
String fileContent = "This content is definitely longer than 10 bytes";
String policy = buildPolicy(BUCKET, key, "text/plain", 0, 10);
String policyBase64 = Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8));
given()
.multiPart("key", key)
.multiPart("Content-Type", "text/plain")
.multiPart("policy", policyBase64)
.multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
.multiPart("x-amz-credential", "AKIAIOSFODNN7EXAMPLE/20260330/us-east-1/s3/aws4_request")
.multiPart("x-amz-date", AMZ_DATE_FORMAT.format(Instant.now()))
.multiPart("x-amz-signature", "dummysignature")
.multiPart("file", "too-large.txt", fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + BUCKET)
.then()
postTextWithPolicy(key, buildPolicy(BUCKET, key, "text/plain", 0, 10), fileContent)
.statusCode(400)
.contentType("application/xml")
.body(hasXPath("/Error/Code", equalTo("EntityTooLarge")))
.body(hasXPath("/Error/Message", equalTo(
"Your proposed upload exceeds the maximum allowed size.")));
"Your proposed upload exceeds the maximum allowed size")))
.body(hasXPath("/Error/ProposedSize", equalTo(String.valueOf(fileContent.length()))))
.body(hasXPath("/Error/MaxSizeAllowed", equalTo("10")));
}
@Test
@Order(31)
void presignedPostRejectsContentBelowMinimumLength() {
String key = "uploads/too-small.txt";
// 5 bytes, below the min content-length-range of 10 bytes
String fileContent = "12345";
postTextWithPolicy(key, buildPolicy(BUCKET, key, "text/plain", 10, 20), fileContent)
.statusCode(400)
.contentType("application/xml")
.body(hasXPath("/Error/Code", equalTo("EntityTooSmall")))
.body(hasXPath("/Error/Message", equalTo(
"Your proposed upload is smaller than the minimum allowed size")))
.body(hasXPath("/Error/ProposedSize", equalTo("5")))
.body(hasXPath("/Error/MinSizeAllowed", equalTo("10")));
given()
.when()
.head("/" + BUCKET + "/" + key)
.then()
.statusCode(404);
}
@Test
@Order(32)
void presignedPostAcceptsContentLengthRangeWrittenAsStrings() {
String key = "uploads/string-range.txt";
postTextWithPolicy(key, buildPolicy(BUCKET, key, "text/plain", "\"5\", \"10\""), "1234567890")
.statusCode(204);
}
@Test
@Order(33)
void presignedPostRejectsContentLengthRangeThatIsNotANumber() {
String key = "uploads/not-a-number-range.txt";
postTextWithPolicy(key, buildPolicy(BUCKET, key, "text/plain", "\"test\", \"10\""), "1234567890")
.statusCode(403)
.contentType("application/xml")
.body(hasXPath("/Error/Code", equalTo("AccessDenied")))
.body(hasXPath("/Error/Message", equalTo(
"Invalid according to Policy: Policy Condition failed: "
+ "[\"content-length-range\", \"test\", \"10\"]")));
given()
.when()
.head("/" + BUCKET + "/" + key)
.then()
.statusCode(404);
}
@Test
@Order(34)
void presignedPostRejectsContentLengthRangeBoundPastALong() {
String key = "uploads/past-a-long-range.txt";
// 2^64 - 1 would wrap to -1 as a long, refusing every upload as too large.
postTextWithPolicy(key, buildPolicy(BUCKET, key, "text/plain", "0, 18446744073709551615"), "1234567890")
.statusCode(403)
.contentType("application/xml")
.body(hasXPath("/Error/Code", equalTo("AccessDenied")))
.body(hasXPath("/Error/Message", equalTo(
"Invalid according to Policy: Policy Condition failed: "
+ "[\"content-length-range\", 0, 18446744073709551615]")));
given()
.when()
.head("/" + BUCKET + "/" + key)
.then()
.statusCode(404);
}
@Test
@@ -660,6 +722,7 @@ class S3PresignedPostIntegrationTest {
given().delete("/" + BUCKET + "/uploads/no-policy.txt");
given().delete("/" + BUCKET + "/uploads/typed-file.json");
given().delete("/" + BUCKET + "/uploads/within-range.txt");
given().delete("/" + BUCKET + "/uploads/string-range.txt");
given().delete("/" + BUCKET + "/uploads/prefix-test.txt");
given().delete("/" + BUCKET + "/uploads/capital-p-ok.txt");
given().delete("/" + BUCKET + "/uploads/with-metadata.txt");
@@ -671,7 +734,27 @@ class S3PresignedPostIntegrationTest {
.statusCode(204);
}
private ValidatableResponse postTextWithPolicy(String key, String policy, String fileContent) {
String fileName = key.substring(key.lastIndexOf('/') + 1);
return given()
.multiPart("key", key)
.multiPart("Content-Type", "text/plain")
.multiPart("policy", Base64.getEncoder().encodeToString(policy.getBytes(StandardCharsets.UTF_8)))
.multiPart("x-amz-algorithm", "AWS4-HMAC-SHA256")
.multiPart("x-amz-credential", "AKIAIOSFODNN7EXAMPLE/20260330/us-east-1/s3/aws4_request")
.multiPart("x-amz-date", AMZ_DATE_FORMAT.format(Instant.now()))
.multiPart("x-amz-signature", "dummysignature")
.multiPart("file", fileName, fileContent.getBytes(StandardCharsets.UTF_8), "text/plain")
.when()
.post("/" + BUCKET)
.then();
}
private String buildPolicy(String bucket, String key, String contentType, long minSize, long maxSize) {
return buildPolicy(bucket, key, contentType, minSize + ", " + maxSize);
}
private String buildPolicy(String bucket, String key, String contentType, String contentLengthRange) {
String expiration = Instant.now().plusSeconds(3600)
.atZone(ZoneOffset.UTC)
.format(DateTimeFormatter.ISO_INSTANT);
@@ -682,10 +765,10 @@ class S3PresignedPostIntegrationTest {
{"bucket": "%s"},
{"key": "%s"},
{"Content-Type": "%s"},
["content-length-range", %d, %d]
["content-length-range", %s]
]
}
""".formatted(expiration, bucket, key, contentType, minSize, maxSize);
""".formatted(expiration, bucket, key, contentType, contentLengthRange);
}
private String buildStartsWithPolicy(String bucket, String keyPrefix, String contentTypePrefix,