feat(s3): read one part of an object with GetObject and HeadObject partNumber (#5569)

GetObject and HeadObject ignored partNumber, so a client reading a
multipart object one part at a time downloaded the whole object for
every part, and never learned how many parts there were. The API
Reference describes partNumber as "effectively" a ranged GET or HEAD
for that part, with x-amz-mp-parts-count "only returned if you specify
partNumber in your request and the object was uploaded as a multipart
upload".

Both now answer partNumber as S3 does in LocalStack's AWS-validated
test_get_object_part, test_get_object_part_checksum and
test_complete_multipart_parts_checksum captures: 206 with the part's
Content-Range and Content-Length, the object's ETag, and
x-amz-mp-parts-count for an object completed from a multipart upload.
An object stored in one request is its own part 1. A part the object
does not have is 416 InvalidPartNumber, naming PartNumberRequested and
ActualPartCount, and partNumber with a Range header is 400
InvalidRequest. A part streams from storage like a range, so the parts
of a large object are read one at a time without holding it.

With checksum mode on, a part of an object with a COMPOSITE checksum
gets that part's own checksum, of type COMPOSITE, and a part that is all
of its object gets the object's checksum; any other part of a
FULL_OBJECT multipart object gets none, as the captures show.

A part number below 1 is 400 InvalidArgument, and one above the part
count, past 10,000 or not, is the 416, as the AWS SDK for Java documents
for partNumber; the 400 carries the wording and fields the captures
record for UploadPart. Part 1 of an empty object succeeds, as the AWS
SDKs' integration tests that download an empty object by part expect,
with no Content-Range, which the CRT client reads only from a part with
bytes, and so with 200, since a 206 must carry one (RFC 9110 15.3.7).

GetObject's ranged response and HeadObject now build their common
headers with GetObject's, given the length served.
This commit is contained in:
Priamo Germosen authored and GitHub committed 2026-10-13 17:46:30 -05:00
1 parent c907eec9d2
commit a88ef42b4b
6 files changed
+725 -29

No files matched your search

@@ -0,0 +1,90 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.s3.model.Part;
import io.github.hectorvent.floci.services.s3.model.S3Object;
import java.io.InputStream;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* The bytes of one part of an object, which GetObject and HeadObject serve for a {@code partNumber}
* as they would a range covering that part. {@code part} is the part's record when the object was
* completed from a multipart upload, and null for an object stored in one request, which is its own
* only part.
*/
record PartRange(long first, long length, Part part) {
/** The message of S3's {@code InvalidPartNumber} error, for a part the object does not have. */
static final String NOT_SATISFIABLE_MESSAGE = "The requested partnumber is not satisfiable";
/** The message of S3's {@code InvalidRequest} error for a request that names a range and a part. */
static final String WITH_RANGE_MESSAGE = "Cannot specify both Range header and partNumber query parameter";
/**
* The part a {@code partNumber} query parameter names, failing with the InvalidArgument S3 gives a part
* number below 1. One above the object's part count, past 10,000 or past what a long holds, names a part
* the object does not have, which is S3's 416 rather than a 400.
*/
static BigInteger parsePartNumber(String value) {
try {
BigInteger partNumber = new BigInteger(value.trim());
if (partNumber.signum() > 0) {
return partNumber;
}
} catch (NumberFormatException ignored) {
// What is not a number is no part number either, so it is rejected the same way.
}
throw new AwsException("InvalidArgument", "Part number must be an integer between 1 and 10000, inclusive",
400, Map.of("ArgumentName", "partNumber", "ArgumentValue", value));
}
/** Part {@code partNumber} of {@code obj}, or empty when the object has no such part. */
static Optional<PartRange> of(S3Object obj, BigInteger partNumber) {
if (!isMultipart(obj)) {
return partNumber.equals(BigInteger.ONE)
? Optional.of(new PartRange(0, obj.getSize(), null))
: Optional.empty();
}
// The parts are kept in the order they were assembled in, so each starts where the last ended.
long first = 0;
for (Part part : obj.getParts()) {
if (partNumber.equals(BigInteger.valueOf(part.getPartNumber()))) {
return Optional.of(new PartRange(first, part.getSize(), part));
}
first += part.getSize();
}
return Optional.empty();
}
/** How many parts {@code obj} has; an object stored in one request has one. */
static int partCount(S3Object obj) {
return isMultipart(obj) ? obj.getParts().size() : 1;
}
private static boolean isMultipart(S3Object obj) {
List<Part> parts = obj.getParts();
return parts != null && !parts.isEmpty();
}
/** Whether this part holds all of an object of {@code size} bytes. */
boolean coversObject(long size) {
return first == 0 && length == size;
}
/**
* The {@code Content-Range} of this part of an object of {@code size} bytes, or null for a part of no
* bytes, which no byte range describes.
*/
String contentRange(long size) {
return length == 0 ? null : new ByteRange(first, first + length - 1).contentRange(size);
}
/** This part's bytes, read from a stream over the whole object as they are needed. */
InputStream slice(InputStream whole) {
return new ByteRangeInputStream(whole, first, length);
}
}
@@ -59,6 +59,7 @@ import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.UncheckedIOException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
@@ -80,6 +81,7 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
@@ -1051,6 +1053,13 @@ public class S3Controller {
}
boolean includeChecksum = "ENABLED".equalsIgnoreCase(resolveHeaderOrQueryParam(checksumMode, uriInfo, "x-amz-checksum-mode"));
String partNumber = uriInfo.getQueryParameters().getFirst("partNumber");
if (partNumber != null) {
Response partResponse = handlePartRequest("GetObject", bucket, key, obj, read.body(),
partNumber, rangeHeader, overrides, includeChecksum);
bodyHandedOff = partResponse.getEntity() instanceof StreamingOutput;
return partResponse;
}
if (ByteRange.inBytes(rangeHeader) && ByteRange.rangeApplies(
httpHeaders.getHeaderString("If-Range"), obj.getETag(), obj.getLastModified())) {
Response rangeResponse = handleRangeRequest(
@@ -1108,8 +1117,15 @@ public class S3Controller {
private Response.ResponseBuilder objectResponseHeaders(Response.ResponseBuilder resp, S3Object obj,
ResponseHeaderOverrides overrides,
boolean includeChecksum) {
return objectResponseHeaders(resp, obj, obj.getSize(), overrides, includeChecksum);
}
/** The same headers for a response carrying {@code contentLength} bytes of the object. */
private Response.ResponseBuilder objectResponseHeaders(Response.ResponseBuilder resp, S3Object obj,
long contentLength, ResponseHeaderOverrides overrides,
boolean includeChecksum) {
resp.header("Content-Type", overrides.contentType() != null ? overrides.contentType() : obj.getContentType())
.header("Content-Length", obj.getSize())
.header("Content-Length", contentLength)
.header("ETag", obj.getETag())
.header("Last-Modified", RFC_822.format(obj.getLastModified()))
.header("Accept-Ranges", "bytes");
@@ -1142,19 +1158,49 @@ public class S3Controller {
in.transferTo(output);
}
};
var resp = Response.status(206)
Response.ResponseBuilder resp = Response.status(206)
.entity(stream)
.header("Content-Type", overrides.contentType() != null ? overrides.contentType() : obj.getContentType())
.header("Content-Length", range.length())
.header("Content-Range", range.contentRange(totalSize))
.header("ETag", obj.getETag())
.header("Last-Modified", RFC_822.format(obj.getLastModified()))
.header("Accept-Ranges", "bytes");
if (obj.getVersionId() != null) {
resp.header("x-amz-version-id", obj.getVersionId());
.header("Content-Range", range.contentRange(totalSize));
return objectResponseHeaders(resp, obj, range.length(), overrides,
includeChecksum && rangeCarriesObjectChecksum(range, obj)).build();
}
/**
* Serves part {@code partNumber} of {@code obj}, as GetObject and HeadObject do for a
* {@code partNumber}: like a range covering that part, with the count of the object's parts when it
* was uploaded in parts. HeadObject passes no {@code body}. A part of no bytes, which no range
* describes, is answered as the whole of an empty object would be.
*/
private Response handlePartRequest(String operation, String bucket, String key, S3Object obj, InputStream body,
String partNumber, String rangeHeader, ResponseHeaderOverrides overrides,
boolean includeChecksum) {
if (rangeHeader != null) {
throw new AwsException("InvalidRequest", PartRange.WITH_RANGE_MESSAGE, 400);
}
appendObjectHeaders(resp, obj, overrides, includeChecksum && rangeCarriesObjectChecksum(range, obj));
return resp.build();
BigInteger requested = PartRange.parsePartNumber(partNumber);
Optional<PartRange> found = PartRange.of(obj, requested);
if (found.isEmpty()) {
emitCloudTrailEvent(operation, bucket, key, 0L, 0L, "InvalidPartNumber", PartRange.NOT_SATISFIABLE_MESSAGE);
return invalidPartNumberResponse(requested, PartRange.partCount(obj));
}
PartRange part = found.get();
emitCloudTrailEvent(operation, bucket, key, 0L, part.length(), null, null);
String contentRange = part.contentRange(obj.getSize());
Function<StreamingOutput, Response> build = stream -> {
Response.ResponseBuilder resp = Response.status(contentRange != null ? 206 : 200).entity(stream);
if (contentRange != null) {
resp.header("Content-Range", contentRange);
}
if (part.part() != null) {
resp.header("x-amz-mp-parts-count", PartRange.partCount(obj));
}
objectResponseHeaders(resp, obj, part.length(), overrides, false);
if (includeChecksum) {
appendChecksumHeaders(resp, partChecksum(obj, part));
}
return resp.build();
};
return body == null ? build.apply(null) : streamingResponse(part.slice(body), build);
}
/**
@@ -1165,12 +1211,41 @@ public class S3Controller {
* ranges get none.
*/
private static boolean rangeCarriesObjectChecksum(ByteRange range, S3Object obj) {
return range.first() == 0 && range.last() == obj.getSize() - 1 && checksumIsOnlyPartsChecksum(obj);
}
/**
* Whether the stored checksum is that of the object's only part: an object stored in one request, or
* completed from one part with a full-object checksum. A composite checksum is never one part's own.
*/
private static boolean checksumIsOnlyPartsChecksum(S3Object obj) {
S3Checksum checksum = obj.getChecksum();
return range.first() == 0 && range.last() == obj.getSize() - 1
&& (obj.getParts() == null || obj.getParts().size() <= 1)
return (obj.getParts() == null || obj.getParts().size() <= 1)
&& checksum != null && checksum.getChecksumType() != ChecksumType.COMPOSITE;
}
/**
* The checksum S3 returns with a part: of an object with a composite checksum, the part's own, which
* the composite is built from, and otherwise the object's when the part is all of the object, as for
* a range covering it.
*/
private static S3Checksum partChecksum(S3Object obj, PartRange part) {
S3Checksum checksum = obj.getChecksum();
if (checksum != null && checksum.getChecksumType() == ChecksumType.COMPOSITE && part.part() != null) {
ChecksumAlgorithm algorithm = checksum.algorithm();
S3Checksum stored = part.part().getChecksum();
String value = algorithm == null || stored == null ? null : stored.valueFor(algorithm);
if (value == null) {
return null;
}
S3Checksum partChecksum = new S3Checksum();
partChecksum.setValueFor(algorithm, value);
partChecksum.setChecksumType(ChecksumType.COMPOSITE);
return partChecksum;
}
return part.coversObject(obj.getSize()) && checksumIsOnlyPartsChecksum(obj) ? checksum : null;
}
private Response websiteObjectResponse(S3Service.ObjectRead read, ResponseHeaderOverrides overrides) {
return fullObjectResponse(read.object(), read.body(), overrides, false);
}
@@ -1191,7 +1266,7 @@ public class S3Controller {
.elem("Message", ByteRange.NOT_SATISFIABLE_MESSAGE)
.elem("RangeRequested", rangeHeader)
.elem("ActualObjectSize", totalSize)
.elem("RequestId", java.util.UUID.randomUUID().toString())
.elem("RequestId", UUID.randomUUID().toString())
.end("Error")
.build();
return Response.status(416)
@@ -1201,6 +1276,21 @@ public class S3Controller {
.build();
}
/** S3's 416 for a part the object does not have, naming the part asked for and how many it has. */
private static Response invalidPartNumberResponse(BigInteger partNumber, int actualPartCount) {
String xml = new XmlBuilder()
.raw("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.start("Error")
.elem("Code", "InvalidPartNumber")
.elem("Message", PartRange.NOT_SATISFIABLE_MESSAGE)
.elem("PartNumberRequested", partNumber.toString())
.elem("ActualPartCount", actualPartCount)
.elem("RequestId", UUID.randomUUID().toString())
.end("Error")
.build();
return Response.status(416).entity(xml).type(MediaType.APPLICATION_XML).build();
}
@HEAD
@Path("/{bucket}/{key:.+}")
public Response headObject(@PathParam("bucket") String bucket,
@@ -1216,7 +1306,7 @@ public class S3Controller {
@HeaderParam("If-None-Match") String ifNoneMatch,
@HeaderParam("If-Modified-Since") String ifModifiedSince,
@HeaderParam("If-Unmodified-Since") String ifUnmodifiedSince,
@HeaderParam("x-amz-checksum-mode") String checksumMode,
@HeaderParam("x-amz-checksum-mode") String checksumModeHeader,
@Context UriInfo uriInfo,
@Context HttpHeaders httpHeaders) {
S3Service.RequestAuthorization authorization = S3Service.RequestAuthorization.unsigned();
@@ -1262,6 +1352,13 @@ public class S3Controller {
return xmlErrorResponse(new AwsException("InvalidRequest",
"Request specific response headers cannot be used for anonymous GET requests.", 400));
}
boolean checksumMode = "ENABLED".equalsIgnoreCase(
resolveHeaderOrQueryParam(checksumModeHeader, uriInfo, "x-amz-checksum-mode"));
String partNumber = uriInfo.getQueryParameters().getFirst("partNumber");
if (partNumber != null) {
return headOnlyResponse(handlePartRequest("HeadObject", bucket, key, obj, null, partNumber,
httpHeaders.getHeaderString("Range"), overrides, checksumMode));
}
// "If the Range is satisfiable, only the ContentLength is affected in the response. If the
// Range is not satisfiable, S3 returns a 416." A Range that is not one valid range is ignored.
long contentLength = obj.getSize();
@@ -1279,19 +1376,9 @@ public class S3Controller {
return headOnlyResponse(invalidRangeResponse(rangeHeader, obj.getSize()));
}
}
var resp = Response.ok()
.header("Content-Type", overrides.contentType() != null ? overrides.contentType() : obj.getContentType())
.header("Content-Length", contentLength)
.header("ETag", obj.getETag())
.header("Last-Modified", RFC_822.format(obj.getLastModified()))
.header("Accept-Ranges", "bytes");
if (obj.getVersionId() != null) {
resp.header("x-amz-version-id", obj.getVersionId());
}
// As on a ranged GetObject, the stored checksum is sent only for a range it describes.
boolean includeChecksum = checksumDescribesRange
&& "ENABLED".equalsIgnoreCase(resolveHeaderOrQueryParam(checksumMode, uriInfo, "x-amz-checksum-mode"));
appendObjectHeaders(resp, obj, overrides, includeChecksum);
Response.ResponseBuilder resp = objectResponseHeaders(Response.ok(), obj, contentLength, overrides,
checksumDescribesRange && checksumMode);
emitCloudTrailEvent("HeadObject", bucket, key, 0L, obj.getSize(), null, null);
return resp.build();
} catch (AwsException e) {
@@ -3472,7 +3559,7 @@ public class S3Controller {
}
}
String xml = xmlBuilder
.elem("RequestId", java.util.UUID.randomUUID().toString())
.elem("RequestId", UUID.randomUUID().toString())
.end("Error")
.build();
return Response.status(e.getHttpStatus()).entity(xml).type(MediaType.APPLICATION_XML).build();