feat(s3): support bucket metrics configurations (#2382)

* feat(s3): support bucket metrics configurations

PutBucketMetricsConfiguration was not routed, so a metrics call fell through to
the unqualified CreateBucket and came back as BucketAlreadyOwnedByYou, which
tells the caller nothing about what happened. The DELETE was worse: it fell
through to DeleteBucket and silently removed the whole bucket while reporting
success, so delete-bucket-metrics-configuration destroyed the bucket it was
called on.

Adds the four actions, stored per bucket and keyed by id:

- PutBucketMetricsConfiguration, GetBucketMetricsConfiguration,
  ListBucketMetricsConfigurations, DeleteBucketMetricsConfiguration
- the body is parsed and re-serialized rather than echoed back, so responses are
  built by floci and a filter survives the round trip in AWS's shape: repeated
  Tag elements inside And, with no wrapping element
- an id in the body that disagrees with the query string is MalformedXML, and an
  unknown id is NoSuchConfiguration on both get and delete, neither of which AWS
  treats as a no-op
- put and delete take the bucket monitor the other bucket-scoped mutations use,
  so concurrent puts of different ids cannot drop one another

Behaviour taken from a live AWS account: the status codes (204 on put and
delete, 404 for an unknown id), both error codes, and the exact XML of the
single-configuration and list responses.

floci records the configurations and returns them; no metrics are produced from
them, and the listing is unpaged, so a continuation token is neither issued nor
honoured.

* fix(s3): validate metrics filters, use the shared XML utilities, guard the delete

Three problems in the previous commit.

The filter was normalized rather than validated, so bodies AWS rejects were
accepted: a filter naming more than one predicate or none, an And of fewer than
two conjuncts, an unknown predicate, and a tag missing its key or value.
Verified against a live account that each is MalformedXML, and the parser now
answers the same.

Parsing and response building went around XmlParser and XmlBuilder, which
AGENTS.md requires, and the S3 namespace was declared again rather than taken
from AwsNamespaces. The bespoke DocumentBuilderFactory carried its own security
configuration, where XmlParser disables DTDs and external entities for everyone
in one place. The controller branches now delegate to handler methods like their
siblings instead of inlining the work.

A metrics mutation resolved the bucket record before writing it back, while
DeleteBucket took no monitor, so a delete landing in between was undone by the
write and the bucket returned. DeleteBucket now takes the same bucket monitor as
the bucket-scoped mutations, and those re-read the record under it, so a
mutation that lost the race reports NoSuchBucket rather than restoring the
bucket. Its test forces that interleaving rather than racing for it.

* fix(s3): reject malformed metrics bodies and stale writes over a recreated bucket

Re-reading the record for presence was not enough. A bucket deleted and then
recreated under the same name leaves a different record in the store, so a
mutation that had resolved the old one passed the presence check and wrote it
back, replacing the new bucket with the old one's state. The check now compares
the record itself, and a mutation holding a superseded one reports NoSuchBucket.

The parser also accepted bodies whose elements were duplicated or misplaced: a
second Id or Filter, or a stray element under the root, was normalized away
rather than refused, so what was stored was not what was sent. The root now has
to be exactly one Id and at most one Filter, in either order.

The concurrency tests wait on thread state rather than sleeping, so they observe
the interleaving instead of hoping for it: instant on a fast machine and not
flaky on a slow one. DeleteBucket taking the bucket monitor is asserted directly,
since the window it closes — a delete between a mutation's re-read and its write
— is too narrow to force from a test.
This commit is contained in:
Michal Schreiber authored and GitHub committed 2026-08-18 18:46:35 -04:00
1 parent f952fffe77
commit 8d33c65129
9 files changed
+937 -2

No files matched your search

@@ -324,6 +324,11 @@ public class S3Controller {
s3Service.putBucketAccelerateConfiguration(bucket, new String(body, StandardCharsets.UTF_8));
return Response.ok().build();
}
// Must be handled here: an unmatched subresource falls through to CreateBucket below,
// which answers a metrics call with BucketAlreadyOwnedByYou.
if (hasQueryParam(uriInfo, "metrics")) {
return handlePutBucketMetricsConfiguration(bucket, uriInfo, body);
}
String locationConstraint = null;
if (body != null && body.length > 0) {
@@ -407,6 +412,11 @@ public class S3Controller {
// handled here so it does NOT fall through to deleting the whole bucket.
return Response.noContent().build();
}
if (hasQueryParam(uriInfo, "metrics")) {
// Likewise this must not fall through to deleting the bucket.
s3Service.deleteBucketMetricsConfiguration(bucket, requireMetricsId(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.
@@ -518,6 +528,16 @@ public class S3Controller {
s3Service.authorizeBucketRead(bucket, "s3:GetAccelerateConfiguration", authorization);
return Response.ok(s3Service.getBucketAccelerateConfiguration(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")) {
s3Service.authorizeBucketRead(bucket, "s3:GetMetricsConfiguration", authorization);
String id = uriInfo.getQueryParameters().getFirst("id");
String xml = id != null
? s3Service.getBucketMetricsConfiguration(bucket, id)
: s3Service.listBucketMetricsConfigurations(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
@@ -1778,6 +1798,34 @@ public class S3Controller {
return Response.ok(buildTaggingXml(tags)).type(MediaType.APPLICATION_XML).build();
}
// --- Metrics Configurations ---
private Response handlePutBucketMetricsConfiguration(String bucket, UriInfo uriInfo, byte[] body) {
String id = requireMetricsId(uriInfo);
S3MetricsConfiguration configuration =
S3MetricsConfiguration.parse(new String(body, StandardCharsets.UTF_8));
// 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.putBucketMetricsConfiguration(bucket, id, configuration.innerXml());
return Response.noContent().build();
}
/**
* The id identifies the configuration, so a request without one is refused rather than guessed
* at. AWS's own answer here was not verified, so floci gives one rejection for both verbs.
*/
private String requireMetricsId(UriInfo uriInfo) {
String id = uriInfo.getQueryParameters().getFirst("id");
if (id == null) {
throw new AwsException("InvalidArgument", "The metrics id must be specified.", 400);
}
return id;
}
// --- Object Tagging ---
private Response handlePutObjectTagging(String bucket, String key, byte[] body) {
@@ -0,0 +1,127 @@
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.List;
import java.util.Map;
/**
* A parsed {@code MetricsConfiguration} request body, reduced to its id and a canonical
* serialization of its contents.
*
* <p>The body is re-serialized rather than stored verbatim, so that what a later
* GetBucketMetricsConfiguration or ListBucketMetricsConfigurations 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 S3MetricsConfiguration(String id, String innerXml) {
private static final String ROOT = "MetricsConfiguration";
/** 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);
}
static S3MetricsConfiguration parse(String xml) {
if (xml == null || xml.isBlank() || !ROOT.equals(XmlParser.rootElementName(xml))) {
throw malformed();
}
// The configuration is one Id and at most one Filter, so anything else under the root —
// a stray element, a second Id, a second Filter — is a body AWS would not have accepted.
List<String> children = XmlParser.childElementNames(xml, ROOT);
long ids = children.stream().filter("Id"::equals).count();
long filters = children.stream().filter("Filter"::equals).count();
if (ids != 1 || filters > 1 || children.size() != ids + filters) {
throw malformed();
}
boolean hasFilter = filters == 1;
String id = XmlParser.extractFirst(xml, "Id", null);
if (id == null || id.isBlank()) {
throw malformed();
}
XmlBuilder inner = new XmlBuilder().elem("Id", id);
if (hasFilter) {
inner.start("Filter").raw(filterXml(xml)).end("Filter");
}
return new S3MetricsConfiguration(id, inner.build());
}
/**
* Serializes the filter. A filter is exactly one of a prefix, an object tag, an access point
* ARN, 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", "AccessPointArn" -> new XmlBuilder()
.elem(predicate, requireText(xml, predicate))
.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));
}
if (conjuncts.contains("AccessPointArn")) {
and.elem("AccessPointArn", requireText(xml, "AccessPointArn"));
}
// 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)
+ (conjuncts.contains("AccessPointArn") ? 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();
}
private static String requireText(String xml, String element) {
String value = XmlParser.extractFirst(xml, element, null);
if (value == null) {
throw malformed();
}
return value;
}
}
@@ -228,7 +228,19 @@ public class S3Service implements Resettable {
public void deleteBucket(String bucketName) {
ensureBucketExists(bucketName);
Bucket bucket = bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
// Takes the bucket monitor that the bucket-scoped mutations take: a mutation that read the
// record before the delete would otherwise write it back afterwards, restoring the bucket.
synchronized (bucket) {
deleteBucketLocked(bucketName);
}
LOG.infov("Deleted bucket: {0}", bucketName);
}
private void deleteBucketLocked(String bucketName) {
// Check if bucket is empty
List<S3Object> objects = listObjects(bucketName, null, null, 1);
if (!objects.isEmpty()) {
@@ -243,7 +255,6 @@ public class S3Service implements Resettable {
} else {
deleteDirectory(dataRoot.resolve(ACCOUNT_STORAGE_ROOT).resolve(ownerId()).resolve(bucketName));
}
LOG.infov("Deleted bucket: {0}", bucketName);
}
public List<Bucket> listBuckets() {
@@ -1634,6 +1645,107 @@ public class S3Service implements Resettable {
LOG.debugv("Deleted tags from bucket: {0}", bucketName);
}
// --- Metrics Configurations ---
private static final String METRICS_XML_DECLARATION = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
/**
* Stores a CloudWatch request metrics configuration under {@code id}, replacing any
* configuration already stored under it. floci records the configuration and returns it; no
* metrics are produced from it.
*/
public void putBucketMetricsConfiguration(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.getMetricsConfigurations() != null
? new java.util.LinkedHashMap<>(bucket.getMetricsConfigurations())
: new java.util.LinkedHashMap<>();
configurations.put(id, innerXml);
bucket.setMetricsConfigurations(configurations);
bucketStore.put(bucketName, bucket);
}
LOG.debugv("Put metrics configuration {0} on bucket: {1}", id, bucketName);
}
public String getBucketMetricsConfiguration(String bucketName, String id) {
Bucket bucket = requireBucket(bucketName);
String innerXml = bucket.getMetricsConfigurations() == null
? null : bucket.getMetricsConfigurations().get(id);
if (innerXml == null) {
throw noSuchMetricsConfiguration();
}
return METRICS_XML_DECLARATION + new XmlBuilder()
.start("MetricsConfiguration", AwsNamespaces.S3)
.raw(innerXml)
.end("MetricsConfiguration")
.build();
}
/**
* Lists every metrics configuration on the bucket. AWS pages these with a continuation token
* once there are more than 100; floci returns them all in one unpaged response, ordered by id
* so that the listing is stable.
*/
public String listBucketMetricsConfigurations(String bucketName) {
Bucket bucket = requireBucket(bucketName);
Map<String, String> configurations = bucket.getMetricsConfigurations() != null
? bucket.getMetricsConfigurations() : Map.of();
XmlBuilder xml = new XmlBuilder().start("ListMetricsConfigurationsResult", AwsNamespaces.S3);
configurations.keySet().stream().sorted().forEach(id -> xml
.start("MetricsConfiguration")
.raw(configurations.get(id))
.end("MetricsConfiguration"));
return METRICS_XML_DECLARATION + xml
.elem("IsTruncated", false)
.end("ListMetricsConfigurationsResult")
.build();
}
public void deleteBucketMetricsConfiguration(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.getMetricsConfigurations();
if (configurations == null || !configurations.containsKey(id)) {
throw noSuchMetricsConfiguration();
}
Map<String, String> remaining = new java.util.LinkedHashMap<>(configurations);
remaining.remove(id);
bucket.setMetricsConfigurations(remaining);
bucketStore.put(bucketName, bucket);
}
LOG.debugv("Deleted metrics configuration {0} from bucket: {1}", id, bucketName);
}
private Bucket requireBucket(String bucketName) {
return bucketStore.get(bucketName)
.orElseThrow(() -> new AwsException("NoSuchBucket",
"The specified bucket does not exist.", 404));
}
/**
* Re-reads the bucket under its monitor and checks it is still the same record. Presence alone
* is not enough: a bucket deleted and recreated under the same name leaves a different record
* in the store, and writing the resolved one back would replace the new bucket with the old
* one's state.
*/
private void requireSameRecord(String bucketName, Bucket resolved) {
if (bucketStore.get(bucketName).orElse(null) != resolved) {
throw new AwsException("NoSuchBucket", "The specified bucket does not exist.", 404);
}
}
private static AwsException noSuchMetricsConfiguration() {
return new AwsException("NoSuchConfiguration", "The specified configuration does not exist.", 404);
}
// --- Object Lock Configuration ---
public void setBucketObjectLockEnabled(String bucketName) {
@@ -31,6 +31,8 @@ public class Bucket {
private String accelerateStatus; // "Enabled" or "Suspended"; null until first PUT
private String region;
private WebsiteConfiguration websiteConfiguration;
/** CloudWatch request metrics configurations, keyed by the id they were stored under. */
private Map<String, String> metricsConfigurations;
public Bucket() {
this.tags = new HashMap<>();
@@ -117,4 +119,7 @@ public class Bucket {
public WebsiteConfiguration getWebsiteConfiguration() { return websiteConfiguration; }
public void setWebsiteConfiguration(WebsiteConfiguration websiteConfiguration) { this.websiteConfiguration = websiteConfiguration; }
public Map<String, String> getMetricsConfigurations() { return metricsConfigurations; }
public void setMetricsConfigurations(Map<String, String> metricsConfigurations) { this.metricsConfigurations = metricsConfigurations; }
}