fix(cloudfront): serve viewer Range GETs (#5377)

A distribution ignored a viewer's Range header: an S3 origin answered
every GET with the whole object and 200, while advertising
Accept-Ranges: bytes, and a custom origin behind a cache or origin
request policy never saw the header, so seeking in a video or resuming
a download read the object from the start.

An S3 origin now serves the one byte range asked for as 206 with its
Content-Range, read from the snapshot GetObject serves, and answers 416
when the range starts past the end of the object. Any other Range gets
the whole object, as CloudFront answers a Range it does not accept and
as S3 does not serve several ranges in one request. A custom origin gets
the viewer's Range and If-Range on every GET or HEAD with a Range
whatever the forwarding settings, as CloudFront forwards a range GET to
the origin and a HEAD can then report the range's length, and its answer
is passed on. A custom error page is served whole.

A Range now applies only while the If-Range sent with it, if any, still
describes the object: a strong ETag equal to the object's, or an
HTTP-date equal to its Last-Modified, matched exactly as RFC 9110
section 13.1.5 requires. Otherwise the whole object is served. This
holds for GetObject, HeadObject and the S3 origin. A presigned URL that
signs Range must also sign an If-Range the request carries, as the S3
User Guide requires.

HeadObject honors Range as the API Reference describes: a satisfiable
range sets Content-Length to the length of the range, leaving out the
whole-object checksum as a ranged GetObject does, and one past the end
answers 416, while a Range that is not one valid range is ignored, as
before. An S3 origin answers a HEAD the same way.

A ranged GetObject is now recorded in CloudTrail like any other, with
the bytes of the range sent, and a range past the end of the object,
for GetObject or HeadObject, is recorded as InvalidRange.

The range parsing GetObject did is now ByteRange, which both use, and
UploadPartCopy's range stream becomes ByteRangeInputStream. GetObject
now matches the range unit in any case, as RFC 9110 section 14.1 has
it, and its InvalidRange error is the one S3 sends, as an AWS-validated
LocalStack capture records it: the message "The requested range is not
satisfiable", with no trailing period, and the RangeRequested and
ActualObjectSize fields.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-10 21:29:02 -05:00
1 parent 7d71df6ac9
commit ff20750d91
18 files changed
+785 -100

No files matched your search

@@ -34,6 +34,7 @@ import java.security.KeyPairGenerator;
import java.security.Signature;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
@@ -424,6 +425,27 @@ class CloudFrontCustomOriginServingTest {
});
}
@Test
void forwardsARangeGetWhateverTheCachePolicyAndPassesThePartialResponse() throws Exception {
byte[] video = randomBytes(1000);
AtomicReference<ReceivedRequest> received = new AtomicReference<>();
startRangeOrigin(video, received);
// CachingDisabled forwards no viewer headers, but CloudFront still forwards a range GET.
Distribution created = cloudFrontService.createDistribution(
customOriginDistribution(policyBehavior(CACHING_DISABLED, null)), Map.of());
Response response = given().header("Host", created.getDomainName())
.header("Range", "bytes=100-199").header("If-Range", "\"v1\"")
.when().get("/video.bin");
assertEquals(206, response.statusCode());
assertEquals("bytes 100-199/1000", response.header("Content-Range"));
assertEquals("100", response.header("Content-Length"));
assertArrayEquals(Arrays.copyOfRange(video, 100, 200), response.asByteArray());
assertEquals("bytes=100-199", received.get().header("Range"));
assertEquals("\"v1\"", received.get().header("If-Range"));
}
@Test
void forwardsTheViewerAuthorizationOnWriteMethodsOnly() throws Exception {
AtomicReference<ReceivedRequest> received = new AtomicReference<>();
@@ -826,6 +848,30 @@ class CloudFrontCustomOriginServingTest {
originServer.start();
}
/** An origin that answers a GET for {@code body} with the one {@code bytes=first-last} range asked for. */
private void startRangeOrigin(byte[] body, AtomicReference<ReceivedRequest> received) throws IOException {
originServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
originServer.createContext("/", exchange -> {
received.set(new ReceivedRequest(exchange.getRequestMethod(), exchange.getRequestURI().getRawPath(),
exchange.getRequestURI().getRawQuery(), exchange.getRequestHeaders(), new byte[0]));
exchange.getResponseHeaders().add("Content-Type", "application/octet-stream");
String range = exchange.getRequestHeaders().getFirst("Range");
if (range == null) {
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
} else {
String[] bounds = range.substring("bytes=".length()).split("-");
int first = Integer.parseInt(bounds[0]);
int last = Integer.parseInt(bounds[1]);
exchange.getResponseHeaders().add("Content-Range", "bytes " + first + "-" + last + "/" + body.length);
exchange.sendResponseHeaders(206, last - first + 1);
exchange.getResponseBody().write(body, first, last - first + 1);
}
exchange.close();
});
originServer.start();
}
/**
* POSTs {@code body} with {@code Transfer-Encoding: chunked} over a raw connection, since an HTTP
* client library buffers a stream it is given and sends its length instead.
@@ -52,6 +52,7 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
class CloudFrontDistributionServingTest {
private static final String REGION = "us-east-1";
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
@Inject
S3Service s3Service;
@@ -283,6 +284,86 @@ class CloudFrontDistributionServingTest {
.header("Content-Length", equalTo(Integer.toString(body.getBytes(StandardCharsets.UTF_8).length)));
}
@Test
void servesTheByteRangeAViewerAsksForFromAnS3Object() {
Distribution dist = alphabetDistribution();
assertRange(dist, "bytes=2-5", "bytes 2-5/26", "cdef");
assertRange(dist, "bytes=20-", "bytes 20-25/26", "uvwxyz");
assertRange(dist, "bytes=-3", "bytes 23-25/26", "xyz");
assertRange(dist, "bytes=-100", "bytes 0-25/26", ALPHABET);
assertRange(dist, "bytes=24-100", "bytes 24-25/26", "yz");
assertRange(dist, "Bytes=2-5", "bytes 2-5/26", "cdef");
// HeadObject: "If the Range is satisfiable, only the ContentLength is affected in the response."
given().header("Host", dist.getDomainName()).header("Range", "bytes=2-5").when().head("/alphabet.txt")
.then().statusCode(200)
.header("Content-Length", equalTo("4"))
.header("Content-Range", nullValue());
}
@Test
void servesTheWholeS3ObjectWhenItsIfRangeNoLongerMatches() {
Distribution dist = alphabetDistribution();
String etag = given().header("Host", dist.getDomainName()).when().head("/alphabet.txt")
.then().extract().header("ETag");
given().header("Host", dist.getDomainName()).header("Range", "bytes=2-5").header("If-Range", etag)
.when().get("/alphabet.txt")
.then().statusCode(206)
.body(equalTo("cdef"));
given().header("Host", dist.getDomainName()).header("Range", "bytes=2-5").header("If-Range", "\"stale\"")
.when().get("/alphabet.txt")
.then().statusCode(200)
.header("Content-Range", nullValue())
.body(equalTo(ALPHABET));
}
@Test
void answersARangePastTheEndOfAnS3ObjectWith416() {
Distribution dist = alphabetDistribution();
for (String range : List.of("bytes=26-", "bytes=100-200", "bytes=-0")) {
given().header("Host", dist.getDomainName()).header("Range", range).when().get("/alphabet.txt")
.then().statusCode(416)
.header("Content-Range", equalTo("bytes */26"))
.body(equalTo("The requested range is not satisfiable"));
given().header("Host", dist.getDomainName()).header("Range", range).when().head("/alphabet.txt")
.then().statusCode(416);
}
}
@Test
void servesTheWholeS3ObjectForARangeHeaderCloudFrontDoesNotAccept() {
Distribution dist = alphabetDistribution();
for (String range : List.of("bytes=5-2", "bytes=0-1,4-5", "bytes=abc", "bytes=-", "items=0-1")) {
given().header("Host", dist.getDomainName()).header("Range", range).when().get("/alphabet.txt")
.then().statusCode(200)
.header("Content-Length", equalTo("26"))
.header("Content-Range", nullValue())
.body(equalTo(ALPHABET));
}
}
@Test
void aViewerRangeIsNotAppliedToTheErrorPageServedInstead() {
String suffix = suffix();
String bucket = "cf-range-error-page-" + suffix;
createBucket(bucket);
putObject(bucket, "index.html", "INDEX-" + suffix, "text/html");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setOrigins(List.of(s3Origin("only-origin", bucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("only-origin"));
cfg.setCustomErrorResponses(List.of(customError(404, 200, "/index.html")));
Distribution dist = cloudFrontService.createDistribution(distribution(cfg), Map.of());
given().header("Host", dist.getDomainName()).header("Range", "bytes=0-1").when().get("/missing/route")
.then().statusCode(200)
.header("Content-Range", nullValue())
.body(equalTo("INDEX-" + suffix));
}
@Test
void returnsErrorPageOriginStatusWhenCustomErrorPageIsMissing() {
// AWS: if the configured custom error page is itself unavailable, CloudFront returns the
@@ -1605,6 +1686,27 @@ class CloudFrontDistributionServingTest {
return new SignerResources(publicKey.getId(), keyGroup.getId());
}
/** A distribution in front of a bucket holding {@code alphabet.txt}, the 26 letters. */
private Distribution alphabetDistribution() {
String bucket = "cf-range-" + suffix();
createBucket(bucket);
putObject(bucket, "alphabet.txt", ALPHABET, "text/plain");
DistributionConfig cfg = new DistributionConfig();
cfg.setEnabled(true);
cfg.setOrigins(List.of(s3Origin("only-origin", bucket)));
cfg.setDefaultCacheBehavior(defaultBehavior("only-origin"));
return cloudFrontService.createDistribution(distribution(cfg), Map.of());
}
private static void assertRange(Distribution dist, String range, String contentRange, String body) {
given().header("Host", dist.getDomainName()).header("Range", range).when().get("/alphabet.txt")
.then().statusCode(206)
.header("Content-Range", equalTo(contentRange))
.header("Content-Length", equalTo(Integer.toString(body.length())))
.header("Accept-Ranges", equalTo("bytes"))
.body(equalTo(body));
}
private void createBucket(String bucket) {
s3Service.createBucket(bucket, REGION);
}
@@ -267,6 +267,22 @@ class CloudFrontOriginRequestBuilderTest {
viewer("GET", null, "Content-Type", "application/json"), nothing), "Content-Type"));
}
@Test
void aRangeReadReachesTheOriginWhateverThePolicy() {
Forwarding nothing = Forwarding.policies(null, null, false);
for (String method : List.of("GET", "HEAD")) {
OriginRequest read = build(viewer(method, null, "Range", "bytes=0-99", "If-Range", "\"v1\""), nothing);
assertEquals("bytes=0-99", value(read, "Range"), method);
assertEquals("\"v1\"", value(read, "If-Range"), method);
}
OriginRequest post = build(viewer("POST", null, "Range", "bytes=0-99"), nothing);
assertNull(value(post, "Range"), "a write follows the forwarding settings");
assertNull(value(build(viewer("GET", null, "If-Range", "\"v1\""), nothing), "If-Range"),
"an If-Range without a Range qualifies nothing");
}
@Test
void hopByHopAndCloudFrontOwnedHeadersAreNeverForwarded() {
OriginRequest request = build(viewer("POST", null,
@@ -13,6 +13,7 @@ import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
@@ -62,6 +63,12 @@ class CloudFrontS3DiskOriginServingTest {
given().header("Host", dist.getDomainName()).when().head("/video.bin")
.then().statusCode(200)
.header("Content-Length", equalTo(Integer.toString(body.length)));
// A range from the middle of the object file.
Response part = given().header("Host", dist.getDomainName())
.header("Range", "bytes=1048576-1048675").when().get("/video.bin");
assertEquals(206, part.statusCode());
assertEquals("bytes 1048576-1048675/" + body.length, part.header("Content-Range"));
assertArrayEquals(Arrays.copyOfRange(body, 1048576, 1048676), part.asByteArray());
// The single-page-app fallback serves its error page through the same stream.
given().header("Host", dist.getDomainName()).when().get("/missing/route")
.then().statusCode(200)
@@ -101,6 +101,16 @@ class CloudTrailIntegrationTest {
headObject(sourceBucket, "documents/hello.txt", 200);
listObjects(sourceBucket);
getObject(sourceBucket, "documents/missing.txt", 404);
// Ranged reads are recorded too, a range that starts past the end of the object as InvalidRange.
given().header("Range", "bytes=0-4")
.when().get("/" + sourceBucket + "/documents/hello.txt")
.then().statusCode(206);
given().header("Range", "bytes=100-")
.when().get("/" + sourceBucket + "/documents/hello.txt")
.then().statusCode(416);
given().header("Range", "bytes=100-")
.when().head("/" + sourceBucket + "/documents/hello.txt")
.then().statusCode(416);
deleteObject(sourceBucket, "documents/hello.txt");
// 6. Force the writer to flush — bypasses the scheduled cadence.
@@ -145,6 +155,7 @@ class CloudTrailIntegrationTest {
+ ":\n" + new String(json));
boolean sawPut = false, sawGet = false, sawDelete = false, sawNoSuchKey = false;
boolean sawRangedGet = false, sawGetInvalidRange = false, sawHeadInvalidRange = false;
for (JsonNode rec : records) {
assertEquals("1.11", rec.path("eventVersion").asText(),
"Bad eventVersion: " + rec);
@@ -164,11 +175,22 @@ class CloudTrailIntegrationTest {
if ("GetObject".equals(name) && rec.path("errorCode").isMissingNode()) sawGet = true;
if ("DeleteObject".equals(name)) sawDelete = true;
if ("NoSuchKey".equals(rec.path("errorCode").asText(null))) sawNoSuchKey = true;
if ("GetObject".equals(name) && rec.path("errorCode").isMissingNode()
&& rec.path("additionalEventData").path("bytesTransferredOut").asLong() == 5) {
sawRangedGet = true;
}
if ("InvalidRange".equals(rec.path("errorCode").asText(null))) {
sawGetInvalidRange |= "GetObject".equals(name);
sawHeadInvalidRange |= "HeadObject".equals(name);
}
}
assertTrue(sawPut, "Expected a PutObject record");
assertTrue(sawGet, "Expected a successful GetObject record");
assertTrue(sawDelete, "Expected a DeleteObject record");
assertTrue(sawNoSuchKey, "Expected a GetObject NoSuchKey record");
assertTrue(sawRangedGet, "Expected a GetObject record of the 5 bytes of a ranged read");
assertTrue(sawGetInvalidRange, "Expected a GetObject InvalidRange record");
assertTrue(sawHeadInvalidRange, "Expected a HeadObject InvalidRange record");
}
@Test
@@ -0,0 +1,134 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.services.s3.ByteRange.Outcome;
import io.github.hectorvent.floci.services.s3.ByteRange.Resolution;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
class ByteRangeTest {
@Test
void aSingleRangeResolvesToItsBytes() {
assertPart("bytes=0-9", 100, 0, 9);
assertPart("bytes=90-", 100, 90, 99);
assertPart("bytes=-10", 100, 90, 99);
assertPart("bytes= 5-6 ", 100, 5, 6);
}
@Test
void theRangeUnitMatchesInAnyCase() {
assertPart("Bytes=0-9", 100, 0, 9);
assertPart("BYTES=90-", 100, 90, 99);
assertOutcome(Outcome.WHOLE, "byte=0-9", 100);
}
@Test
void aByteRangeRunsForwardFromAFirstByteThatExists() {
assertThrows(IllegalArgumentException.class, () -> new ByteRange(5, 2));
assertThrows(IllegalArgumentException.class, () -> new ByteRange(-1, 2));
assertEquals(1, new ByteRange(7, 7).length());
assertEquals("bytes */100", ByteRange.unsatisfiedContentRange(100));
}
@Test
void aRangeRunningPastTheEndStopsAtTheLastByte() {
assertPart("bytes=95-200", 100, 95, 99);
assertPart("bytes=-500", 100, 0, 99);
assertPart("bytes=0-99999999999999999999", 100, 0, 99);
assertPart("bytes=-99999999999999999999", 100, 0, 99);
}
@Test
void offsetsPastTwoGibibytesResolve() {
long size = 3L * 1024 * 1024 * 1024;
ByteRange range = assertPart("bytes=3000000000-3000000009", size, 3_000_000_000L, 3_000_000_009L);
assertEquals(10, range.length());
assertEquals("bytes 3000000000-3000000009/" + size, range.contentRange(size));
}
@Test
void aRangeStartingPastTheEndIsNotSatisfiable() {
for (String header : List.of("bytes=100-", "bytes=100-200", "bytes=-0", "bytes=99999999999999999999-")) {
assertOutcome(Outcome.NOT_SATISFIABLE, header, 100);
}
assertOutcome(Outcome.NOT_SATISFIABLE, "bytes=0-", 0);
assertOutcome(Outcome.NOT_SATISFIABLE, "bytes=0-0", 0);
}
@Test
void anythingButOneValidRangeIsInvalid() {
for (String header : List.of("bytes=5-2", "bytes=0-1,4-5", "bytes=abc", "bytes=-", "bytes=1",
"bytes=--5", "bytes=+1-2", "bytes=")) {
assertOutcome(Outcome.INVALID, header, 100);
}
}
@Test
void noHeaderAnotherUnitOrASuffixOfAnEmptyObjectIsTheWholeObject() {
assertOutcome(Outcome.WHOLE, null, 100);
assertOutcome(Outcome.WHOLE, "items=0-1", 100);
assertOutcome(Outcome.WHOLE, "bytes=-5", 0);
}
@Test
void anIfRangeThatStillDescribesTheObjectLetsTheRangeApply() {
Instant modified = Instant.parse("2015-10-21T07:28:00.250Z");
assertTrue(ByteRange.rangeApplies(null, "\"abc\"", modified));
assertTrue(ByteRange.rangeApplies("\"abc\"", "\"abc\"", modified));
assertTrue(ByteRange.rangeApplies("\"abc-2\"", "\"abc-2\"", modified), "a multipart ETag, whole");
assertTrue(ByteRange.rangeApplies("Wed, 21 Oct 2015 07:28:00 GMT", "\"abc\"", modified),
"Last-Modified, to the second");
}
@Test
void anIfRangeThatNoLongerDescribesTheObjectServesItWhole() {
Instant modified = Instant.parse("2015-10-21T07:28:00.250Z");
assertFalse(ByteRange.rangeApplies("\"old\"", "\"abc\"", modified));
assertFalse(ByteRange.rangeApplies("\"2\"", "\"abc-2\"", modified), "a multipart suffix alone");
assertFalse(ByteRange.rangeApplies("Tue, 20 Oct 2015 07:28:00 GMT", "\"abc\"", modified));
assertFalse(ByteRange.rangeApplies("Thu, 22 Oct 2015 07:28:00 GMT", "\"abc\"", modified),
"a date later than Last-Modified");
for (String malformed : List.of("W/\"abc\"", "abc", "\"", "2015-10-21T07:28:00Z", "")) {
assertFalse(ByteRange.rangeApplies(malformed, "\"abc\"", modified), malformed);
}
}
@Test
void aSliceReadsTheRangeFromAStreamOverTheWholeObject() throws IOException {
byte[] object = "abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.US_ASCII);
ByteRange range = assertPart("bytes=2-5", object.length, 2, 5);
try (InputStream slice = range.slice(new ByteArrayInputStream(object))) {
assertArrayEquals("cdef".getBytes(StandardCharsets.US_ASCII), slice.readAllBytes());
}
}
private static ByteRange assertPart(String header, long size, long first, long last) {
Resolution resolution = ByteRange.resolve(header, size);
assertEquals(Outcome.PART, resolution.outcome(), header);
assertEquals(new ByteRange(first, last), resolution.range(), header);
return resolution.range();
}
private static void assertOutcome(Outcome outcome, String header, long size) {
Resolution resolution = ByteRange.resolve(header, size);
assertEquals(outcome, resolution.outcome(), header + " of " + size + " bytes");
assertNull(resolution.range(), header);
}
}
@@ -201,6 +201,23 @@ class PreSignedUrlFilterTest {
"host;x-amz-meta-signed"));
}
@Test
void requiresIfRangeSignedWhenRangeIsSigned() {
assertEquals(
List.of("if-range"),
PreSignedUrlFilter.unsignedHeadersRequiringSignature(
Set.of("host", "Range", "If-Range"), "host;range"));
assertEquals(
List.of(),
PreSignedUrlFilter.unsignedHeadersRequiringSignature(
Set.of("host", "range", "if-range"), "host;range;if-range"));
assertEquals(
List.of(),
PreSignedUrlFilter.unsignedHeadersRequiringSignature(
Set.of("host", "range", "if-range"), "host"),
"an unsigned Range leaves If-Range unsigned too");
}
@Test
void ignoresHeadersOutsideChecksumFamily() {
assertEquals(
@@ -95,7 +95,8 @@ class S3CopySourceRangeTest {
void aRangeSkipsToAnOffsetPastTwoGibibytes() throws IOException {
CopySourceRange range = new CopySourceRange(2_500_000_000L, 2_500_000_015L);
byte[] data = new CopyRangeInputStream(patternStream(3L * 1024 * 1024 * 1024), range).readAllBytes();
byte[] data = new ByteRangeInputStream(patternStream(3L * 1024 * 1024 * 1024), range.first(), range.length())
.readAllBytes();
assertEquals(16, data.length);
for (int i = 0; i < data.length; i++) {
@@ -119,8 +120,7 @@ class S3CopySourceRangeTest {
byte[] data;
try (FileChannel channel = FileChannel.open(file, StandardOpenOption.READ)) {
data = new CopyRangeInputStream(Channels.newInputStream(channel),
new CopySourceRange(offset, offset + written.length - 1)).readAllBytes();
data = new ByteRangeInputStream(Channels.newInputStream(channel), offset, written.length).readAllBytes();
}
assertArrayEquals(written, data);
@@ -129,9 +129,9 @@ class S3CopySourceRangeTest {
@Test
void aRangeFailsWhenTheSourceEndsBeforeIt() {
assertThrows(IOException.class,
() -> new CopyRangeInputStream(patternStream(10), new CopySourceRange(5, 14)).readAllBytes());
() -> new ByteRangeInputStream(patternStream(10), 5, 10).readAllBytes());
assertThrows(IOException.class,
() -> new CopyRangeInputStream(patternStream(10), new CopySourceRange(12, 14)).readAllBytes(),
() -> new ByteRangeInputStream(patternStream(10), 12, 3).readAllBytes(),
"a source that ends before the range starts");
}
@@ -139,7 +139,7 @@ class S3CopySourceRangeTest {
void aRangeEndsAfterItsLastByteWhateverTheReadSize() throws IOException {
CopySourceRange range = new CopySourceRange(3, 1002);
for (int readSize : List.of(1, 7, 1000, 4096)) {
try (InputStream in = new CopyRangeInputStream(patternStream(5000), range)) {
try (InputStream in = new ByteRangeInputStream(patternStream(5000), range.first(), range.length())) {
ByteArrayOutputStream copied = new ByteArrayOutputStream();
byte[] buffer = new byte[readSize];
for (int read = in.read(buffer); read >= 0; read = in.read(buffer)) {
@@ -1031,6 +1031,108 @@ class S3IntegrationTest {
given().delete("/checksum-mode-head-bucket");
}
@Test
@Order(123)
void getObjectWithARangeUnitInAnyCase() {
putGreeting("range-unit-bucket");
try {
// Range unit names are case-insensitive (RFC 9110, section 14.1).
given()
.header("Range", "Bytes=0-4")
.when()
.get("/range-unit-bucket/greeting.txt")
.then()
.statusCode(206)
.header("Content-Range", equalTo("bytes 0-4/20"))
.body(equalTo("Hello"));
} finally {
deleteGreeting("range-unit-bucket");
}
}
@Test
@Order(124)
void getObjectWithIfRangeServesTheRangeOnlyWhileItsValidatorMatches() {
putGreeting("if-range-bucket");
try {
String etag = given().when().head("/if-range-bucket/greeting.txt").then().extract().header("ETag");
String lastModified = given().when().head("/if-range-bucket/greeting.txt").then().extract()
.header("Last-Modified");
for (String current : List.of(etag, lastModified)) {
given()
.header("Range", "bytes=0-4")
.header("If-Range", current)
.when()
.get("/if-range-bucket/greeting.txt")
.then()
.statusCode(206)
.header("Content-Range", equalTo("bytes 0-4/20"))
.body(equalTo("Hello"));
}
given()
.header("Range", "bytes=0-4")
.header("If-Range", "\"stale\"")
.when()
.get("/if-range-bucket/greeting.txt")
.then()
.statusCode(200)
.header("Content-Range", nullValue())
.header("Content-Length", equalTo("20"));
} finally {
deleteGreeting("if-range-bucket");
}
}
@Test
@Order(125)
void headObjectWithRangeReportsTheRangeLengthOr416() {
putGreeting("head-range-bucket");
try {
// "If the Range is satisfiable, only the ContentLength is affected in the response. If the
// Range is not satisfiable, S3 returns a 416".
given()
.header("Range", "bytes=0-4")
.header("x-amz-checksum-mode", "ENABLED")
.when()
.head("/head-range-bucket/greeting.txt")
.then()
.statusCode(200)
.header("Content-Length", equalTo("5"))
.header("Content-Range", nullValue())
.header("x-amz-checksum-crc64nvme", nullValue())
.header("x-amz-checksum-type", nullValue());
given()
.header("Range", "bytes=0-4")
.header("If-Range", "\"stale\"")
.header("x-amz-checksum-mode", "ENABLED")
.when()
.head("/head-range-bucket/greeting.txt")
.then()
.statusCode(200)
.header("Content-Length", equalTo("20"))
.header("x-amz-checksum-crc64nvme", notNullValue());
given()
.header("Range", "bytes=50-")
.when()
.head("/head-range-bucket/greeting.txt")
.then()
.statusCode(416);
// A Range that is not one valid range is not one that cannot be satisfied, so it is ignored.
for (String invalid : List.of("bytes=0-1,4-5", "bytes=5-2", "bytes=abc")) {
given()
.header("Range", invalid)
.when()
.head("/head-range-bucket/greeting.txt")
.then()
.statusCode(200)
.header("Content-Length", equalTo("20"));
}
} finally {
deleteGreeting("head-range-bucket");
}
}
@Test
@Order(27)
void getObjectWithFullRange() {
@@ -1082,7 +1184,10 @@ class S3IntegrationTest {
.then()
.statusCode(416)
.header("Content-Range", equalTo("bytes */20"))
.body(containsString("InvalidRange"));
.body(hasXPath("/Error/Code", equalTo("InvalidRange")))
.body(hasXPath("/Error/Message", equalTo("The requested range is not satisfiable")))
.body(hasXPath("/Error/RangeRequested", equalTo("bytes=50-100")))
.body(hasXPath("/Error/ActualObjectSize", equalTo("20")));
}
@Test
@@ -3199,6 +3304,17 @@ class S3IntegrationTest {
}
}
/** Creates {@code bucket} holding {@code greeting.txt}, the 20 bytes "Hello World from S3!". */
private static void putGreeting(String bucket) {
given().when().put("/" + bucket).then().statusCode(200);
given().body("Hello World from S3!").when().put("/" + bucket + "/greeting.txt").then().statusCode(200);
}
private static void deleteGreeting(String bucket) {
given().delete("/" + bucket + "/greeting.txt");
given().delete("/" + bucket);
}
private static byte[] alphabetBytes(int size) {
byte[] bytes = new byte[size];
for (int i = 0; i < size; i++) {