feat(s3): add Intelligent-Tiering configuration CRUD (#2997)

* feat(s3): add Intelligent-Tiering configuration CRUD

Add AWS S3 Intelligent-Tiering configuration management through the
real REST XML subresource (?intelligent-tiering), mirroring the existing
metrics configuration pattern.

Operations:
- PutBucketIntelligentTieringConfiguration (PUT, 204)
- GetBucketIntelligentTieringConfiguration (GET by id)
- ListBucketIntelligentTieringConfigurations (GET without id)
- DeleteBucketIntelligentTieringConfiguration (DELETE, 204)

The parser validates Id, Status (Enabled/Disabled), optional Filter
(Prefix/Tag/And), and one or more Tiering entries (AccessTier + positive
Days), re-serializing through XmlBuilder/XmlParser/AwsNamespaces.S3 so
responses are built by floci rather than echoing the request body.
Malformed bodies return MalformedXML; missing configurations return
NoSuchConfiguration.

Configurations are stored on the Bucket model keyed by id (nullable map
for backward-compatible deserialization of older snapshots), persisted
through StorageFactory, and synchronized on the bucket monitor with the
same requireSameRecord guard as metrics to survive concurrent puts and
bucket delete/recreate races.

Tests:
- S3IntelligentTieringConfigurationTest: parser unit tests
- S3ServiceTest: service lifecycle, isolation, persistence, concurrency
- S3IntelligentTieringConfigurationIntegrationTest: REST integration
- compatibility-tests/sdk-test-awscli: AWS CLI bats coverage

* refactor(s3): rename METRICS_XML_DECLARATION to S3_XML_DECLARATION

The XML declaration constant is shared by both metrics and
intelligent-tiering configuration responses, so the name should reflect
its S3-wide scope rather than implying it is metrics-specific.

* fix(s3): enforce auth and validate Days overflow on intelligent-tiering

Address review feedback on PR #2997:

- PUT and DELETE ?intelligent-tiering now enforce S3 authorization via
  a new authorizeBucketWrite method, closing the bypass where mutations
  skipped the auth applied to reads.
- Days values above Integer.MAX_VALUE no longer throw NumberFormatException
  and return 500 InternalError; they are rejected as 400 MalformedXML.
- A PUT without a request body returns 400 MalformedXML instead of NPE/500.

Tests: unit coverage for Days overflow, integration coverage for empty body.

* fix(s3): enforce tier-specific Days range on intelligent-tiering

AWS enforces a tier-specific Days range for S3 Intelligent-Tiering:
- ARCHIVE_ACCESS: 90 to 730 days
- DEEP_ARCHIVE_ACCESS: 180 to 730 days

Out-of-range values now return InvalidArgument with ArgumentName and
ArgumentValue in the XML error body, matching the real S3 error shape.

Add unit and integration tests covering below-minimum, above-maximum,
boundary acceptance, and the full XML error response.

* refactor(s3): extract Days range constants in intelligent-tiering

Replace repeated magic numbers (90, 180, 730) with named constants
ARCHIVE_ACCESS_MIN_DAYS, DEEP_ARCHIVE_ACCESS_MIN_DAYS, and MAX_DAYS.
Pass min into daysOutOfRange instead of recomputing it, and use an
import for LinkedHashMap.
This commit is contained in:
Chiara Forresi authored and GitHub committed 2026-09-04 09:06:15 -04:00
1 parent c55733c49e
commit 96d16de998
9 files changed
+1314 -9

No files matched your search

@@ -332,6 +332,14 @@ public class S3Controller {
if (hasQueryParam(uriInfo, "metrics")) {
return handlePutBucketMetricsConfiguration(bucket, uriInfo, body);
}
// Same fall-through hazard as metrics: an intelligent-tiering PUT must not become a
// CreateBucket.
if (hasQueryParam(uriInfo, "intelligent-tiering")) {
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
s3Service.authorizeBucketWrite(bucket, "s3:PutIntelligentTieringConfiguration", authorization);
return handlePutBucketIntelligentTieringConfiguration(bucket, uriInfo, body);
}
String locationConstraint = null;
if (body != null && body.length > 0) {
@@ -374,7 +382,8 @@ public class S3Controller {
@DELETE
@Path("/{bucket}")
public Response deleteBucket(@PathParam("bucket") String bucket,
@Context UriInfo uriInfo) {
@Context UriInfo uriInfo,
@Context HttpHeaders httpHeaders) {
try {
validateRawUri();
if (hasQueryParam(uriInfo, "tagging")) {
@@ -418,6 +427,15 @@ public class S3Controller {
s3Service.deleteBucketMetricsConfiguration(bucket, requireMetricsId(uriInfo));
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "intelligent-tiering")) {
// Likewise this must not fall through to deleting the bucket.
S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
s3Service.isAuthEnforced(), httpHeaders, uriInfo);
s3Service.authorizeBucketWrite(bucket, "s3:PutIntelligentTieringConfiguration", authorization);
s3Service.deleteBucketIntelligentTieringConfiguration(bucket,
requireIntelligentTieringId(uriInfo));
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "accelerate")) {
// AWS defines no DELETE for the accelerate subresource; reject it here so
// it does NOT fall through to deleting the whole bucket.
@@ -543,6 +561,17 @@ public class S3Controller {
: s3Service.listBucketMetricsConfigurations(bucket);
return Response.ok(xml).type("application/xml").build();
}
// 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")) {
s3Service.authorizeBucketRead(bucket, "s3:GetIntelligentTieringConfiguration", authorization);
String id = uriInfo.getQueryParameters().getFirst("id");
String xml = id != null
? s3Service.getBucketIntelligentTieringConfiguration(bucket, id)
: s3Service.listBucketIntelligentTieringConfigurations(bucket);
return Response.ok(xml).type("application/xml").build();
}
// --- S3 static-website index resolution (site root) ---
// A website endpoint has no S3 REST API, so it serves the index document for the site root
@@ -1839,6 +1868,37 @@ public class S3Controller {
return id;
}
// --- Intelligent-Tiering Configurations ---
private Response handlePutBucketIntelligentTieringConfiguration(String bucket, UriInfo uriInfo,
byte[] body) {
String id = requireIntelligentTieringId(uriInfo);
String xml = body == null ? null : new String(body, StandardCharsets.UTF_8);
S3IntelligentTieringConfiguration configuration =
S3IntelligentTieringConfiguration.parse(xml);
// AWS rejects a body whose Id disagrees with the id in the query string.
if (!id.equals(configuration.id())) {
throw new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our "
+ "published schema", 400);
}
s3Service.putBucketIntelligentTieringConfiguration(bucket, id, configuration.innerXml());
return Response.noContent().build();
}
/**
* The id identifies the configuration, so a request without one is refused rather than guessed
* at, mirroring the metrics subresource.
*/
private String requireIntelligentTieringId(UriInfo uriInfo) {
String id = uriInfo.getQueryParameters().getFirst("id");
if (id == null) {
throw new AwsException("InvalidArgument",
"The intelligent-tiering configuration id must be specified.", 400);
}
return id;
}
// --- Object Tagging ---
private Response handlePutObjectTagging(String bucket, String key, byte[] body) {
@@ -2486,6 +2546,18 @@ public class S3Controller {
if (condition != null) {
xmlBuilder.elem("Condition", condition);
}
// S3 InvalidArgument responses carry ArgumentName and ArgumentValue so the SDK can
// surface which input was rejected. They travel through AwsException.extendedData.
if (e.getExtendedData() != null) {
Object argumentName = e.getExtendedData().get("ArgumentName");
Object argumentValue = e.getExtendedData().get("ArgumentValue");
if (argumentName != null) {
xmlBuilder.elem("ArgumentName", argumentName.toString());
}
if (argumentValue != null) {
xmlBuilder.elem("ArgumentValue", argumentValue.toString());
}
}
String xml = xmlBuilder
.elem("RequestId", java.util.UUID.randomUUID().toString())
.end("Error")
@@ -0,0 +1,200 @@
package io.github.hectorvent.floci.services.s3;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.core.common.XmlBuilder;
import io.github.hectorvent.floci.core.common.XmlParser;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* A parsed {@code IntelligentTieringConfiguration} request body, reduced to a canonical
* serialization of its contents.
*
* <p>The body is re-serialized rather than stored verbatim, so that what a later
* GetBucketIntelligentTieringConfiguration or ListBucketIntelligentTieringConfigurations returns
* is built by floci instead of being whatever XML the caller sent, and so that the same stored
* form can be wrapped in either response.
*/
record S3IntelligentTieringConfiguration(String id, String innerXml) {
private static final String ROOT = "IntelligentTieringConfiguration";
private static final List<String> STATUSES = List.of("Enabled", "Disabled");
private static final List<String> ACCESS_TIERS = List.of("ARCHIVE_ACCESS", "DEEP_ARCHIVE_ACCESS");
private static final int ARCHIVE_ACCESS_MIN_DAYS = 90;
private static final int DEEP_ARCHIVE_ACCESS_MIN_DAYS = 180;
private static final int MAX_DAYS = 730;
/** AWS reports a body that does not match the published schema this way. */
private static AwsException malformed() {
return new AwsException("MalformedXML",
"The XML you provided was not well-formed or did not validate against our published schema", 400);
}
/**
* AWS reports a {@code Days} value outside the tier-specific allowed range this way: the XML
* is well-formed, but the value is semantically invalid. Minimums are tier-specific
* ({@link #ARCHIVE_ACCESS_MIN_DAYS} for ARCHIVE_ACCESS, {@link #DEEP_ARCHIVE_ACCESS_MIN_DAYS}
* for DEEP_ARCHIVE_ACCESS) and both are capped at {@link #MAX_DAYS}. The response carries
* {@code ArgumentName} and {@code ArgumentValue} so the SDK can surface which input was
* rejected, matching the real S3 error shape.
*/
private static AwsException daysOutOfRange(String accessTier, int min, int days) {
String message = days < min
? "Days must be at least " + min + " for AccessTier " + accessTier + "."
: "Days must be at most " + MAX_DAYS + " for AccessTier " + accessTier + ".";
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("ArgumentName", "Tiering.Days");
detail.put("ArgumentValue", String.valueOf(days));
return new AwsException("InvalidArgument", message, 400, detail);
}
static S3IntelligentTieringConfiguration parse(String xml) {
if (xml == null || xml.isBlank() || !ROOT.equals(XmlParser.rootElementName(xml))) {
throw malformed();
}
// The configuration is one Id, one Status, at most one Filter, and at least one Tiering,
// so anything else under the root is a body AWS would not have accepted.
List<String> children = XmlParser.childElementNames(xml, ROOT);
long ids = children.stream().filter("Id"::equals).count();
long statuses = children.stream().filter("Status"::equals).count();
long filters = children.stream().filter("Filter"::equals).count();
long tierings = children.stream().filter("Tiering"::equals).count();
if (ids != 1 || statuses != 1 || filters > 1 || tierings < 1
|| children.size() != ids + statuses + filters + tierings) {
throw malformed();
}
String id = XmlParser.extractFirst(xml, "Id", null);
if (id == null || id.isBlank()) {
throw malformed();
}
String status = XmlParser.extractFirst(xml, "Status", null);
if (status == null || !STATUSES.contains(status)) {
throw malformed();
}
XmlBuilder inner = new XmlBuilder().elem("Id", id);
if (filters == 1) {
inner.start("Filter").raw(filterXml(xml)).end("Filter");
}
inner.elem("Status", status);
for (int i = 0; i < tierings; i++) {
inner.start("Tiering").raw(tieringXml(xml, i)).end("Tiering");
}
return new S3IntelligentTieringConfiguration(id, inner.build());
}
/**
* Serializes the filter. A filter is exactly one of a prefix, an object tag, or an And
* conjunction: AWS answers MalformedXML for a filter naming none of them or more than one,
* and for an And holding fewer than two predicates.
*/
private static String filterXml(String xml) {
List<String> predicates = XmlParser.childElementNames(xml, "Filter");
if (predicates.size() != 1) {
throw malformed();
}
String predicate = predicates.getFirst();
return switch (predicate) {
case "Prefix" -> new XmlBuilder().elem("Prefix", requireText(xml, "Prefix")).build();
case "Tag" -> tagsXml(xml, 1);
case "And" -> {
List<String> conjuncts = XmlParser.childElementNames(xml, "And");
if (conjuncts.size() < 2) {
throw malformed();
}
XmlBuilder and = new XmlBuilder().start("And");
if (conjuncts.contains("Prefix")) {
and.elem("Prefix", requireText(xml, "Prefix"));
}
long tagCount = conjuncts.stream().filter("Tag"::equals).count();
if (tagCount > 0) {
and.raw(tagsXml(xml, (int) tagCount));
}
// Every conjunct has to be one floci understands, or the filter it stores would
// not be the filter that was sent.
if (conjuncts.size() != tagCount + (conjuncts.contains("Prefix") ? 1 : 0)) {
throw malformed();
}
yield and.end("And").build();
}
default -> throw malformed();
};
}
/**
* Serializes {@code expected} tags. A tag carries both a key and a value, so a pair short of
* the element count means one of them was missing.
*/
private static String tagsXml(String xml, int expected) {
Map<String, String> tags = XmlParser.extractPairs(xml, "Tag", "Key", "Value");
if (tags.size() != expected) {
throw malformed();
}
XmlBuilder out = new XmlBuilder();
tags.forEach((key, value) -> {
if (key.isBlank() || value == null) {
throw malformed();
}
out.start("Tag").elem("Key", key).elem("Value", value).end("Tag");
});
return out.build();
}
/**
* Serializes the {@code index}-th {@code Tiering} entry. Each tiering is an access tier and a
* positive day count, and both are required. Days must also fall in the tier-specific range
* AWS enforces: {@link #ARCHIVE_ACCESS_MIN_DAYS}-{@link #MAX_DAYS} for ARCHIVE_ACCESS and
* {@link #DEEP_ARCHIVE_ACCESS_MIN_DAYS}-{@link #MAX_DAYS} for DEEP_ARCHIVE_ACCESS.
*/
private static String tieringXml(String xml, int index) {
List<Map<String, String>> entries = XmlParser.extractGroups(xml, "Tiering");
if (index >= entries.size()) {
throw malformed();
}
Map<String, String> tiering = entries.get(index);
String accessTier = tiering.get("AccessTier");
String days = tiering.get("Days");
if (accessTier == null || !ACCESS_TIERS.contains(accessTier)) {
throw malformed();
}
if (days == null || !days.matches("\\d+")) {
throw malformed();
}
int dayCount;
try {
dayCount = Integer.parseInt(days);
} catch (NumberFormatException e) {
// Values above Integer.MAX_VALUE match the regex but overflow parseInt.
throw malformed();
}
if (dayCount < 1) {
throw malformed();
}
// Beyond well-formedness, AWS enforces a tier-specific range. A value outside it is
// semantically invalid, not malformed, so AWS answers InvalidArgument.
int min = "DEEP_ARCHIVE_ACCESS".equals(accessTier) ? DEEP_ARCHIVE_ACCESS_MIN_DAYS : ARCHIVE_ACCESS_MIN_DAYS;
if (dayCount < min || dayCount > MAX_DAYS) {
throw daysOutOfRange(accessTier, min, dayCount);
}
return new XmlBuilder()
.elem("AccessTier", accessTier)
.elem("Days", days)
.build();
}
private static String requireText(String xml, String element) {
String value = XmlParser.extractFirst(xml, element, null);
if (value == null) {
throw malformed();
}
return value;
}
}
@@ -682,6 +682,35 @@ public class S3Service implements Resettable, ResourceProvider {
authorizeS3Read(bucketName, null, null, action, bucketArn, authorization);
}
void authorizeBucketWrite(String bucketName, String action, RequestAuthorization authorization) {
if (!enforceAuth) {
return;
}
authorizeSignedRequest(authorization);
RequestAuthorization requestAuthorization = authorization != null
? authorization
: RequestAuthorization.unsigned();
if (requestAuthorization.signed()) {
return;
}
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404));
String bucketArn = S3PublicAccessEvaluator.bucketArn(bucketName);
S3PublicAccessEvaluator.PublicAccessDecision policyDecision =
S3PublicAccessEvaluator.publicPolicyDecision(objectMapper, bucket.getPolicy(), action, bucketArn);
if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.DENY) {
throw new AwsException("AccessDenied", "Access Denied", 403);
}
if (policyDecision == S3PublicAccessEvaluator.PublicAccessDecision.ALLOW) {
return;
}
throw new AwsException("AccessDenied", "Access Denied", 403);
}
void authorizeObjectRead(String bucketName, String key, String versionId, String action, RequestAuthorization authorization) {
String objectArn = S3PublicAccessEvaluator.objectArn(bucketName, key);
authorizeS3Read(bucketName, key, versionId, action, objectArn, authorization);
@@ -1780,7 +1809,7 @@ public class S3Service implements Resettable, ResourceProvider {
// --- Metrics Configurations ---
private static final String METRICS_XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
private static final String S3_XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
/**
* Stores a CloudWatch request metrics configuration under {@code id}, replacing any
@@ -1811,7 +1840,7 @@ public class S3Service implements Resettable, ResourceProvider {
if (innerXml == null) {
throw noSuchMetricsConfiguration();
}
return METRICS_XML_DECLARATION + new XmlBuilder()
return S3_XML_DECLARATION + new XmlBuilder()
.start("MetricsConfiguration", AwsNamespaces.S3)
.raw(innerXml)
.end("MetricsConfiguration")
@@ -1833,7 +1862,7 @@ public class S3Service implements Resettable, ResourceProvider {
.start("MetricsConfiguration")
.raw(configurations.get(id))
.end("MetricsConfiguration"));
return METRICS_XML_DECLARATION + xml
return S3_XML_DECLARATION + xml
.elem("IsTruncated", false)
.end("ListMetricsConfigurationsResult")
.build();
@@ -1879,6 +1908,88 @@ public class S3Service implements Resettable, ResourceProvider {
return new AwsException("NoSuchConfiguration", "The specified configuration does not exist.", 404);
}
// --- Intelligent-Tiering Configurations ---
/**
* Stores an Intelligent-Tiering configuration under {@code id}, replacing any configuration
* already stored under it. floci records the configuration and returns it; no objects are
* transitioned between tiers because of it.
*/
public void putBucketIntelligentTieringConfiguration(String bucketName, String id, String innerXml) {
Bucket bucket = requireBucket(bucketName);
// Read-modify-write of the bucket record, so it takes the same monitor as the other
// bucket-scoped mutations: without it two concurrent puts of different ids both start from
// the same map and one of the configurations is lost.
synchronized (bucket) {
requireSameRecord(bucketName, bucket);
Map<String, String> configurations = bucket.getIntelligentTieringConfigurations() != null
? new java.util.LinkedHashMap<>(bucket.getIntelligentTieringConfigurations())
: new java.util.LinkedHashMap<>();
configurations.put(id, innerXml);
bucket.setIntelligentTieringConfigurations(configurations);
bucketStore.put(bucketName, bucket);
}
LOG.debugv("Put intelligent-tiering configuration {0} on bucket: {1}", id, bucketName);
}
public String getBucketIntelligentTieringConfiguration(String bucketName, String id) {
Bucket bucket = requireBucket(bucketName);
String innerXml = bucket.getIntelligentTieringConfigurations() == null
? null : bucket.getIntelligentTieringConfigurations().get(id);
if (innerXml == null) {
throw noSuchIntelligentTieringConfiguration();
}
return S3_XML_DECLARATION + new XmlBuilder()
.start("IntelligentTieringConfiguration", AwsNamespaces.S3)
.raw(innerXml)
.end("IntelligentTieringConfiguration")
.build();
}
/**
* Lists every Intelligent-Tiering configuration on the bucket. AWS pages these with a
* continuation token; floci returns them all in one unpaged response, ordered by id so that
* the listing is stable.
*/
public String listBucketIntelligentTieringConfigurations(String bucketName) {
Bucket bucket = requireBucket(bucketName);
Map<String, String> configurations = bucket.getIntelligentTieringConfigurations() != null
? bucket.getIntelligentTieringConfigurations() : Map.of();
XmlBuilder xml = new XmlBuilder().start("ListBucketIntelligentTieringConfigurationsResult",
AwsNamespaces.S3);
configurations.keySet().stream().sorted().forEach(id -> xml
.start("IntelligentTieringConfiguration")
.raw(configurations.get(id))
.end("IntelligentTieringConfiguration"));
return S3_XML_DECLARATION + xml
.elem("IsTruncated", false)
.end("ListBucketIntelligentTieringConfigurationsResult")
.build();
}
public void deleteBucketIntelligentTieringConfiguration(String bucketName, String id) {
Bucket bucket = requireBucket(bucketName);
// Same monitor as the put: the existence check and the write have to be one step, or a
// concurrent put of another id is dropped by the write that follows it.
synchronized (bucket) {
requireSameRecord(bucketName, bucket);
Map<String, String> configurations = bucket.getIntelligentTieringConfigurations();
if (configurations == null || !configurations.containsKey(id)) {
throw noSuchIntelligentTieringConfiguration();
}
Map<String, String> remaining = new java.util.LinkedHashMap<>(configurations);
remaining.remove(id);
bucket.setIntelligentTieringConfigurations(remaining);
bucketStore.put(bucketName, bucket);
}
LOG.debugv("Deleted intelligent-tiering configuration {0} from bucket: {1}", id, bucketName);
}
private static AwsException noSuchIntelligentTieringConfiguration() {
return new AwsException("NoSuchConfiguration", "The specified configuration does not exist.", 404);
}
// --- Object Lock Configuration ---
public void setBucketObjectLockEnabled(String bucketName) {
@@ -34,6 +34,8 @@ public class Bucket {
private WebsiteConfiguration websiteConfiguration;
/** CloudWatch request metrics configurations, keyed by the id they were stored under. */
private Map<String, String> metricsConfigurations;
/** Intelligent-Tiering configurations, keyed by the id they were stored under. */
private Map<String, String> intelligentTieringConfigurations;
public Bucket() {
this.tags = new HashMap<>();
@@ -127,4 +129,9 @@ public class Bucket {
public Map<String, String> getMetricsConfigurations() { return metricsConfigurations; }
public void setMetricsConfigurations(Map<String, String> metricsConfigurations) { this.metricsConfigurations = metricsConfigurations; }
public Map<String, String> getIntelligentTieringConfigurations() { return intelligentTieringConfigurations; }
public void setIntelligentTieringConfigurations(Map<String, String> intelligentTieringConfigurations) {
this.intelligentTieringConfigurations = intelligentTieringConfigurations;
}
}