From 3dbbb461610223c7bea9f9d793b9a875e9c3e71a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?TATSUNO=20=E2=80=9CTaz=E2=80=9D=20Yasuhiro?= Date: Wed, 4 Nov 2026 08:45:16 +0900 Subject: [PATCH] perf(s3): speed up in-memory PutObject, GetObject, DeleteObject and ListObjectsV2 (#7386) * perf(s3): cut PutObject work in memory mode A PutObject parsed the bucket's OwnershipControls XML twice and read a 1 KB body through a 64 KB buffer into a growing stream. Bucket now caches the parsed ObjectOwnership until the XML changes. The body is read into an array sized from the declared length, up to 64 MiB, and larger or undeclared bodies keep the growing read. ETag hex uses HexFormat, the event sequencer is written without String.format, and the in-process dataGeneration token comes from a counter instead of SecureRandom. S3Object and Part get copy constructors so a copy no longer allocates collections it drops right away. * perf(s3): list objects without per-key allocation ListObjects filtered the object store through the account-aware wrapper, which built the relative key of every stored entry, and the S3 predicate rebuilt the null-version prefix for each one. The result was then copied, sorted in full and filtered by the continuation token afterwards. The handler asked UriInfo for the query map on each of its 25 subresource checks and formatted LastModified with DateTimeFormatter. AccountAwareStorageBackend gains scanRaw, which hands the stored key to the filter, so ListObjects tests prefixes on it directly. Objects at or before the continuation token are dropped before the sort, and common prefixes at or before it are never collected. S3QueryParams reads the query map once per request for the list, put, get, head and delete handlers. The list handler formats seconds-precision timestamps itself and presizes its XmlBuilder. * perf(s3): serve in-memory GetObject bodies as byte arrays and trim DeleteObject A GetObject in memory mode wrapped its byte array in a StreamingOutput, which resteasy wrote through a blocking Vert.x output stream, formatted Last-Modified with DateTimeFormatter, and resolved the bucket twice. A DeleteObject entered RequestScopes.callAs even when the caller already was the bucket owner, and swept the annotation store for every key. ObjectRead carries the in-memory body, which the handler returns as the entity with the same headers. Last-Modified is written by a small RFC 822 formatter that falls back to the DateTimeFormatter outside four-digit years. The optimistic read reuses the bucket it resolved. DeleteObject runs directly when the store's account is the owner's, and the annotation sweep returns at once when no annotation exists. * perf(s3): decode object keys and read query parameters only when needed The object and list handlers decoded the raw path twice per request and walked its segments even when no ".." could be present, re-wrapped the query map for every trailer, tagging and checksum-mode lookup, lowercased every request header while looking for user metadata, and resolved the MD5 provider by reflection twice per PutObject. URLDecoder runs only when the path carries a percent sign or a plus, and the traversal check returns early without "..". The hot handlers reuse their S3QueryParams for the trailer, tagging, checksum-mode and user metadata lookups, user metadata matching lowercases only the x-amz-meta- names, and MD5 digests are cloned from a prototype. * perf(s3): hash an in-memory PutObject body once and trim the request helpers The memory branch of PutObject now takes the ETag and the stored checksum from the digesting stream, as the disk branch does, instead of hashing the body again under the bucket lock. The controller parses the declared size and resolves the trailer header once per request, skips the CloudTrail event prologue when the account has no trail, reuses one formatted LastModified for objects written in the same second, and checks a key for traversal with a path only when it contains "..". XmlBuilder escapes into its own buffer and appends numbers without a String. S3QueryParams delegates its raw query check to S3RequestParser, which now scans without splitting. The Digests helper hands out MD5 digests cloned from a prototype, so S3Service, S3Object and DigestingInputStream share it. Dead and single-use overloads in S3Controller and S3Service are gone, Part.copyAll replaces two copies of the part list copy, ObjectRead carries the body only once, Bucket derives the ownership flag in its setter, and AccountAwareStorageBackend keeps its existing key concatenations. * perf(s3): bound the query parameter name scan to its own segment The search for "=" ran to the end of the query for every segment without one, so a query of many valueless flags was scanned quadratically. * docs(s3): describe where ObjectRead finds an in-memory body --- .../hectorvent/floci/core/common/Digests.java | 21 +- .../floci/core/common/XmlBuilder.java | 74 ++-- .../storage/AccountAwareStorageBackend.java | 13 + .../cloudtrail/CloudTrailService.java | 5 + .../services/s3/DigestingInputStream.java | 8 +- .../floci/services/s3/S3Controller.java | 343 ++++++++++++------ .../floci/services/s3/S3ObjectKeys.java | 8 +- .../floci/services/s3/S3QueryParams.java | 38 ++ .../floci/services/s3/S3RequestParser.java | 21 +- .../floci/services/s3/S3Service.java | 308 ++++++++-------- .../floci/services/s3/model/Bucket.java | 10 + .../services/s3/model/ChecksumAlgorithm.java | 10 +- .../floci/services/s3/model/Part.java | 22 ++ .../floci/services/s3/model/S3Object.java | 49 ++- .../floci/core/common/DigestsTest.java | 11 + .../s3/S3ControllerTimestampTest.java | 47 +++ .../s3/S3GlobalLegacyListingTest.java | 1 + .../S3LegacyHeaderAccountIntegrationTest.java | 2 + .../services/s3/S3ServiceReadWithinTest.java | 61 ++++ .../services/s3/S3ServiceSequencerTest.java | 19 + .../services/s3/model/S3ObjectCopyTest.java | 105 ++++++ 21 files changed, 857 insertions(+), 319 deletions(-) create mode 100644 src/main/java/io/github/hectorvent/floci/services/s3/S3QueryParams.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/s3/S3ControllerTimestampTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceSequencerTest.java create mode 100644 src/test/java/io/github/hectorvent/floci/services/s3/model/S3ObjectCopyTest.java diff --git a/src/main/java/io/github/hectorvent/floci/core/common/Digests.java b/src/main/java/io/github/hectorvent/floci/core/common/Digests.java index 69a3c27a96..a465315868 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/Digests.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/Digests.java @@ -8,14 +8,29 @@ import java.util.HexFormat; /** Message digests every Java runtime is required to provide, without the checked exception. */ public final class Digests { + private static final MessageDigest MD5 = newDigest("MD5"); + private Digests() { } - public static byte[] md5(byte[] data) { + /** A fresh MD5 digest. Cloning the prototype costs far less than MessageDigest.getInstance. */ + public static MessageDigest md5Digest() { try { - return MessageDigest.getInstance("MD5").digest(data); + return (MessageDigest) MD5.clone(); + } catch (CloneNotSupportedException e) { + return newDigest("MD5"); + } + } + + public static byte[] md5(byte[] data) { + return md5Digest().digest(data); + } + + private static MessageDigest newDigest(String algorithm) { + try { + return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("MD5 is not available", e); + throw new IllegalStateException(algorithm + " is not available", e); } } diff --git a/src/main/java/io/github/hectorvent/floci/core/common/XmlBuilder.java b/src/main/java/io/github/hectorvent/floci/core/common/XmlBuilder.java index a2c3c88119..6e6ccf2688 100644 --- a/src/main/java/io/github/hectorvent/floci/core/common/XmlBuilder.java +++ b/src/main/java/io/github/hectorvent/floci/core/common/XmlBuilder.java @@ -19,7 +19,15 @@ package io.github.hectorvent.floci.core.common; */ public final class XmlBuilder { - private final StringBuilder sb = new StringBuilder(); + private final StringBuilder sb; + + public XmlBuilder() { + this.sb = new StringBuilder(); + } + + public XmlBuilder(int expectedLength) { + this.sb = new StringBuilder(expectedLength); + } /** Opens {@code }. Omits the xmlns attribute when {@code xmlns} is null. */ public XmlBuilder start(String element, String xmlns) { @@ -50,20 +58,22 @@ public final class XmlBuilder { if (value == null) { return this; } - sb.append('<').append(name).append('>') - .append(escape(value)) - .append("'); + sb.append('<').append(name).append('>'); + appendEscaped(sb, value, 0); + sb.append("'); return this; } /** Convenience overload — converts {@code long} to string. */ public XmlBuilder elem(String name, long value) { - return elem(name, String.valueOf(value)); + sb.append('<').append(name).append('>').append(value).append("'); + return this; } /** Convenience overload — converts {@code boolean} to string. */ public XmlBuilder elem(String name, boolean value) { - return elem(name, String.valueOf(value)); + sb.append('<').append(name).append('>').append(value).append("'); + return this; } /** @@ -91,29 +101,41 @@ public final class XmlBuilder { if (s == null || s.isEmpty()) { return ""; } - StringBuilder out = null; int len = s.length(); for (int i = 0; i < len; i++) { - char c = s.charAt(i); - String replacement = switch (c) { - case '&' -> "&"; - case '<' -> "<"; - case '>' -> ">"; - case '"' -> """; - case '\'' -> "'"; - case '\r' -> " "; - default -> null; - }; - if (replacement != null) { - if (out == null) { - out = new StringBuilder(len + 8); - out.append(s, 0, i); - } - out.append(replacement); - } else if (out != null) { - out.append(c); + if (replacement(s.charAt(i)) != null) { + StringBuilder out = new StringBuilder(len + 16); + out.append(s, 0, i); + appendEscaped(out, s, i); + return out.toString(); } } - return out != null ? out.toString() : s; + return s; + } + + /** Appends {@code s} from {@code from} with the XML special characters replaced, in runs. */ + private static void appendEscaped(StringBuilder out, String s, int from) { + int len = s.length(); + int runStart = from; + for (int i = from; i < len; i++) { + String replacement = replacement(s.charAt(i)); + if (replacement != null) { + out.append(s, runStart, i).append(replacement); + runStart = i + 1; + } + } + out.append(s, runStart, len); + } + + private static String replacement(char c) { + return switch (c) { + case '&' -> "&"; + case '<' -> "<"; + case '>' -> ">"; + case '"' -> """; + case '\'' -> "'"; + case '\r' -> " "; + default -> null; + }; } } diff --git a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java index 08ef21a37e..d2429c09d1 100644 --- a/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java +++ b/src/main/java/io/github/hectorvent/floci/core/storage/AccountAwareStorageBackend.java @@ -507,6 +507,19 @@ public class AccountAwareStorageBackend implements StorageBackend return delegate.scan(k -> k.startsWith(prefix) && keyFilter.test(k.substring(prefix.length()))); } + /** + * Scans with a filter that sees the stored key, {@code accountId + "/" + relativeKey}, so a prefix + * test can run without building the relative key. The filter must check the {@code accountId + "/"} + * prefix itself to keep the result to one account. + */ + public List scanRaw(Predicate rawKeyFilter) { + return delegate.scan(rawKeyFilter); + } + + public static String rawKey(String accountId, String key) { + return accountId + "/" + key; + } + /** Returns unprefixed pre-account values that satisfy an ownership predicate. */ public List scanUnscopedLegacy(Predicate legacyOwner) { return delegate.scan(k -> !k.contains("/")).stream() diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java index a8e39dc474..cea928827b 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudtrail/CloudTrailService.java @@ -446,6 +446,11 @@ public class CloudTrailService { } } + /** Whether the current account has a trail, so a caller can skip building an event. */ + public boolean hasTrails() { + return !store.isEmpty(); + } + public void emitS3DataEvent(S3EventInput in) { if (store.isEmpty()) { return; diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/DigestingInputStream.java b/src/main/java/io/github/hectorvent/floci/services/s3/DigestingInputStream.java index 928e8de7ea..f89cb8d247 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/DigestingInputStream.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/DigestingInputStream.java @@ -1,5 +1,6 @@ package io.github.hectorvent.floci.services.s3; +import io.github.hectorvent.floci.core.common.Digests; import io.github.hectorvent.floci.services.s3.model.ChecksumAlgorithm; import io.github.hectorvent.floci.services.s3.model.S3Checksum; @@ -7,7 +8,6 @@ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.util.Collection; import java.util.EnumMap; import java.util.HexFormat; @@ -30,11 +30,7 @@ final class DigestingInputStream extends FilterInputStream { DigestingInputStream(InputStream in, Collection algorithms, long maxSize) { super(in); this.maxSize = maxSize; - try { - this.md5 = MessageDigest.getInstance("MD5"); - } catch (NoSuchAlgorithmException e) { - throw new IllegalStateException("MD5 algorithm is not available", e); - } + this.md5 = Digests.md5Digest(); for (ChecksumAlgorithm algorithm : algorithms) { calculators.put(algorithm, S3Checksum.calculator(algorithm)); } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java index 95adc5c26a..a43696bed8 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Controller.java @@ -68,7 +68,9 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Clock; import java.time.Instant; +import java.time.LocalDateTime; import java.time.ZoneId; +import java.time.ZoneOffset; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.time.temporal.ChronoUnit; @@ -119,12 +121,15 @@ public class S3Controller { Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"); private static final Logger LOG = Logger.getLogger(S3Controller.class); - private static final DateTimeFormatter ISO_FORMAT = DateTimeFormatter + static final DateTimeFormatter ISO_FORMAT = DateTimeFormatter .ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") .withZone(ZoneId.of("UTC")); static final DateTimeFormatter RFC_822 = DateTimeFormatter .ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.US) .withZone(ZoneId.of("GMT")); + private static final String[] DAY_NAMES = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}; + private static final String[] MONTH_NAMES = { + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final S3Service s3Service; @@ -172,6 +177,9 @@ public class S3Controller { private void emitCloudTrailEvent(String eventName, String bucket, String key, long bytesIn, long bytesOut, String errorCode, String errorMessage) { + if (!cloudTrailService.hasTrails()) { + return; + } try { String authHeader = null; String userAgent = null; @@ -608,49 +616,50 @@ public class S3Controller { @Context UriInfo uriInfo, @Context HttpHeaders httpHeaders) { try { + S3QueryParams params = new S3QueryParams(uriInfo); validateRawUri(); S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired( s3Service.isAuthEnforced(), httpHeaders, uriInfo); - if (hasQueryParam(uriInfo, "uploads")) { + if (params.has("uploads")) { s3Service.authorizeBucketRead(bucket, "s3:ListBucketMultipartUploads", authorization); return handleListMultipartUploads(bucket, uriInfo); } - if (hasQueryParam(uriInfo, "notification")) { + if (params.has("notification")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketNotification", authorization); return handleGetBucketNotification(bucket); } - if (hasQueryParam(uriInfo, "versioning")) { + if (params.has("versioning")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketVersioning", authorization); return handleGetBucketVersioning(bucket); } - if (hasQueryParam(uriInfo, "versions")) { + if (params.has("versions")) { s3Service.authorizeBucketRead(bucket, "s3:ListBucketVersions", authorization); return handleListObjectVersions(bucket, prefix, delimiter, maxKeys, keyMarker, versionIdMarker, encodingType); } - if (hasQueryParam(uriInfo, "location")) { + if (params.has("location")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketLocation", authorization); return handleGetBucketLocation(bucket); } - if (hasQueryParam(uriInfo, "tagging")) { + if (params.has("tagging")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketTagging", authorization); return handleGetBucketTagging(bucket); } - if (hasQueryParam(uriInfo, "object-lock")) { + if (params.has("object-lock")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketObjectLockConfiguration", authorization); return handleGetObjectLockConfiguration(bucket); } - if (hasQueryParam(uriInfo, "website")) { + if (params.has("website")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketWebsite", authorization); return handleGetBucketWebsite(bucket); } - if (hasQueryParam(uriInfo, "logging")) { + if (params.has("logging")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketLogging", authorization); return Response.ok(s3Service.getBucketLogging(bucket)) .type("application/xml") .build(); } - if (hasQueryParam(uriInfo, "policyStatus")) { + if (params.has("policyStatus")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketPolicyStatus", authorization); XmlBuilder xml = new XmlBuilder() .raw("") @@ -659,54 +668,54 @@ public class S3Controller { .end("PolicyStatus"); return Response.ok(xml.build()).type(MediaType.APPLICATION_XML).build(); } - if (hasQueryParam(uriInfo, "policy")) { + if (params.has("policy")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketPolicy", authorization); return Response.ok(s3Service.getBucketPolicy(bucket)).build(); } - if (hasQueryParam(uriInfo, "cors")) { + if (params.has("cors")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketCORS", authorization); return Response.ok(s3Service.getBucketCors(bucket)).build(); } - if (hasQueryParam(uriInfo, "lifecycle")) { + if (params.has("lifecycle")) { s3Service.authorizeBucketRead(bucket, "s3:GetLifecycleConfiguration", authorization); S3Service.LifecycleConfigurationResult lc = s3Service.getBucketLifecycle(bucket); return Response.ok(lc.xml()) .header("x-amz-transition-default-minimum-object-size", lc.transitionDefaultMinimumObjectSize()) .build(); } - if (hasQueryParam(uriInfo, "acl")) { + if (params.has("acl")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketAcl", authorization); return Response.ok(s3Service.getBucketAcl(bucket)).build(); } - if (hasQueryParam(uriInfo, "encryption")) { + if (params.has("encryption")) { s3Service.authorizeBucketRead(bucket, "s3:GetEncryptionConfiguration", authorization); return Response.ok(s3Service.getBucketEncryption(bucket)).build(); } - if (hasQueryParam(uriInfo, "publicAccessBlock")) { + if (params.has("publicAccessBlock")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketPublicAccessBlock", authorization); return Response.ok(s3Service.getPublicAccessBlock(bucket)).build(); } - if (hasQueryParam(uriInfo, "ownershipControls")) { + if (params.has("ownershipControls")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketOwnershipControls", authorization); return Response.ok(s3Service.getBucketOwnershipControls(bucket)).build(); } - if (hasQueryParam(uriInfo, "requestPayment")) { + if (params.has("requestPayment")) { s3Service.authorizeBucketRead(bucket, "s3:GetBucketRequestPayment", authorization); return Response.ok(s3Service.getBucketRequestPayment(bucket)).build(); } - if (hasQueryParam(uriInfo, "accelerate")) { + if (params.has("accelerate")) { s3Service.authorizeBucketRead(bucket, "s3:GetAccelerateConfiguration", authorization); return Response.ok(s3Service.getBucketAccelerateConfiguration(bucket)).build(); } - if (hasQueryParam(uriInfo, "replication")) { + if (params.has("replication")) { s3Service.authorizeBucketRead(bucket, "s3:GetReplicationConfiguration", authorization); return Response.ok(s3Service.getBucketReplication(bucket)).build(); } // GetBucketMetricsConfiguration and ListBucketMetricsConfigurations share ?metrics and // are told apart by the id, which only the single-configuration read carries. - if (hasQueryParam(uriInfo, "metrics")) { + if (params.has("metrics")) { s3Service.authorizeBucketRead(bucket, "s3:GetMetricsConfiguration", authorization); - String id = uriInfo.getQueryParameters().getFirst("id"); + String id = params.first("id"); String xml = id != null ? s3Service.getBucketMetricsConfiguration(bucket, id) : s3Service.listBucketMetricsConfigurations(bucket); @@ -715,9 +724,9 @@ public class S3Controller { // GetBucketIntelligentTieringConfiguration and ListBucketIntelligentTieringConfigurations // share ?intelligent-tiering and are told apart by the id, which only the // single-configuration read carries. - if (hasQueryParam(uriInfo, "intelligent-tiering")) { + if (params.has("intelligent-tiering")) { s3Service.authorizeBucketRead(bucket, "s3:GetIntelligentTieringConfiguration", authorization); - String id = uriInfo.getQueryParameters().getFirst("id"); + String id = params.first("id"); String xml = id != null ? s3Service.getBucketIntelligentTieringConfiguration(bucket, id) : s3Service.listBucketIntelligentTieringConfigurations(bucket); @@ -726,9 +735,9 @@ public class S3Controller { // GetBucketAnalyticsConfiguration and ListBucketAnalyticsConfigurations share // ?analytics and are told apart by the id, which only the single-configuration read // carries. - if (hasQueryParam(uriInfo, "analytics")) { + if (params.has("analytics")) { s3Service.authorizeBucketRead(bucket, "s3:GetAnalyticsConfiguration", authorization); - String id = uriInfo.getQueryParameters().getFirst("id"); + String id = params.first("id"); String xml = id != null ? s3Service.getBucketAnalyticsConfiguration(bucket, id) : s3Service.listBucketAnalyticsConfigurations(bucket); @@ -736,9 +745,9 @@ public class S3Controller { } // GetBucketInventoryConfiguration and ListBucketInventoryConfigurations share // ?inventory and are told apart the same way. - if (hasQueryParam(uriInfo, "inventory")) { + if (params.has("inventory")) { s3Service.authorizeBucketRead(bucket, "s3:GetInventoryConfiguration", authorization); - String id = uriInfo.getQueryParameters().getFirst("id"); + String id = params.first("id"); String xml = id != null ? s3Service.getBucketInventoryConfiguration(bucket, id) : s3Service.listBucketInventoryConfigurations(bucket); @@ -768,11 +777,11 @@ public class S3Controller { List objects = result.objects(); List commonPrefixes = result.commonPrefixes(); boolean v2 = "2".equals(listType); - String bucketOwnerAccount = (v1 || Boolean.parseBoolean(uriInfo.getQueryParameters().getFirst("fetch-owner"))) + String bucketOwnerAccount = (v1 || Boolean.parseBoolean(params.first("fetch-owner"))) ? s3Service.getBucketOwnerAccountId(bucket) : null; boolean ownershipEnforced = bucketOwnerAccount != null && s3Service.bucketOwnershipIsEnforced(bucket); - XmlBuilder xml = new XmlBuilder() + XmlBuilder xml = new XmlBuilder(512 + 256 * (objects.size() + commonPrefixes.size())) .raw("") .start("ListBucketResult", AwsNamespaces.S3) .elem("Name", bucket) @@ -783,10 +792,17 @@ public class S3Controller { xml.elem("KeyCount", objects.size() + commonPrefixes.size()); } xml.elem("IsTruncated", result.isTruncated()); + long lastModifiedSecond = Long.MIN_VALUE; + String lastModifiedText = null; for (S3Object obj : objects) { + // Objects written in the same second share one formatted timestamp. + if (obj.getLastModified().getEpochSecond() != lastModifiedSecond) { + lastModifiedSecond = obj.getLastModified().getEpochSecond(); + lastModifiedText = isoSeconds(obj.getLastModified()); + } xml.start("Contents") .elem("Key", maybeEncode(obj.getKey(), encodingType)) - .elem("LastModified", ISO_FORMAT.format(obj.getLastModified())) + .elem("LastModified", lastModifiedText) .elem("ETag", obj.getETag()) .elem("Size", obj.getSize()) .elem("StorageClass", obj.getStorageClass()); @@ -852,6 +868,7 @@ public class S3Controller { @Context HttpHeaders httpHeaders, InputStream body) { try { + S3QueryParams params = new S3QueryParams(uriInfo); key = extractObjectKey(uriInfo, bucket, key); S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired( s3Service.isAuthEnforced(), httpHeaders, uriInfo); @@ -859,16 +876,16 @@ public class S3Controller { // The sub-resource actions are checked as IAM checks them: as their version counterpart // when the request names a version, and offered the tags or Object Lock settings the // body sets. - String versionId = uriInfo.getQueryParameters().getFirst("versionId"); - if (hasQueryParam(uriInfo, "tagging")) { - checkVersionId(bucket, uriInfo); + String versionId = params.first("versionId"); + if (params.has("tagging")) { + checkVersionId(bucket, versionId); byte[] tags = readWholeBody(body); s3Service.authorizeObjectWrite(bucket, key, versionId, "s3:PutObjectTagging", authorization, S3ObjectActions.taggingBodyConditions(new String(tags, StandardCharsets.UTF_8))); return handlePutObjectTagging(bucket, key, versionId, tags); } - if (hasQueryParam(uriInfo, "retention")) { - checkVersionId(bucket, uriInfo); + if (params.has("retention")) { + checkVersionId(bucket, versionId); String retention = new String(readWholeBody(body), StandardCharsets.UTF_8); s3Service.authorizeObjectWrite(bucket, key, null, "s3:PutObjectRetention", authorization, S3ObjectActions.retentionBodyConditions(retention, clock.instant())); @@ -882,16 +899,16 @@ public class S3Controller { } return handlePutObjectRetention(bucket, key, versionId, retention, effectiveBypass(bypass, overrides)); } - if (hasQueryParam(uriInfo, "legal-hold")) { - checkVersionId(bucket, uriInfo); + if (params.has("legal-hold")) { + checkVersionId(bucket, versionId); byte[] legalHold = readWholeBody(body); s3Service.authorizeObjectWrite(bucket, key, null, "s3:PutObjectLegalHold", authorization, S3ObjectActions.legalHoldBodyConditions( new String(legalHold, StandardCharsets.UTF_8), clock.instant())); return handlePutObjectLegalHold(bucket, key, versionId, legalHold); } - if (hasQueryParam(uriInfo, "acl")) { - checkVersionId(bucket, uriInfo); + if (params.has("acl")) { + checkVersionId(bucket, versionId); s3Service.authorizeObjectWrite(bucket, key, versionId, "s3:PutObjectAcl", authorization, null); s3Service.putObjectAcl(bucket, key, versionId, new String(readWholeBody(body), StandardCharsets.UTF_8), @@ -904,8 +921,8 @@ public class S3Controller { return Response.ok().build(); } - if (hasQueryParam(uriInfo, "annotation")) { - checkVersionId(bucket, uriInfo); + if (params.has("annotation")) { + checkVersionId(bucket, versionId); s3Service.authorizeObjectWrite(bucket, key, versionId, "s3:PutObjectAnnotation", authorization, null); return handlePutObjectAnnotation(bucket, key, readWholeBody(body), uriInfo, httpHeaders); } @@ -918,9 +935,10 @@ public class S3Controller { httpHeaders, uriInfo, authorization); } requireDeclaredSizeWithin(httpHeaders, contentEncoding, contentSha256, S3Service.MAX_PART_SIZE); + String trailer = trailerHeader(httpHeaders, params); Part part = s3Service.storePart(bucket, key, uploadId, parsedPartNumber, - decodedBody(body, contentEncoding, contentSha256, trailerHeader(httpHeaders, uriInfo)), - uploadChecksums(httpHeaders, uriInfo), + decodedBody(body, contentEncoding, contentSha256, trailer), + uploadChecksums(httpHeaders, trailer), httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-algorithm"), httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key"), httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-key-MD5")); @@ -928,7 +946,7 @@ public class S3Controller { // S3 echoes the part checksum only when the upload declared an algorithm. ChecksumAlgorithm declared = s3Service.getMultipartUpload(bucket, key, uploadId).getChecksumAlgorithm(); if (declared != null) { - response.header("x-amz-checksum-" + declared.wireValue(), part.getChecksum().valueFor(declared)); + response.header(declared.headerName(), part.getChecksum().valueFor(declared)); } appendSseCustomerHeaders(response, httpHeaders.getHeaderString("x-amz-server-side-encryption-customer-algorithm"), @@ -946,7 +964,7 @@ public class S3Controller { rejectUnimplementedPutConditions(ifMatch, ifNoneMatch); - Map inlineTags = parseInlineTaggingHeader(resolveInlineTaggingSource(tagging, uriInfo)); + Map inlineTags = parseInlineTaggingHeader(resolveInlineTaggingSource(tagging, params.decoded())); ObjectLockHeaders lock = objectLockHeaders(httpHeaders); @@ -962,10 +980,13 @@ public class S3Controller { String cannedAcl = httpHeaders.getHeaderString("x-amz-acl"); authorizeObjectCreation(bucket, key, httpHeaders, uriInfo, false, authorization); authorizeConditionalWriteRead(bucket, key, ifMatch, authorization); - requireDeclaredSizeWithin(httpHeaders, contentEncoding, contentSha256, S3Service.MAX_PUT_OBJECT_SIZE); + long declaredSize = requireDeclaredSizeWithin(httpHeaders, contentEncoding, contentSha256, + S3Service.MAX_PUT_OBJECT_SIZE); + String trailer = trailerHeader(httpHeaders, params); S3Object obj = s3Service.putObject(bucket, key, - decodedBody(body, contentEncoding, contentSha256, trailerHeader(httpHeaders, uriInfo)), - uploadChecksums(httpHeaders, uriInfo), contentType, extractUserMetadata(httpHeaders, uriInfo), + decodedBody(body, contentEncoding, contentSha256, trailer), + uploadChecksums(httpHeaders, trailer), contentType, + extractUserMetadata(httpHeaders, params.decoded()), new PutObjectOptions() .withStorageClass(httpHeaders.getHeaderString("x-amz-storage-class")) .withContentEncoding(persistedEncoding) @@ -989,7 +1010,8 @@ public class S3Controller { .withClientChecksum(extractChecksum(httpHeaders)) .withIfMatch(ifMatch) .withIfNoneMatch(ifNoneMatch) - .withTagging(inlineTags)); + .withTagging(inlineTags), + declaredSize); var resp = Response.ok().header("ETag", obj.getETag()); if (obj.getVersionId() != null) { resp.header("x-amz-version-id", obj.getVersionId()); @@ -1030,6 +1052,7 @@ public class S3Controller { @Context HttpHeaders httpHeaders) { S3Service.RequestAuthorization authorization = S3Service.RequestAuthorization.unsigned(); try { + S3QueryParams params = new S3QueryParams(uriInfo); key = extractObjectKey(uriInfo, bucket, key); authorization = S3RequestAuthorizationParser.parseIfRequired( s3Service.isAuthEnforced(), httpHeaders, uriInfo); @@ -1046,13 +1069,13 @@ public class S3Controller { return handleListParts(bucket, key, uploadId, maxPartsQuery, partNumberMarkerQuery); } - checkVersionId(bucket, uriInfo); - if (hasQueryParam(uriInfo, "tagging")) { + checkVersionId(bucket, params.first("versionId")); + if (params.has("tagging")) { s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectTagging", authorization); return handleGetObjectTagging(bucket, key, versionId); } - if (hasQueryParam(uriInfo, "annotation")) { - String annotationNameParam = uriInfo.getQueryParameters().getFirst("annotationName"); + if (params.has("annotation")) { + String annotationNameParam = params.first("annotationName"); // An empty annotationName is not a Get request for the empty name: it falls // through to ListObjectAnnotations, matching the blank-name put semantics. if (annotationNameParam != null && !annotationNameParam.isEmpty()) { @@ -1062,15 +1085,15 @@ public class S3Controller { s3Service.authorizeObjectRead(bucket, key, versionId, "s3:ListObjectAnnotations", authorization); return handleListObjectAnnotations(bucket, key, uriInfo); } - if (hasQueryParam(uriInfo, "retention")) { + if (params.has("retention")) { s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectRetention", authorization); return handleGetObjectRetention(bucket, key, versionId); } - if (hasQueryParam(uriInfo, "legal-hold")) { + if (params.has("legal-hold")) { s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectLegalHold", authorization); return handleGetObjectLegalHold(bucket, key, versionId); } - if (hasQueryParam(uriInfo, "acl")) { + if (params.has("acl")) { s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAcl", authorization); try { String aclXml = s3Service.getObjectAcl(bucket, key, versionId); @@ -1082,7 +1105,7 @@ public class S3Controller { return xmlErrorResponse(e, bucket); } } - if (hasQueryParam(uriInfo, "attributes")) { + if (params.has("attributes")) { // GetObjectAttributes needs the read beside its own action, as IAM checks it. s3Service.authorizeGetObject(bucket, key, versionId, authorization); s3Service.authorizeObjectRead(bucket, key, versionId, "s3:GetObjectAttributes", authorization); @@ -1123,8 +1146,9 @@ public class S3Controller { "Request specific response headers cannot be used for anonymous GET requests.", 400)); } - boolean includeChecksum = "ENABLED".equalsIgnoreCase(resolveHeaderOrQueryParam(checksumMode, uriInfo, "x-amz-checksum-mode")); - String partNumber = uriInfo.getQueryParameters().getFirst("partNumber"); + boolean includeChecksum = "ENABLED".equalsIgnoreCase( + resolveHeaderOrQueryParam(checksumMode, params.decoded(), "x-amz-checksum-mode")); + String partNumber = params.first("partNumber"); if (partNumber != null) { Response partResponse = handlePartRequest("GetObject", bucket, key, obj, read.body(), partNumber, rangeHeader, overrides, includeChecksum); @@ -1141,7 +1165,7 @@ public class S3Controller { emitCloudTrailEvent("GetObject", bucket, key, 0L, obj.getSize(), null, null); bodyHandedOff = true; - return fullObjectResponse(obj, read.body(), overrides, includeChecksum); + return fullObjectResponse(read, overrides, includeChecksum); } finally { if (!bodyHandedOff) { closeQuietly(read); @@ -1160,6 +1184,15 @@ public class S3Controller { } } + private Response fullObjectResponse(S3Service.ObjectRead read, ResponseHeaderOverrides overrides, + boolean includeChecksum) { + byte[] bytes = read.object().getData(); + if (bytes == null) { + return fullObjectResponse(read.object(), read.body(), overrides, includeChecksum); + } + return objectResponseHeaders(Response.ok(bytes), read.object(), overrides, includeChecksum).build(); + } + /** Streams {@code body}, opened together with {@code obj} by {@link S3Service#openObject}, and closes it. */ private Response fullObjectResponse(S3Object obj, InputStream body, ResponseHeaderOverrides overrides, boolean includeChecksum) { @@ -1199,7 +1232,7 @@ public class S3Controller { resp.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("Last-Modified", rfc822(obj.getLastModified())) .header("Accept-Ranges", "bytes"); if (obj.getVersionId() != null) { resp.header("x-amz-version-id", obj.getVersionId()); @@ -1319,7 +1352,7 @@ public class S3Controller { } private Response websiteObjectResponse(S3Service.ObjectRead read, ResponseHeaderOverrides overrides) { - return fullObjectResponse(read.object(), read.body(), overrides, false); + return fullObjectResponse(read, overrides, false); } private static void closeQuietly(Closeable closeable) { @@ -1383,6 +1416,7 @@ public class S3Controller { @Context HttpHeaders httpHeaders) { S3Service.RequestAuthorization authorization = S3Service.RequestAuthorization.unsigned(); try { + S3QueryParams params = new S3QueryParams(uriInfo); key = extractObjectKey(uriInfo, bucket, key); authorization = S3RequestAuthorizationParser.parseIfRequired( s3Service.isAuthEnforced(), httpHeaders, uriInfo); @@ -1392,11 +1426,11 @@ public class S3Controller { return headOnlyResponse(websiteResponse); } } - checkVersionId(bucket, uriInfo); + checkVersionId(bucket, params.first("versionId")); // HEAD honors the annotation subresource so a HEAD probe reports the same status and // annotation metadata a GET would, instead of falling through to the object's headers. - if (hasQueryParam(uriInfo, "annotation")) { - String annotationNameParam = uriInfo.getQueryParameters().getFirst("annotationName"); + if (params.has("annotation")) { + String annotationNameParam = params.first("annotationName"); // An empty annotationName is not a Get request for the empty name: it falls // through to ListObjectAnnotations, matching the blank-name put semantics. if (annotationNameParam != null && !annotationNameParam.isEmpty()) { @@ -1426,8 +1460,8 @@ public class S3Controller { "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"); + resolveHeaderOrQueryParam(checksumModeHeader, params.decoded(), "x-amz-checksum-mode")); + String partNumber = params.first("partNumber"); if (partNumber != null) { return headOnlyResponse(handlePartRequest("HeadObject", bucket, key, obj, null, partNumber, httpHeaders.getHeaderString("Range"), overrides, checksumMode)); @@ -1548,18 +1582,19 @@ public class S3Controller { @Context UriInfo uriInfo, @Context HttpHeaders httpHeaders) { try { + S3QueryParams params = new S3QueryParams(uriInfo); key = extractObjectKey(uriInfo, bucket, key); S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired( s3Service.isAuthEnforced(), httpHeaders, uriInfo); - if (hasQueryParam(uriInfo, "tagging")) { - checkVersionId(bucket, uriInfo); + if (params.has("tagging")) { + checkVersionId(bucket, params.first("versionId")); s3Service.authorizeObjectWrite(bucket, key, versionId, "s3:DeleteObjectTagging", authorization, null); return withVersionId(Response.noContent(), s3Service.deleteObjectTagging(bucket, key, versionId)) .build(); } - if (hasQueryParam(uriInfo, "annotation")) { - checkVersionId(bucket, uriInfo); + if (params.has("annotation")) { + checkVersionId(bucket, params.first("versionId")); // The user guide: "The BypassGovernanceRetention permission does not apply to annotation // operations", so the bypass header asks for no permission of its own here. boolean bypass = "true".equalsIgnoreCase( @@ -1573,7 +1608,7 @@ public class S3Controller { s3Service.abortMultipartUpload(bucket, key, uploadId); return Response.noContent().build(); } - checkVersionId(bucket, uriInfo); + checkVersionId(bucket, params.first("versionId")); boolean bypass = "true".equalsIgnoreCase( httpHeaders.getHeaderString("x-amz-bypass-governance-retention")); String ifMatch = httpHeaders.getHeaderString("If-Match"); @@ -1709,7 +1744,7 @@ public class S3Controller { } if (hasQueryParam(uriInfo, "restore")) { - checkVersionId(bucket, uriInfo); + checkVersionId(bucket, uriInfo.getQueryParameters().getFirst("versionId")); s3Service.authorizeObjectWrite(bucket, key, "s3:RestoreObject", authorization); s3Service.restoreObject(bucket, key, versionId, new String(body, StandardCharsets.UTF_8)); return Response.accepted().build(); @@ -2469,24 +2504,29 @@ public class S3Controller { * 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. + * number, is held to the limit as it is read. Returns that size, or -1 for none. */ - static void requireDeclaredSizeWithin(HttpHeaders httpHeaders, String contentEncoding, String contentSha256, + static long requireDeclaredSizeWithin(HttpHeaders httpHeaders, String contentEncoding, String contentSha256, long maxSize) { + long size = declaredBodySize(httpHeaders, contentEncoding, contentSha256); + if (size > maxSize) { + throw S3Service.entityTooLarge(size, maxSize); + } + return size; + } + + /** The size the request declares for its body, or -1 when it declares none it can be read as. */ + static long declaredBodySize(HttpHeaders httpHeaders, String contentEncoding, String contentSha256) { boolean awsChunked = declaresStreamingPayload(contentSha256) || namesAwsChunked(contentEncoding); String declared = httpHeaders.getHeaderString(awsChunked ? "x-amz-decoded-content-length" : "Content-Length"); if (declared == null) { - return; + return -1; } - long size; try { - size = Long.parseLong(declared.trim()); + return 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); + // Not a size, so the body is read without one. + return -1; } } @@ -2519,8 +2559,8 @@ public class S3Controller { return size; } - private static String trailerHeader(HttpHeaders httpHeaders, UriInfo uriInfo) { - return resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-trailer"); + private static String trailerHeader(HttpHeaders httpHeaders, S3QueryParams params) { + return resolveHeaderOrQueryParam(httpHeaders.getHeaderString("x-amz-trailer"), params.decoded(), "x-amz-trailer"); } /** The whole of a body that is small by nature, such as a subresource's XML. */ @@ -2874,7 +2914,7 @@ public class S3Controller { .type(MediaType.APPLICATION_OCTET_STREAM) .header("Content-Length", payload.length) .header("ETag", annotation.getETag()) - .header("Last-Modified", RFC_822.format(annotation.getLastModified())); + .header("Last-Modified", rfc822(annotation.getLastModified())); // No Accept-Ranges: range requests are not honored on annotation payloads. if (annotation.getVersionId() != null) { response.header("x-amz-object-version-id", annotation.getVersionId()); @@ -3405,7 +3445,7 @@ public class S3Controller { Response.ResponseBuilder response = Response.ok(xml.build()).type(MediaType.APPLICATION_XML); if (result.getLastModified() != null) { - response.header("Last-Modified", RFC_822.format(result.getLastModified())); + response.header("Last-Modified", rfc822(result.getLastModified())); } if (result.getVersionId() != null) { response.header("x-amz-version-id", result.getVersionId()); @@ -3492,9 +3532,13 @@ public class S3Controller { * with the same key, because the presigned URL signature covers the query value. */ private Map extractUserMetadata(HttpHeaders httpHeaders, UriInfo uriInfo) { + return extractUserMetadata(httpHeaders, uriInfo != null ? uriInfo.getQueryParameters() : null); + } + + private Map extractUserMetadata(HttpHeaders httpHeaders, MultivaluedMap query) { Map metadata = new LinkedHashMap<>(); - if (uriInfo != null) { - addUserMetadata(metadata, uriInfo.getQueryParameters()); + if (query != null) { + addUserMetadata(metadata, query); } addUserMetadata(metadata, httpHeaders.getRequestHeaders()); return metadata; @@ -3502,11 +3546,10 @@ public class S3Controller { private static void addUserMetadata(Map metadata, Map> source) { for (Map.Entry> entry : source.entrySet()) { - String name = entry.getKey().toLowerCase(Locale.ROOT); - if (!name.startsWith("x-amz-meta-")) { + if (!entry.getKey().regionMatches(true, 0, "x-amz-meta-", 0, 11)) { continue; } - String key = name.substring("x-amz-meta-".length()); + String key = entry.getKey().toLowerCase(Locale.ROOT).substring(11); if (!key.isBlank() && !entry.getValue().isEmpty()) { metadata.putIfAbsent(key, entry.getValue().get(0)); } @@ -3515,26 +3558,27 @@ public class S3Controller { static String resolveHeaderOrQueryParam(HttpHeaders httpHeaders, UriInfo uriInfo, String name) { String headerVal = httpHeaders != null ? httpHeaders.getHeaderString(name) : null; - return resolveHeaderOrQueryParam(headerVal, uriInfo, name); + return resolveHeaderOrQueryParam(headerVal, uriInfo != null ? uriInfo.getQueryParameters() : null, name); } - static String resolveHeaderOrQueryParam(String headerValue, UriInfo uriInfo, String name) { + static String resolveHeaderOrQueryParam(String headerValue, MultivaluedMap query, String name) { if (headerValue != null && !headerValue.isBlank()) { return headerValue; } - if (uriInfo != null) { - MultivaluedMap queryParams = uriInfo.getQueryParameters(); - if (queryParams != null) { - String val = queryParams.getFirst(name); - if (val != null && !val.isBlank()) { - return val; - } - for (Map.Entry> entry : queryParams.entrySet()) { - if (entry.getKey().equalsIgnoreCase(name) && !entry.getValue().isEmpty()) { - String v = entry.getValue().get(0); - if (v != null && !v.isBlank()) { - return v; - } + return resolveQueryParam(query, name); + } + + private static String resolveQueryParam(MultivaluedMap queryParams, String name) { + if (queryParams != null) { + String val = queryParams.getFirst(name); + if (val != null && !val.isBlank()) { + return val; + } + for (Map.Entry> entry : queryParams.entrySet()) { + if (entry.getKey().equalsIgnoreCase(name) && !entry.getValue().isEmpty()) { + String v = entry.getValue().get(0); + if (v != null && !v.isBlank()) { + return v; } } } @@ -3583,15 +3627,19 @@ public class S3Controller { } private UploadChecksums uploadChecksums(HttpHeaders httpHeaders, UriInfo uriInfo) { + return uploadChecksums(httpHeaders, resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-trailer")); + } + + private UploadChecksums uploadChecksums(HttpHeaders httpHeaders, String trailer) { Map claimed = new EnumMap<>(ChecksumAlgorithm.class); for (ChecksumAlgorithm algorithm : ChecksumAlgorithm.values()) { - String value = httpHeaders.getHeaderString("x-amz-checksum-" + algorithm.wireValue()); + String value = httpHeaders.getHeaderString(algorithm.headerName()); if (value != null) { claimed.put(algorithm, value); } } return new UploadChecksums(httpHeaders.getHeaderString("Content-MD5"), claimed, - trailerChecksumAlgorithm(resolveHeaderOrQueryParam(httpHeaders, uriInfo, "x-amz-trailer"))); + trailerChecksumAlgorithm(trailer)); } /** The checksum algorithm an {@code x-amz-trailer} value names, as {@code x-amz-checksum-crc32}. */ @@ -3608,12 +3656,61 @@ public class S3Controller { return null; } + static String rfc822(Instant instant) { + LocalDateTime time = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), 0, ZoneOffset.UTC); + int year = time.getYear(); + if (year < 1000 || year > 9999) { + return RFC_822.format(instant); + } + StringBuilder sb = new StringBuilder(29); + sb.append(DAY_NAMES[time.getDayOfWeek().getValue() - 1]).append(", "); + appendTwoDigits(sb, time.getDayOfMonth()); + sb.append(' ').append(MONTH_NAMES[time.getMonthValue() - 1]).append(' '); + appendTwoDigits(sb, year / 100); + appendTwoDigits(sb, year % 100); + sb.append(' '); + appendTwoDigits(sb, time.getHour()); + sb.append(':'); + appendTwoDigits(sb, time.getMinute()); + sb.append(':'); + appendTwoDigits(sb, time.getSecond()); + return sb.append(" GMT").toString(); + } + + static String isoSeconds(Instant instant) { + LocalDateTime time = LocalDateTime.ofEpochSecond(instant.getEpochSecond(), 0, ZoneOffset.UTC); + int year = time.getYear(); + if (year < 1000 || year > 9999) { + return ISO_FORMAT.format(instant); + } + StringBuilder sb = new StringBuilder(20); + appendTwoDigits(sb, year / 100); + appendTwoDigits(sb, year % 100); + sb.append('-'); + appendTwoDigits(sb, time.getMonthValue()); + sb.append('-'); + appendTwoDigits(sb, time.getDayOfMonth()); + sb.append('T'); + appendTwoDigits(sb, time.getHour()); + sb.append(':'); + appendTwoDigits(sb, time.getMinute()); + sb.append(':'); + appendTwoDigits(sb, time.getSecond()); + return sb.append('Z').toString(); + } + + private static void appendTwoDigits(StringBuilder sb, int value) { + sb.append((char) ('0' + value / 10)).append((char) ('0' + value % 10)); + } + static boolean isWebsiteRequest(HttpHeaders httpHeaders, UriInfo uriInfo) { // HTTP/2 (RFC 9113) carries no Host header, so fall back to the request URI authority — // the same resolution S3VirtualHostFilter applies. Without this, a website bucket reached // over HTTP/2 would be served as an API (XML) response instead of website HTML. - String host = S3VirtualHostFilter.resolveHost(httpHeaders.getHeaderString("Host"), - httpHeaders.getHeaderString("X-Forwarded-Host"), uriInfo.getRequestUri()); + String hostHeader = httpHeaders.getHeaderString("Host"); + String host = S3VirtualHostFilter.resolveHost(hostHeader, + httpHeaders.getHeaderString("X-Forwarded-Host"), + hostHeader != null && !hostHeader.isBlank() ? null : uriInfo.getRequestUri()); return host != null && host.contains("s3-website"); } @@ -3825,8 +3922,7 @@ public class S3Controller { * Floci mints every version id as a UUID, so it refuses any other value. The raw query keeps an empty * {@code versionId=}, which a {@code @QueryParam} reads as absent. */ - private void checkVersionId(String bucket, UriInfo uriInfo) { - String versionId = uriInfo.getQueryParameters().getFirst("versionId"); + private void checkVersionId(String bucket, String versionId) { if (versionId == null || "null".equals(versionId) || MINTED_VERSION_ID.matcher(versionId).matches() || !s3Service.bucketExists(bucket)) { return; @@ -3940,7 +4036,7 @@ public class S3Controller { private Response notModifiedResponse(String eTag, Instant lastModified) { return Response.notModified() .header("ETag", eTag) - .header("Last-Modified", RFC_822.format(lastModified)) + .header("Last-Modified", rfc822(lastModified)) .build(); } @@ -4372,10 +4468,14 @@ public class S3Controller { * {@link #parseInlineTaggingHeader(String)} unchanged. Real S3 honors both forms. */ private static String resolveInlineTaggingSource(String taggingHeader, UriInfo uriInfo) { + return resolveInlineTaggingSource(taggingHeader, uriInfo.getQueryParameters()); + } + + private static String resolveInlineTaggingSource(String taggingHeader, MultivaluedMap query) { if (taggingHeader != null) { return taggingHeader; } - return uriInfo.getQueryParameters().getFirst("x-amz-tagging"); + return query.getFirst("x-amz-tagging"); } /** @@ -4452,6 +4552,10 @@ public class S3Controller { private void validateKeyNoTraversal(String key) { if (key == null) return; + // Only a ".." segment can leave the sandbox below, and only NUL makes the key an invalid path. + if (key.indexOf("..") < 0 && key.indexOf('\0') < 0) { + return; + } try { // Use a dummy root to mirror the service pattern, allowing leading slashes but keeping them in sandbox java.nio.file.Path dummyRoot = java.nio.file.Path.of("/s3-sandbox"); @@ -4472,11 +4576,14 @@ public class S3Controller { String rawPath = currentVertxRequest.getCurrent().request().path(); String decodedPath; try { - decodedPath = URLDecoder.decode(rawPath.replace("+", "%2B"), StandardCharsets.UTF_8); + decodedPath = S3ObjectKeys.decodePath(rawPath); } catch (IllegalArgumentException e) { throw new AwsException("BadRequest", null, 400); } + if (decodedPath.indexOf("..") < 0) { + return; + } String[] segments = decodedPath.split("/", -1); int firstKeySegment = decodedPath.startsWith("/") ? 2 : 1; diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectKeys.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectKeys.java index f92dee426b..7eacbd9472 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectKeys.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3ObjectKeys.java @@ -34,13 +34,19 @@ public final class S3ObjectKeys { rawKey = rawPath.substring(prefixIndex + bucketPrefix.length()); } try { - return URLDecoder.decode(rawKey.replace("+", "%2B"), StandardCharsets.UTF_8); + return decodePath(rawKey); } catch (IllegalArgumentException ignored) { // A malformed escape names no key; S3Controller refuses the request as BadRequest. return null; } } + /** Decodes a URL path, skipping the decoder when it holds no escape and no plus. */ + static String decodePath(String raw) { + return raw.indexOf('%') < 0 && raw.indexOf('+') < 0 + ? raw : URLDecoder.decode(raw.replace("+", "%2B"), StandardCharsets.UTF_8); + } + /** * True when the raw request path carries no bucket prefix because the bucket came from the * Host header: the rewritten request URI is then exactly "/" + bucket + rawPath, which is diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3QueryParams.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3QueryParams.java new file mode 100644 index 0000000000..9912f22273 --- /dev/null +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3QueryParams.java @@ -0,0 +1,38 @@ +package io.github.hectorvent.floci.services.s3; + +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.UriInfo; + +/** The query parameters of one request, read from UriInfo once. */ +final class S3QueryParams { + + private final MultivaluedMap decoded; + private final UriInfo uriInfo; + private String rawQuery; + private boolean rawQueryRead; + + S3QueryParams(UriInfo uriInfo) { + this.uriInfo = uriInfo; + this.decoded = uriInfo.getQueryParameters(); + } + + MultivaluedMap decoded() { + return decoded; + } + + boolean has(String name) { + return decoded.containsKey(name) || S3RequestParser.hasQueryParamInString(rawQuery(), name); + } + + String first(String name) { + return decoded.getFirst(name); + } + + private String rawQuery() { + if (!rawQueryRead) { + rawQuery = uriInfo.getRequestUri().getQuery(); + rawQueryRead = true; + } + return rawQuery; + } +} diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestParser.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestParser.java index f92bf92a0a..b7dbee4e96 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestParser.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3RequestParser.java @@ -35,11 +35,22 @@ final class S3RequestParser { * Package-private so unit tests in the same package can call it. */ static boolean hasQueryParamInString(String query, String param) { - if (query == null) return false; - for (String pair : query.split("&")) { - int eq = pair.indexOf('='); - String name = eq >= 0 ? pair.substring(0, eq) : pair; - if (name.equals(param)) return true; + if (query == null) { + return false; + } + int length = query.length(); + int start = 0; + while (start <= length) { + int end = query.indexOf('&', start); + if (end < 0) { + end = length; + } + int eq = query.indexOf('=', start, end); + int nameEnd = eq >= 0 ? eq : end; + if (nameEnd - start == param.length() && query.startsWith(param, start)) { + return true; + } + start = end + 1; } return false; } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java index 2301c2154d..4173ae448a 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3Service.java @@ -140,6 +140,7 @@ public class S3Service implements Resettable, ResourceProvider { private static final Logger LOG = Logger.getLogger(S3Service.class); /** Last {@code s3.object.sequencer} handed out, in microseconds since the epoch. */ private final AtomicLong lastEventSequencer = new AtomicLong(); + private final AtomicLong dataGenerations = new AtomicLong(); record RequestAuthorization(boolean signed, String accessKeyId, String sessionToken) { static RequestAuthorization unsigned() { @@ -746,6 +747,12 @@ public class S3Service implements Resettable, ResourceProvider { */ S3Object putObject(String bucketName, String key, InputStream body, UploadChecksums checksums, String contentType, Map metadata, PutObjectOptions options) { + return putObject(bucketName, key, body, checksums, contentType, metadata, options, -1); + } + + S3Object putObject(String bucketName, String key, InputStream body, UploadChecksums checksums, + String contentType, Map metadata, PutObjectOptions options, + long declaredSize) { requirePublicObjectKey(key); PutObjectOptions effectiveOptions = options != null ? options : new PutObjectOptions(); checksums.requireWellFormedContentMd5(); @@ -761,31 +768,27 @@ public class S3Service implements Resettable, ResourceProvider { ChecksumAlgorithm declared = ChecksumAlgorithm.fromWireValue(effectiveOptions.getChecksumAlgorithm()); // Checked again under the bucket lock when the object is stored; this only spares a transfer. checkWritePreconditions(bucketName, key, effectiveOptions.getIfMatch(), effectiveOptions.getIfNoneMatch()); + // A checksum the client sent is stored as sent; otherwise the declared algorithm's, or CRC64NVME. + ChecksumAlgorithm computed = effectiveOptions.getClientChecksum() != null ? null + : declared != null ? declared : ChecksumAlgorithm.CRC64NVME; if (inMemory) { - byte[] data = readVerified(body, checksums, "PutObject of " + bucketName + "/" + key); - S3Object object = storeObject(checkedBucket, bucketName, key, new BytesBody(data), - contentType, metadata, null, null, effectiveOptions, null); + VerifiedBody verified = readVerified(body, checksums, "PutObject of " + bucketName + "/" + key, + declaredSize, computed); + S3Object object = storeObject(checkedBucket, bucketName, key, new BytesBody(verified.data()), + contentType, metadata, verified.checksum(), null, effectiveOptions, verified.eTag()); fireNotifications(bucketName, key, "ObjectCreated:Put", object); return object; } - // A checksum the client sent is stored as sent; otherwise the declared algorithm's, or CRC64NVME. - ChecksumAlgorithm computed = effectiveOptions.getClientChecksum() != null ? null - : declared != null ? declared : ChecksumAlgorithm.CRC64NVME; DigestingInputStream digests = new DigestingInputStream(body, digestAlgorithms(checksums, computed), MAX_PUT_OBJECT_SIZE); Path staged = stageBody(digests); try { checksums.verify(digests.md5(), digests::checksum); verifyChunkedTrailers(body, digests, checksums); - S3Checksum checksum = null; - if (computed != null) { - checksum = new S3Checksum(); - checksum.setValueFor(computed, digests.checksum(computed)); - checksum.setChecksumType(ChecksumType.FULL_OBJECT); - } S3Object object = storeObject(checkedBucket, bucketName, key, new AssembledBody(staged, digests.size()), - contentType, metadata, checksum, null, effectiveOptions, digests.eTag()); + contentType, metadata, computedChecksum(digests, computed), null, effectiveOptions, + digests.eTag()); fireNotifications(bucketName, key, "ObjectCreated:Put", object); return object; } finally { @@ -944,7 +947,7 @@ public class S3Service implements Resettable, ResourceProvider { : effectiveOptions.getClientChecksum() != null ? copyChecksum(effectiveOptions.getClientChecksum()) : S3Checksum.fullObject(validatedChecksumAlgorithm, data); object.setChecksum(resolvedChecksum); - object.setParts(copyParts(parts)); + object.setParts(Part.copyAll(parts)); object.setContentEncoding(effectiveOptions.getContentEncoding()); object.setContentDisposition(effectiveOptions.getContentDisposition()); object.setCacheControl(effectiveOptions.getCacheControl()); @@ -1077,7 +1080,7 @@ public class S3Service implements Resettable, ResourceProvider { // A fresh per-write token, compared by getObject's optimistic read against a // later re-read of this same field to detect a concurrent overwrite - see the // dataGeneration javadoc on S3Object. - object.setDataGeneration(UUID.randomUUID().toString()); + object.setDataGeneration(nextDataGeneration()); // Write the body before publishing metadata - see the comment in the versioned // branch above; the same ordering requirement applies here. @@ -1106,7 +1109,7 @@ public class S3Service implements Resettable, ResourceProvider { // Annotation readers share this bucket monitor, so they cannot observe the // replacement with the old annotations while cleanup is pending. deleteArchivedNullVersion(bucketOwnerAccount, bucketName, key, false); - deleteAllAnnotationsFor(annotationParentKey(bucketName, key, null)); + deleteAllAnnotationsFor(bucketName, key, null); LOG.debugv("Put object: {0}/{1} ({2} bytes)", bucketName, key, body.size()); } return object; @@ -2016,7 +2019,7 @@ public class S3Service implements Resettable, ResourceProvider { // (the recheck disagreeing with getObjectMetadata about where this key lives) fails loudly // with a clear error instead of spinning forever re-reading the file and exhausting the heap. for (int attempt = 0; attempt < 10_000; attempt++) { - S3Object obj = getObjectMetadata(bucketName, key, versionId); + S3Object obj = copyObject(requireStoredObject(ownedBucket, bucketName, key, versionId)); if (obj.getVersionId() == null && bucket.getVersioningStatus() != null) { synchronized (bucket) { S3Object current = resolveObjectForAccount(bucketOwnerAccount, storeKey).orElse(null); @@ -2060,7 +2063,10 @@ public class S3Service implements Resettable, ResourceProvider { + "metadata/data resolution paths disagree about where this key lives"); } - /** An object's metadata and an open stream over the body that matches it. */ + /** + * An object's metadata and an open stream over the body that matches it. In memory mode the + * object also holds the whole body. + */ public record ObjectRead(S3Object object, InputStream body) implements Closeable { @Override public void close() throws IOException { @@ -2243,12 +2249,18 @@ public class S3Service implements Resettable, ResourceProvider { .orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404)); + return new AccountAwareStorageBackend.OwnedEntry<>(ownedBucket.account(), + requireStoredObject(ownedBucket, bucketName, key, versionId)); + } + + private S3Object requireStoredObject(AccountAwareStorageBackend.OwnedEntry ownedBucket, + String bucketName, String key, String versionId) { S3Object object = findStoredObject(ownedBucket, bucketName, key, versionId) .orElseThrow(() -> versionId != null ? noSuchVersion(key, versionId) : noSuchKey(key)); if (object.isDeleteMarker()) { throw new S3DeleteMarkerException(object); } - return new AccountAwareStorageBackend.OwnedEntry<>(ownedBucket.account(), object); + return object; } private static AwsException noSuchKey(String key) { @@ -2319,7 +2331,7 @@ public class S3Service implements Resettable, ResourceProvider { // AWS lists part-level checksums only for composite objects; a full-object multipart object // reports its part count alone. private GetObjectAttributesParts buildObjectParts(S3Object object, Integer maxParts, Integer partNumberMarker) { - List sortedParts = new ArrayList<>(copyParts(object.getParts())); + List sortedParts = new ArrayList<>(Part.copyAll(object.getParts())); sortedParts.sort(Comparator.comparingInt(Part::getPartNumber)); if (object.getChecksum() == null || object.getChecksum().getChecksumType() != ChecksumType.COMPOSITE) { GetObjectAttributesParts countOnly = new GetObjectAttributesParts(); @@ -2378,12 +2390,17 @@ public class S3Service implements Resettable, ResourceProvider { // annotation subresource writes, which hold the same monitor (storeObjectInternal // already runs under it via storeObject). The precondition is checked under it too, // so a concurrent overwrite cannot land between the check and the delete. - return RequestScopes.callAs(ownedBucket.account(), () -> { + Supplier locked = () -> { synchronized (bucket) { checkDeletePrecondition(bucketName, key, ifMatch); return deleteObjectLocked(bucket, bucketName, key, versionId, bypassGovernance, OBJECT_REMOVED_EVENT); } - }); + }; + if (objectStore instanceof AccountAwareStorageBackend aware + && ownedBucket.account().equals(aware.accountId())) { + return locked.get(); + } + return RequestScopes.callAs(ownedBucket.account(), locked); } /** @@ -2500,7 +2517,7 @@ public class S3Service implements Resettable, ResourceProvider { deleteArchivedNullVersion(ownerId(), bucketName, key, true); objectStore.put(objectKey(bucketName, key), deleteMarker); deleteFile(bucketName, key); - deleteAllAnnotationsFor(annotationParentKey(bucketName, key, null)); + deleteAllAnnotationsFor(bucketName, key, null); LOG.debugv("Created null delete marker: {0}/{1}", bucketName, key); fireNotifications(bucketName, key, removalEvent + ":DeleteMarkerCreated", deleteMarker); return deleteMarker; @@ -2526,8 +2543,7 @@ public class S3Service implements Resettable, ResourceProvider { // Permanently delete a specific version (metadata + file data) objectStore.delete(historyKey); deleteVersionedFile(bucketName, key, versionId); - deleteAllAnnotationsFor(annotationParentKey( - bucketName, key, "null".equals(versionId) ? null : versionId)); + deleteAllAnnotationsFor(bucketName, key, normalizeNullVersionId(versionId)); LOG.debugv("Permanently deleted version: {0}/{1} v={2}", bucketName, key, versionId); // Promote the next most-recent version when the deleted one was the latest String latestKey = objectKey(bucketName, key); @@ -2547,7 +2563,7 @@ public class S3Service implements Resettable, ResourceProvider { .max(WRITE_ORDER) .orElseThrow()); if (newLatest.getVersionId() == null) { - newLatest.setDataGeneration(UUID.randomUUID().toString()); + newLatest.setDataGeneration(nextDataGeneration()); } // The promoted version's body becomes current before its metadata is // published, the order storeObjectInternal writes in, so a concurrent GET @@ -2580,7 +2596,7 @@ public class S3Service implements Resettable, ResourceProvider { deleteArchivedNullVersion(ownerId(), bucketName, key, true); objectStore.delete(objectKey(bucketName, key)); deleteFile(bucketName, key); - deleteAllAnnotationsFor(annotationParentKey(bucketName, key, null)); + deleteAllAnnotationsFor(bucketName, key, null); LOG.debugv("Deleted object: {0}/{1}", bucketName, key); fireNotifications(bucketName, key, removalEvent + ":Delete", null); return null; @@ -2615,6 +2631,8 @@ public class S3Service implements Resettable, ResourceProvider { return listObjectsWithPrefixes(bucketName, prefix, delimiter, maxKeys, null, null); } + private static final Comparator BY_KEY = Comparator.comparing(S3Object::getKey); + public ListObjectsResult listObjectsWithPrefixes(String bucketName, String prefix, String delimiter, int maxKeys, String continuationToken, String startAfter) { String bucketOwnerAccount = resolveBucketEntry(bucketName) @@ -2624,17 +2642,16 @@ public class S3Service implements Resettable, ResourceProvider { String keyPrefix = bucketName + "/"; String fullPrefix = prefix != null ? keyPrefix + prefix : keyPrefix; + List storedObjects = scanCurrentObjects(bucketOwnerAccount, bucketName, fullPrefix); - // Filter out versioned entries (contain #v#) and delete markers - Predicate keyFilter = key -> key.startsWith(fullPrefix) - && !key.contains("#v#") - && !key.startsWith(nullVersionPrefix(bucketName)); - List storedObjects = scanObjectsForAccount(bucketOwnerAccount, keyFilter); - List allObjects = storedObjects - .stream() - .filter(obj -> !obj.isDeleteMarker()) - .toList(); - allObjects = new ArrayList<>(allObjects); + // continuation-token takes precedence; it encodes the last key seen on a previous page. + String filterKey = continuationToken != null ? continuationToken : startAfter; + List allObjects = new ArrayList<>(storedObjects.size()); + for (S3Object obj : storedObjects) { + if (!obj.isDeleteMarker() && (filterKey == null || obj.getKey().compareTo(filterKey) > 0)) { + allObjects.add(obj); + } + } // see https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-prefixes.html List commonPrefixes = List.of(); @@ -2643,22 +2660,12 @@ public class S3Service implements Resettable, ResourceProvider { DelimiterGroups groups = groupByDelimiter(allObjects, prefix, delimiter, S3Object::getKey); allObjects = groups.direct(); commonPrefixes = groups.commonPrefixes(); + if (filterKey != null) { + commonPrefixes.removeIf(cp -> cp.compareTo(filterKey) <= 0); + } } - allObjects.sort(Comparator.comparing(S3Object::getKey)); - - // Apply continuation-token / start-after filter. - // continuation-token takes precedence; it encodes the last key seen on a previous page. - String filterKey = continuationToken != null ? continuationToken : startAfter; - if (filterKey != null) { - final String fk = filterKey; - allObjects = allObjects.stream() - .filter(o -> o.getKey().compareTo(fk) > 0) - .collect(java.util.stream.Collectors.toCollection(ArrayList::new)); - commonPrefixes = commonPrefixes.stream() - .filter(cp -> cp.compareTo(fk) > 0) - .collect(java.util.stream.Collectors.toCollection(ArrayList::new)); - } + allObjects.sort(BY_KEY); // S3 counts both direct objects and common prefixes. // Each common prefix group (e.g. "docs/") uses one entry regardless of @@ -2668,8 +2675,8 @@ public class S3Service implements Resettable, ResourceProvider { boolean isTruncated = false; String nextContinuationToken = null; if (maxKeys >= 0) { - List limitedObjects = new ArrayList<>(); - List limitedPrefixes = new ArrayList<>(); + List limitedObjects = new ArrayList<>(Math.min(maxKeys, allObjects.size())); + List limitedPrefixes = new ArrayList<>(Math.min(maxKeys, commonPrefixes.size())); int count = 0; int directObjectCount = 0; int commonPrefixCount = 0; @@ -2700,6 +2707,25 @@ public class S3Service implements Resettable, ResourceProvider { return new ListObjectsResult(allObjects, commonPrefixes, isTruncated, nextContinuationToken); } + /** The current versions under {@code fullPrefix}: no version history entries and no archived null versions. */ + private List scanCurrentObjects(String bucketOwnerAccount, String bucketName, String fullPrefix) { + String nullPrefix = nullVersionPrefix(bucketName); + if (objectStore instanceof AccountAwareStorageBackend aware) { + @SuppressWarnings("unchecked") + AccountAwareStorageBackend typed = (AccountAwareStorageBackend) aware; + String account = globalBucketNamespace ? bucketOwnerAccount : typed.accountId(); + String rawPrefix = AccountAwareStorageBackend.rawKey(account, fullPrefix); + String rawNullPrefix = AccountAwareStorageBackend.rawKey(account, nullPrefix); + int keyStart = account.length() + 1; + return typed.scanRaw(raw -> raw.startsWith(rawPrefix) + && raw.indexOf("#v#", keyStart) < 0 + && !raw.startsWith(rawNullPrefix)); + } + return objectStore.scan(key -> key.startsWith(fullPrefix) + && !key.contains("#v#") + && !key.startsWith(nullPrefix)); + } + private record DelimiterGroups(List direct, List commonPrefixes) {} private static DelimiterGroups groupByDelimiter(List items, String prefix, String delimiter, @@ -3592,7 +3618,11 @@ public class S3Service implements Resettable, ResourceProvider { } /** Removes every annotation attached to one object version (metadata + payload). */ - private void deleteAllAnnotationsFor(String parentKey) { + private void deleteAllAnnotationsFor(String bucketName, String key, String versionId) { + if (annotationStore.isEmpty()) { + return; + } + String parentKey = annotationParentKey(bucketName, key, versionId); for (ObjectAnnotation annotation : annotationStore.scan(k -> k.startsWith(parentKey + ANNOTATION_SEPARATOR))) { annotationStore.delete(annotationStoreKey(parentKey, annotation.getAnnotationName())); deleteAnnotationPayload(annotation); @@ -4821,7 +4851,7 @@ public class S3Service implements Resettable, ResourceProvider { return upload.getChecksumAlgorithm(); }); if (inMemory) { - byte[] data = readVerified(body, checksums, "Multipart upload " + uploadId); + byte[] data = readVerified(body, checksums, "Multipart upload " + uploadId, -1, null).data(); return storePart(bucket, key, uploadId, partNumber, data, sseCustomerAlgorithm, sseCustomerKey, sseCustomerKeyMd5); } @@ -4862,15 +4892,30 @@ public class S3Service implements Resettable, ResourceProvider { * Reads a memory-mode upload body into one array, checked against {@code checksums}, failing * with EntityTooLarge once it outgrows the largest array the JDK allocates. */ - private static byte[] readVerified(InputStream body, UploadChecksums checksums, String upload) { + /** A body read whole, with its ETag and stored checksum taken from the same pass over the bytes. */ + private record VerifiedBody(byte[] data, String eTag, S3Checksum checksum) { } + + private static VerifiedBody readVerified(InputStream body, UploadChecksums checksums, String upload, + long declaredSize, ChecksumAlgorithm computed) { // 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), + DigestingInputStream digests = new DigestingInputStream(body, digestAlgorithms(checksums, computed), Long.MAX_VALUE); - byte[] data = readWithin(digests, MAX_IN_MEMORY_OBJECT_SIZE, + byte[] data = readWithin(digests, MAX_IN_MEMORY_OBJECT_SIZE, declaredSize, readSoFar -> warnTooLargeForMemory(upload, readSoFar)); checksums.verify(digests.md5(), digests::checksum); verifyChunkedTrailers(body, digests, checksums); - return data; + return new VerifiedBody(data, digests.eTag(), computedChecksum(digests, computed)); + } + + /** The full object checksum of {@code computed} from the stream, or null when the client's is stored. */ + private static S3Checksum computedChecksum(DigestingInputStream digests, ChecksumAlgorithm computed) { + if (computed == null) { + return null; + } + S3Checksum checksum = new S3Checksum(); + checksum.setValueFor(computed, digests.checksum(computed)); + checksum.setChecksumType(ChecksumType.FULL_OBJECT); + return checksum; } /** @@ -4878,7 +4923,46 @@ public class S3Service implements Resettable, ResourceProvider { * {@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(); + return readWithin(body, maxSize, -1, tooLarge); + } + + private static final long MAX_EXACT_READ = 64L * 1024 * 1024; + + /** + * Like {@link #readWithin(InputStream, long, LongConsumer)}, sizing the array from the length the + * request declared. A body shorter or longer than declared is still read in full. + */ + static byte[] readWithin(InputStream body, long maxSize, long declaredSize, LongConsumer tooLarge) { + if (declaredSize < 0 || declaredSize > maxSize || declaredSize > MAX_EXACT_READ) { + return readGrowing(body, maxSize, declaredSize, new byte[0], tooLarge); + } + byte[] exact = new byte[(int) declaredSize]; + try { + int filled = body.readNBytes(exact, 0, exact.length); + if (filled < exact.length) { + return Arrays.copyOf(exact, filled); + } + int extra = body.read(); + if (extra < 0) { + return exact; + } + byte[] prefix = Arrays.copyOf(exact, exact.length + 1); + prefix[exact.length] = (byte) extra; + return readGrowing(body, maxSize, declaredSize, prefix, tooLarge); + } catch (IOException e) { + throw new UncheckedIOException("Failed to read the upload body", e); + } + } + + private static byte[] readGrowing(InputStream body, long maxSize, long declaredSize, byte[] prefix, + LongConsumer tooLarge) { + if (prefix.length > maxSize) { + tooLarge.accept(prefix.length); + throw entityTooLarge(maxSize); + } + int initial = declaredSize >= 0 ? (int) Math.min(declaredSize, 1024 * 1024) : 32; + ByteArrayOutputStream out = new ByteArrayOutputStream(Math.max(initial, prefix.length)); + out.write(prefix, 0, prefix.length); byte[] buffer = new byte[64 * 1024]; try { for (int read = body.read(buffer); read >= 0; read = body.read(buffer)) { @@ -5147,9 +5231,7 @@ public class S3Service implements Resettable, ResourceProvider { // Both checksum types come from the stored part checksums, so a mismatch is rejected // before any part is read. - List completedParts = parts.stream() - .map(S3Service::copyPart) - .toList(); + List completedParts = Part.copyAll(parts); S3Checksum checksum = storedChecksumType == ChecksumType.COMPOSITE ? S3Checksum.composite(algorithm, completedParts.stream() .map(part -> part.getChecksum().valueFor(algorithm)).toList()) @@ -6303,16 +6385,15 @@ public class S3Service implements Resettable, ResourceProvider { } private static boolean ownershipIsEnforced(Bucket bucket) { - return XmlParser.containsValue(bucket.getOwnershipControlsConfiguration(), - "ObjectOwnership", "BucketOwnerEnforced"); + return bucket.isObjectOwnershipEnforced(); } private static String objectOwnerAccount(Bucket bucket, String bucketOwnerAccount, String writerAccount, String cannedAcl) { String controls = bucket.getOwnershipControlsConfiguration(); if (ownershipIsEnforced(bucket) - || (XmlParser.containsValue(controls, "ObjectOwnership", "BucketOwnerPreferred") - && "bucket-owner-full-control".equals(cannedAcl))) { + || ("bucket-owner-full-control".equals(cannedAcl) + && XmlParser.containsValue(controls, "ObjectOwnership", "BucketOwnerPreferred"))) { return bucketOwnerAccount; } return writerAccount; @@ -7325,7 +7406,15 @@ public class S3Service implements Resettable, ResourceProvider { private String nextEventSequencer() { long nowMicros = ChronoUnit.MICROS.between(Instant.EPOCH, Instant.now()); long value = lastEventSequencer.updateAndGet(last -> Math.max(last + 1, nowMicros)); - return String.format(Locale.ROOT, "%018X", value); + return toSequencer(value); + } + + private String nextDataGeneration() { + return Long.toString(dataGenerations.incrementAndGet()); + } + + static String toSequencer(long value) { + return "00" + HexFormat.of().withUpperCase().toHexDigits(value); } private void cleanupMultipart(String uploadId) { @@ -7409,81 +7498,19 @@ public class S3Service implements Resettable, ResourceProvider { } private static S3Object copyObject(S3Object source) { - S3Object copy = new S3Object(); - copy.setBucketName(source.getBucketName()); - copy.setKey(source.getKey()); - copy.setData(source.getData() != null ? Arrays.copyOf(source.getData(), source.getData().length) : null); - copy.setMetadata(new HashMap<>(source.getMetadata())); - copy.setContentType(source.getContentType()); - copy.setContentEncoding(source.getContentEncoding()); - copy.setContentDisposition(source.getContentDisposition()); - copy.setCacheControl(source.getCacheControl()); - copy.setServerSideEncryption(source.getServerSideEncryption()); - copy.setSseKmsKeyId(source.getSseKmsKeyId()); - copy.setSseCustomerAlgorithm(source.getSseCustomerAlgorithm()); - copy.setSseCustomerKeyMd5(source.getSseCustomerKeyMd5()); - copy.setSize(source.getSize()); - copy.setLastModified(source.getLastModified()); - copy.setETag(source.getETag()); - copy.setStorageClass(source.getStorageClass()); - copy.setChecksum(copyChecksum(source.getChecksum())); - copy.setParts(copyParts(source.getParts())); - copy.setVersionId(source.getVersionId()); - copy.setDeleteMarker(source.isDeleteMarker()); - copy.setLatest(source.isLatest()); - copy.setTags(new HashMap<>(source.getTags())); - copy.setObjectLockMode(source.getObjectLockMode()); - copy.setRetainUntilDate(source.getRetainUntilDate()); - copy.setLegalHoldStatus(source.getLegalHoldStatus()); - copy.setAcl(source.getAcl()); - copy.setOwnerAccountId(source.getOwnerAccountId()); - copy.setDataGeneration(source.getDataGeneration()); - copy.setEventSequencer(source.getEventSequencer()); - return copy; + return new S3Object(source); } private static S3Checksum copyChecksum(S3Checksum source) { return source == null ? null : source.copy(); } - private static List copyParts(List sourceParts) { - if (sourceParts == null) { - return new ArrayList<>(); - } - return sourceParts.stream().map(S3Service::copyPart).toList(); - } - - private static Part copyPart(Part source) { - if (source == null) { - return null; - } - Part copy = new Part(); - copy.setPartNumber(source.getPartNumber()); - copy.setETag(source.getETag()); - copy.setSize(source.getSize()); - copy.setChecksum(copyChecksum(source.getChecksum())); - copy.setLastModified(source.getLastModified()); - return copy; - } - private static String computeETag(byte[] data) { - return "\"" + bytesToHex(computeETagBytes(data)) + "\""; - } - - private static byte[] computeETagBytes(byte[] data) { - try { - return MessageDigest.getInstance("MD5").digest(data); - } catch (NoSuchAlgorithmException e) { - throw new RuntimeException("MD5 algorithm not available", e); - } + return "\"" + Digests.md5Hex(data) + "\""; } private static String bytesToHex(byte[] bytes) { - var sb = new StringBuilder(); - for (byte b : bytes) { - sb.append(String.format("%02x", b)); - } - return sb.toString(); + return HexFormat.of().formatHex(bytes); } private void ensureBucketExists(String bucketName) { @@ -7597,15 +7624,6 @@ public class S3Service implements Resettable, ResourceProvider { return objectStore.get(storeKey); } - private List scanObjectsForAccount(String accountId, Predicate keyFilter) { - if (globalBucketNamespace && objectStore instanceof AccountAwareStorageBackend aware) { - @SuppressWarnings("unchecked") - AccountAwareStorageBackend typed = (AccountAwareStorageBackend) aware; - return typed.scanForAccount(accountId, keyFilter); - } - return objectStore.scan(keyFilter); - } - private void putObjectForAccount(String accountId, String storeKey, S3Object object) { if (objectStore instanceof AccountAwareStorageBackend aware) { @SuppressWarnings("unchecked") @@ -8004,7 +8022,7 @@ public class S3Service implements Resettable, ResourceProvider { resolveObjectPath(accountId, bucketName, key)); } S3Object restored = copyObject(previous); - restored.setDataGeneration(UUID.randomUUID().toString()); + restored.setDataGeneration(nextDataGeneration()); putObjectForAccount(accountId, objectKey(bucketName, key), restored); deleteObjectForAccount(accountId, versionedKey(bucketName, key, failedVersionId)); if (priorHistory != null) { @@ -8035,7 +8053,7 @@ public class S3Service implements Resettable, ResourceProvider { resolveObjectPath(accountId, bucketName, key)); } S3Object restored = copyObject(previous); - restored.setDataGeneration(UUID.randomUUID().toString()); + restored.setDataGeneration(nextDataGeneration()); putObjectForAccount(accountId, versionedKey(bucketName, key, storedVersionId(restored)), restored); putObjectForAccount(accountId, objectKey(bucketName, key), restored); } catch (RuntimeException recoveryFailure) { @@ -8067,7 +8085,7 @@ public class S3Service implements Resettable, ResourceProvider { deleteObjectForAccount(accountId, storeKey); deleteVersionedFile(accountId, bucketName, key, "null"); if (deleteAnnotations) { - deleteAllAnnotationsFor(annotationParentKey(bucketName, key, null)); + deleteAllAnnotationsFor(bucketName, key, null); } } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/Bucket.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/Bucket.java index 07c4842e41..a91b9b0b9e 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/Bucket.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/Bucket.java @@ -1,6 +1,8 @@ package io.github.hectorvent.floci.services.s3.model; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.github.hectorvent.floci.core.common.XmlParser; import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; @@ -29,6 +31,8 @@ public class Bucket { private String publicAccessBlockConfiguration; // XML string private boolean publicAccessBlockDeleted; private String ownershipControlsConfiguration; // XML string + @JsonIgnore + private boolean ownershipEnforced; private String requestPaymentPayer; // "BucketOwner" (default) or "Requester"; null until first PUT private String accelerateStatus; // "Enabled" or "Suspended"; null until first PUT private String region; @@ -123,8 +127,14 @@ public class Bucket { public String getOwnershipControlsConfiguration() { return ownershipControlsConfiguration; } public void setOwnershipControlsConfiguration(String ownershipControlsConfiguration) { this.ownershipControlsConfiguration = ownershipControlsConfiguration; + this.ownershipEnforced = ownershipControlsConfiguration != null + && XmlParser.containsValue(ownershipControlsConfiguration, "ObjectOwnership", "BucketOwnerEnforced"); } + @JsonIgnore + public boolean isObjectOwnershipEnforced() { + return ownershipEnforced; + } public String getRequestPaymentPayer() { return requestPaymentPayer; } public void setRequestPaymentPayer(String requestPaymentPayer) { this.requestPaymentPayer = requestPaymentPayer; } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumAlgorithm.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumAlgorithm.java index 29f2f5f7ce..41204af0f0 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumAlgorithm.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/ChecksumAlgorithm.java @@ -26,14 +26,22 @@ public enum ChecksumAlgorithm { private static final Set KNOWN_UNSUPPORTED = Set.of("SHA512", "MD5", "XXHASH3", "XXHASH64", "XXHASH128"); private final Set multipartTypes; + private final String wireValue; + private final String headerName; ChecksumAlgorithm(Set multipartTypes) { this.multipartTypes = multipartTypes; + this.wireValue = name().toLowerCase(Locale.ROOT); + this.headerName = "x-amz-checksum-" + wireValue; + } + + public String headerName() { + return headerName; } /** Lowercase name, as AWS spells the algorithm in error messages. */ public String wireValue() { - return name().toLowerCase(Locale.ROOT); + return wireValue; } public boolean supports(ChecksumType type) { diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/Part.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/Part.java index 7395d8037a..f5c1a485dd 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/Part.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/Part.java @@ -5,6 +5,8 @@ import io.quarkus.runtime.annotations.RegisterForReflection; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; @RegisterForReflection public class Part { @@ -31,6 +33,26 @@ public class Part { this.lastModified = Instant.now().truncatedTo(ChronoUnit.SECONDS); } + public Part(Part source) { + this.partNumber = source.partNumber; + this.eTag = source.eTag; + this.size = source.size; + this.checksum = source.checksum == null ? null : source.checksum.copy(); + this.lastModified = source.lastModified; + } + + /** Copies of {@code parts}, an empty list for null, null entries kept. */ + public static List copyAll(List parts) { + if (parts == null) { + return new ArrayList<>(); + } + List copies = new ArrayList<>(parts.size()); + for (Part part : parts) { + copies.add(part == null ? null : new Part(part)); + } + return copies; + } + public int getPartNumber() { return partNumber; } public void setPartNumber(int partNumber) { this.partNumber = partNumber; } diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java b/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java index 2ef0e91ac9..0f1ebb09d1 100644 --- a/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java +++ b/src/main/java/io/github/hectorvent/floci/services/s3/model/S3Object.java @@ -2,13 +2,13 @@ package io.github.hectorvent.floci.services.s3.model; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import io.github.hectorvent.floci.core.common.Digests; import io.quarkus.runtime.annotations.RegisterForReflection; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; +import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -93,6 +93,38 @@ public class S3Object { this.tags = new HashMap<>(); } + public S3Object(S3Object source) { + this.bucketName = source.bucketName; + this.key = source.key; + this.data = source.data != null ? Arrays.copyOf(source.data, source.data.length) : null; + this.metadata = new HashMap<>(source.metadata); + this.contentType = source.contentType; + this.contentEncoding = source.contentEncoding; + this.contentDisposition = source.contentDisposition; + this.cacheControl = source.cacheControl; + this.serverSideEncryption = source.serverSideEncryption; + this.sseKmsKeyId = source.sseKmsKeyId; + this.sseCustomerAlgorithm = source.sseCustomerAlgorithm; + this.sseCustomerKeyMd5 = source.sseCustomerKeyMd5; + this.size = source.size; + this.lastModified = source.lastModified; + this.eTag = source.eTag; + this.storageClass = source.storageClass; + this.checksum = source.checksum == null ? null : source.checksum.copy(); + this.parts = Part.copyAll(source.parts); + this.versionId = source.versionId; + this.deleteMarker = source.deleteMarker; + this.isLatest = source.isLatest; + this.tags = new HashMap<>(source.tags); + this.objectLockMode = source.objectLockMode; + this.retainUntilDate = source.retainUntilDate; + this.legalHoldStatus = source.legalHoldStatus; + this.acl = source.acl; + this.ownerAccountId = source.ownerAccountId; + this.dataGeneration = source.dataGeneration; + this.eventSequencer = source.eventSequencer; + } + public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } @@ -181,17 +213,6 @@ public class S3Object { public void setEventSequencer(String eventSequencer) { this.eventSequencer = eventSequencer; } public static String computeETag(byte[] data) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - byte[] digest = md.digest(data); - StringBuilder sb = new StringBuilder("\""); - for (byte b : digest) { - sb.append(String.format("%02x", b)); - } - sb.append("\""); - return sb.toString(); - } catch (NoSuchAlgorithmException e) { - return "\"\""; - } + return "\"" + Digests.md5Hex(data) + "\""; } } diff --git a/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java b/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java index 3a2432f8b7..ad904de9b8 100644 --- a/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java +++ b/src/test/java/io/github/hectorvent/floci/core/common/DigestsTest.java @@ -3,9 +3,13 @@ package io.github.hectorvent.floci.core.common; import org.junit.jupiter.api.Test; import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; import java.util.HexFormat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; class DigestsTest { @@ -18,6 +22,13 @@ class DigestsTest { assertEquals(ABC_MD5, HexFormat.of().formatHex(Digests.md5("abc".getBytes(StandardCharsets.UTF_8)))); } + @Test + void md5DigestIsAFreshInstanceWithTheProviderResult() throws NoSuchAlgorithmException { + byte[] data = "floci".getBytes(StandardCharsets.UTF_8); + assertArrayEquals(MessageDigest.getInstance("MD5").digest(data), Digests.md5Digest().digest(data)); + assertNotSame(Digests.md5Digest(), Digests.md5Digest()); + } + @Test void sha1MatchesTheFipsTestVector() { assertEquals(ABC_SHA1, HexFormat.of().formatHex(Digests.sha1("abc".getBytes(StandardCharsets.UTF_8)))); diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ControllerTimestampTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ControllerTimestampTest.java new file mode 100644 index 0000000000..d9b4151b4b --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ControllerTimestampTest.java @@ -0,0 +1,47 @@ +package io.github.hectorvent.floci.services.s3; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class S3ControllerTimestampTest { + + @Test + void isoSecondsMatchesFormatter() { + List instants = List.of( + Instant.EPOCH, + Instant.parse("2000-02-29T23:59:59Z"), + Instant.parse("2026-10-29T10:15:14.999Z"), + Instant.parse("1999-12-31T23:59:59.5Z"), + Instant.parse("2038-01-19T03:14:07Z"), + Instant.parse("0999-12-31T23:59:59Z"), + Instant.parse("+10000-01-01T00:00:00Z")); + for (Instant instant : instants) { + assertEquals(S3Controller.ISO_FORMAT.format(instant), S3Controller.isoSeconds(instant)); + } + } + + @Test + void rfc822MatchesFormatter() { + List instants = new ArrayList<>(List.of( + Instant.EPOCH, + Instant.parse("1999-12-31T23:59:59Z"), + Instant.parse("2000-02-29T00:00:00Z"), + Instant.parse("2026-10-29T10:15:14.999Z"), + Instant.parse("2038-01-19T03:14:07Z"), + Instant.parse("2100-03-01T12:00:00Z"), + Instant.parse("0999-12-31T23:59:59Z"), + Instant.parse("+10000-01-01T00:00:00Z"))); + for (int day = 26; day <= 31; day++) { + instants.add(Instant.parse("2026-10-" + day + "T05:06:07Z")); + } + instants.add(Instant.parse("2026-11-01T05:06:07Z")); + for (Instant instant : instants) { + assertEquals(S3Controller.RFC_822.format(instant), S3Controller.rfc822(instant)); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalLegacyListingTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalLegacyListingTest.java index dafe6610fa..6852a90384 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalLegacyListingTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalLegacyListingTest.java @@ -104,6 +104,7 @@ class S3GlobalLegacyListingTest { when(provider.get()).thenReturn(lambda); s3 = new S3Service(factory, config, null, null, provider, null, null, region, new ObjectMapper(), null); trail = mock(CloudTrailService.class); + when(trail.hasTrails()).thenReturn(true); CurrentVertxRequest vertx = mock(CurrentVertxRequest.class, RETURNS_DEEP_STUBS); when(vertx.getCurrent().request().path()).thenReturn("/" + BUCKET + "/object.txt"); when(vertx.getCurrent().request().getHeader("Authorization")).thenAnswer(invocation -> diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3LegacyHeaderAccountIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3LegacyHeaderAccountIntegrationTest.java index 8d749994a5..eb305283e3 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3LegacyHeaderAccountIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3LegacyHeaderAccountIntegrationTest.java @@ -22,6 +22,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; @QuarkusTest class S3LegacyHeaderAccountIntegrationTest { @@ -102,6 +103,7 @@ class S3LegacyHeaderAccountIntegrationTest { AtomicReference recorded = new AtomicReference<>(); AtomicReference eventAccount = new AtomicReference<>(); CloudTrailService cloudTrail = mock(CloudTrailService.class); + when(cloudTrail.hasTrails()).thenReturn(true); doAnswer(invocation -> { recorded.set(invocation.getArgument(0)); eventAccount.set(requestContext.getAccountId()); diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceReadWithinTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceReadWithinTest.java index 871326dcfb..dcb560a338 100644 --- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceReadWithinTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceReadWithinTest.java @@ -40,7 +40,68 @@ class S3ServiceReadWithinTest { assertEquals(List.of(11L), tooLarge); } + @Test + void readWithinReadsBodyOfDeclaredSize() { + byte[] body = bytes(1000); + assertArrayEquals(body, S3Service.readWithin(new ByteArrayInputStream(body), 5000, 1000, n -> { })); + } + + @Test + void readWithinAcceptsShorterBodyThanDeclared() { + byte[] body = bytes(10); + assertArrayEquals(body, S3Service.readWithin(new ByteArrayInputStream(body), 5000, 1000, n -> { })); + } + + @Test + void readWithinAcceptsLongerBodyThanDeclared() { + byte[] body = bytes(30000); + assertArrayEquals(body, S3Service.readWithin(new ByteArrayInputStream(body), 50000, 100, n -> { })); + } + + @Test + void readWithinReadsShortBodyWhenDeclaredSizeIsAboveExactReadLimit() { + byte[] body = bytes(10); + long declared = 65L * 1024 * 1024; + assertArrayEquals(body, S3Service.readWithin(new ByteArrayInputStream(body), Long.MAX_VALUE / 2, declared, + n -> { })); + } + + @Test + void readWithinReadsEmptyBody() { + assertEquals(0, S3Service.readWithin(new ByteArrayInputStream(new byte[0]), 5000, 0, n -> { }).length); + assertEquals(1, S3Service.readWithin(new ByteArrayInputStream(bytes(1)), 5000, 0, n -> { }).length); + } + + @Test + void readWithinReadsBodyWithoutDeclaredSize() { + byte[] body = bytes(20000); + assertArrayEquals(body, S3Service.readWithin(new ByteArrayInputStream(body), 50000, -1, n -> { })); + assertArrayEquals(body, S3Service.readWithin(new ByteArrayInputStream(body), 50000, n -> { })); + } + + @Test + void readWithinRejectsBodyPastMaxSize() { + long[] reported = {-1}; + assertThrows(AwsException.class, () -> S3Service.readWithin( + new ByteArrayInputStream(bytes(200)), 100, 50, n -> reported[0] = n)); + assertEquals(200, reported[0]); + } + + @Test + void readWithinRejectsDeclaredSizeAboveMaxSizeWhenBodyIsLarger() { + assertThrows(AwsException.class, () -> S3Service.readWithin( + new ByteArrayInputStream(bytes(200)), 100, 150, n -> { })); + } + private static ByteArrayInputStream body(String text) { return new ByteArrayInputStream(text.getBytes(StandardCharsets.UTF_8)); } + + private static byte[] bytes(int length) { + byte[] data = new byte[length]; + for (int index = 0; index < length; index++) { + data[index] = (byte) (index * 31); + } + return data; + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceSequencerTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceSequencerTest.java new file mode 100644 index 0000000000..685c240be6 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceSequencerTest.java @@ -0,0 +1,19 @@ +package io.github.hectorvent.floci.services.s3; + +import org.junit.jupiter.api.Test; + +import java.util.Locale; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class S3ServiceSequencerTest { + + @Test + void toSequencerMatchesFormattedValue() { + long[] values = {0, 1, 15, 16, 255, 0xABCDEF, System.currentTimeMillis() * 1000, Long.MAX_VALUE, -1, + Long.MIN_VALUE}; + for (long value : values) { + assertEquals(String.format(Locale.ROOT, "%018X", value), S3Service.toSequencer(value)); + } + } +} diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/model/S3ObjectCopyTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/model/S3ObjectCopyTest.java new file mode 100644 index 0000000000..62ac6f2be3 --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/s3/model/S3ObjectCopyTest.java @@ -0,0 +1,105 @@ +package io.github.hectorvent.floci.services.s3.model; + +import org.junit.jupiter.api.Test; + +import java.time.Instant; +import java.util.ArrayList; +import java.util.HashMap; +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.assertNotSame; + +class S3ObjectCopyTest { + + @Test + void copyConstructorCopiesEveryField() { + S3Object source = new S3Object(); + source.setBucketName("bucket"); + source.setKey("key"); + source.setData(new byte[] {1, 2, 3}); + Map metadata = new HashMap<>(); + metadata.put("a", "b"); + source.setMetadata(metadata); + source.setContentType("text/plain"); + source.setContentEncoding("gzip"); + source.setContentDisposition("attachment"); + source.setCacheControl("no-cache"); + source.setServerSideEncryption("aws:kms"); + source.setSseKmsKeyId("key-id"); + source.setSseCustomerAlgorithm("AES256"); + source.setSseCustomerKeyMd5("md5"); + source.setSize(3); + source.setLastModified(Instant.parse("2024-01-02T03:04:05Z")); + source.setETag("\"etag\""); + source.setStorageClass("GLACIER"); + S3Checksum checksum = new S3Checksum(); + checksum.setChecksumCRC32("crc"); + checksum.setChecksumType(ChecksumType.COMPOSITE); + source.setChecksum(checksum); + Part part = new Part(1, "\"p\"", 3); + part.setChecksum(new S3Checksum()); + List parts = new ArrayList<>(); + parts.add(part); + source.setParts(parts); + source.setVersionId("v1"); + source.setDeleteMarker(true); + source.setLatest(false); + Map tags = new HashMap<>(); + tags.put("t", "u"); + source.setTags(tags); + source.setObjectLockMode("GOVERNANCE"); + source.setRetainUntilDate(Instant.parse("2030-01-01T00:00:00Z")); + source.setLegalHoldStatus("ON"); + source.setAcl("private"); + source.setOwnerAccountId("111111111111"); + source.setDataGeneration("7"); + source.setEventSequencer("00000000000000ABCD"); + + S3Object copy = new S3Object(source); + + assertEquals(source.getBucketName(), copy.getBucketName()); + assertEquals(source.getKey(), copy.getKey()); + assertArrayEquals(source.getData(), copy.getData()); + assertNotSame(source.getData(), copy.getData()); + assertEquals(source.getMetadata(), copy.getMetadata()); + assertNotSame(source.getMetadata(), copy.getMetadata()); + assertEquals(source.getContentType(), copy.getContentType()); + assertEquals(source.getContentEncoding(), copy.getContentEncoding()); + assertEquals(source.getContentDisposition(), copy.getContentDisposition()); + assertEquals(source.getCacheControl(), copy.getCacheControl()); + assertEquals(source.getServerSideEncryption(), copy.getServerSideEncryption()); + assertEquals(source.getSseKmsKeyId(), copy.getSseKmsKeyId()); + assertEquals(source.getSseCustomerAlgorithm(), copy.getSseCustomerAlgorithm()); + assertEquals(source.getSseCustomerKeyMd5(), copy.getSseCustomerKeyMd5()); + assertEquals(source.getSize(), copy.getSize()); + assertEquals(source.getLastModified(), copy.getLastModified()); + assertEquals(source.getETag(), copy.getETag()); + assertEquals(source.getStorageClass(), copy.getStorageClass()); + assertNotSame(source.getChecksum(), copy.getChecksum()); + assertEquals("crc", copy.getChecksum().getChecksumCRC32()); + assertEquals(ChecksumType.COMPOSITE, copy.getChecksum().getChecksumType()); + assertNotSame(source.getParts(), copy.getParts()); + assertEquals(1, copy.getParts().size()); + assertNotSame(source.getParts().get(0), copy.getParts().get(0)); + assertEquals(1, copy.getParts().get(0).getPartNumber()); + assertEquals("\"p\"", copy.getParts().get(0).getETag()); + assertEquals(3, copy.getParts().get(0).getSize()); + assertEquals(source.getParts().get(0).getLastModified(), copy.getParts().get(0).getLastModified()); + assertNotSame(source.getParts().get(0).getChecksum(), copy.getParts().get(0).getChecksum()); + assertEquals(source.getVersionId(), copy.getVersionId()); + assertEquals(source.isDeleteMarker(), copy.isDeleteMarker()); + assertEquals(source.isLatest(), copy.isLatest()); + assertEquals(source.getTags(), copy.getTags()); + assertNotSame(source.getTags(), copy.getTags()); + assertEquals(source.getObjectLockMode(), copy.getObjectLockMode()); + assertEquals(source.getRetainUntilDate(), copy.getRetainUntilDate()); + assertEquals(source.getLegalHoldStatus(), copy.getLegalHoldStatus()); + assertEquals(source.getAcl(), copy.getAcl()); + assertEquals(source.getOwnerAccountId(), copy.getOwnerAccountId()); + assertEquals(source.getDataGeneration(), copy.getDataGeneration()); + assertEquals(source.getEventSequencer(), copy.getEventSequencer()); + } +}