Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(s3): support bucket analytics and inventory configurations (#3213)

lex00703744c9fb5b
diff --git a/docs/services/s3.md b/docs/services/s3.md
index 2c39ec4b84..ce5eb24a41 100644
--- a/docs/services/s3.md
+++ b/docs/services/s3.md
@@ -26,6 +26,8 @@
| **Public Access Block** | PutPublicAccessBlock, GetPublicAccessBlock, DeletePublicAccessBlock |
| **Metrics** | PutBucketMetricsConfiguration, GetBucketMetricsConfiguration, ListBucketMetricsConfigurations, DeleteBucketMetricsConfiguration |
| **Intelligent-Tiering** | PutBucketIntelligentTieringConfiguration, GetBucketIntelligentTieringConfiguration, ListBucketIntelligentTieringConfigurations, DeleteBucketIntelligentTieringConfiguration |
+| **Analytics** | PutBucketAnalyticsConfiguration, GetBucketAnalyticsConfiguration, ListBucketAnalyticsConfigurations, DeleteBucketAnalyticsConfiguration |
+| **Inventory** | PutBucketInventoryConfiguration, GetBucketInventoryConfiguration, ListBucketInventoryConfigurations, DeleteBucketInventoryConfiguration |
| **Replication** | PutBucketReplication, GetBucketReplication, DeleteBucketReplication |
**RestoreObject** is accepted but stubbed: Floci validates the request and returns `202 Accepted`, but no restore state machine runs.
@@ -174,8 +176,6 @@ These AWS S3 features have no handler in Floci. Calls will return an error (typi
- Access logging (`PutBucketLogging`, `GetBucketLogging`)
- Request payment (`PutBucketRequestPayment`, `GetBucketRequestPayment`)
-- Inventory configurations
-- Analytics configurations
## Configuration
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfiguration.java
new file mode 100644
index 0000000000..d48cdc1729
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfiguration.java
@@ -0,0 +1,163 @@
+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 io.github.hectorvent.floci.core.common.XmlParser.XmlElement;
+
+import java.util.List;
+
+/**
+ * A parsed {@code AnalyticsConfiguration} 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
+ * GetBucketAnalyticsConfiguration or ListBucketAnalyticsConfigurations 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 S3AnalyticsConfiguration(String id, String innerXml) {
+
+ private static final String ROOT = "AnalyticsConfiguration";
+
+ private static final List<String> OUTPUT_SCHEMA_VERSIONS = List.of("V_1");
+ private static final List<String> FORMATS = List.of("CSV");
+
+ /** 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 S3AnalyticsConfiguration parse(String xml) {
+ if (xml == null || xml.isBlank() || !ROOT.equals(XmlParser.rootElementName(xml))) {
+ throw malformed();
+ }
+ XmlElement root = XmlParser.extractElementTree(xml, ROOT);
+ if (root == null) {
+ throw malformed();
+ }
+
+ // The configuration is one Id, at most one Filter and one StorageClassAnalysis, so
+ // anything else under the root is a body AWS would not have accepted.
+ long ids = count(root, "Id");
+ long filters = count(root, "Filter");
+ long analyses = count(root, "StorageClassAnalysis");
+ if (ids != 1 || filters > 1 || analyses != 1
+ || root.children().size() != ids + filters + analyses) {
+ throw malformed();
+ }
+
+ String id = root.child("Id").text();
+ if (id == null || id.isBlank()) {
+ throw malformed();
+ }
+
+ XmlBuilder inner = new XmlBuilder().elem("Id", id);
+ if (filters == 1) {
+ inner.start("Filter").raw(filterXml(root.child("Filter"))).end("Filter");
+ }
+ inner.start("StorageClassAnalysis")
+ .raw(storageClassAnalysisXml(root.child("StorageClassAnalysis")))
+ .end("StorageClassAnalysis");
+ return new S3AnalyticsConfiguration(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(XmlElement filter) {
+ if (filter.children().size() != 1) {
+ throw malformed();
+ }
+ XmlElement predicate = filter.children().getFirst();
+ return switch (predicate.name()) {
+ case "Prefix" -> new XmlBuilder().elem("Prefix", predicate.text()).build();
+ case "Tag" -> tagXml(predicate);
+ case "And" -> {
+ List<XmlElement> conjuncts = predicate.children();
+ long prefixes = count(predicate, "Prefix");
+ long tags = count(predicate, "Tag");
+ // Every conjunct has to be one floci understands, or the filter it stores would
+ // not be the filter that was sent.
+ if (conjuncts.size() < 2 || prefixes > 1 || conjuncts.size() != prefixes + tags) {
+ throw malformed();
+ }
+ XmlBuilder and = new XmlBuilder().start("And");
+ if (prefixes == 1) {
+ and.elem("Prefix", predicate.child("Prefix").text());
+ }
+ conjuncts.stream().filter(c -> "Tag".equals(c.name()))
+ .forEach(tag -> and.raw(tagXml(tag)));
+ yield and.end("And").build();
+ }
+ default -> throw malformed();
+ };
+ }
+
+ /** A tag carries both a key and a value, so either one missing is a schema violation. */
+ private static String tagXml(XmlElement tag) {
+ XmlElement key = tag.child("Key");
+ XmlElement value = tag.child("Value");
+ if (key == null || key.text().isBlank() || value == null || tag.children().size() != 2) {
+ throw malformed();
+ }
+ return new XmlBuilder().start("Tag").elem("Key", key.text()).elem("Value", value.text()).end("Tag").build();
+ }
+
+ /**
+ * Serializes the storage class analysis. It holds at most one DataExport, and an export names
+ * the output schema version and a destination bucket, with the account id and prefix optional.
+ */
+ private static String storageClassAnalysisXml(XmlElement analysis) {
+ long exports = count(analysis, "DataExport");
+ if (exports > 1 || analysis.children().size() != exports) {
+ throw malformed();
+ }
+ if (exports == 0) {
+ return "";
+ }
+ XmlElement export = analysis.child("DataExport");
+ XmlElement version = export.child("OutputSchemaVersion");
+ XmlElement destination = export.child("Destination");
+ if (version == null || !OUTPUT_SCHEMA_VERSIONS.contains(version.text())
+ || destination == null || export.children().size() != 2) {
+ throw malformed();
+ }
+ XmlElement bucketDestination = destination.child("S3BucketDestination");
+ if (bucketDestination == null || destination.children().size() != 1) {
+ throw malformed();
+ }
+ XmlElement format = bucketDestination.child("Format");
+ XmlElement bucket = bucketDestination.child("Bucket");
+ XmlElement accountId = bucketDestination.child("BucketAccountId");
+ XmlElement prefix = bucketDestination.child("Prefix");
+ int expected = 2 + (accountId != null ? 1 : 0) + (prefix != null ? 1 : 0);
+ if (format == null || !FORMATS.contains(format.text())
+ || bucket == null || bucket.text().isBlank()
+ || bucketDestination.children().size() != expected) {
+ throw malformed();
+ }
+
+ XmlBuilder out = new XmlBuilder()
+ .start("DataExport")
+ .elem("OutputSchemaVersion", version.text())
+ .start("Destination")
+ .start("S3BucketDestination")
+ .elem("Format", format.text());
+ if (accountId != null) {
+ out.elem("BucketAccountId", accountId.text());
+ }
+ out.elem("Bucket", bucket.text());
+ if (prefix != null) {
+ out.elem("Prefix", prefix.text());
+ }
+ return out.end("S3BucketDestination").end("Destination").end("DataExport").build();
+ }
+
+ private static long count(XmlElement parent, String childName) {
+ return parent.children().stream().filter(child -> childName.equals(child.name())).count();
+ }
+}
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 04c9a45d52..55ad3066cd 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
@@ -347,6 +347,20 @@ public class S3Controller {
s3Service.authorizeBucketWrite(bucket, "s3:PutIntelligentTieringConfiguration", authorization);
return handlePutBucketIntelligentTieringConfiguration(bucket, uriInfo, body);
}
+ // Same fall-through hazard as metrics: an analytics or inventory PUT must not become
+ // a CreateBucket.
+ if (hasQueryParam(uriInfo, "analytics")) {
+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);
+ s3Service.authorizeBucketWrite(bucket, "s3:PutAnalyticsConfiguration", authorization);
+ return handlePutBucketAnalyticsConfiguration(bucket, uriInfo, body);
+ }
+ if (hasQueryParam(uriInfo, "inventory")) {
+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);
+ s3Service.authorizeBucketWrite(bucket, "s3:PutInventoryConfiguration", authorization);
+ return handlePutBucketInventoryConfiguration(bucket, uriInfo, body);
+ }
String locationConstraint = null;
if (body != null && body.length > 0) {
@@ -443,6 +457,22 @@ public class S3Controller {
requireIntelligentTieringId(uriInfo));
return Response.noContent().build();
}
+ if (hasQueryParam(uriInfo, "analytics")) {
+ // Likewise this must not fall through to deleting the bucket.
+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);
+ s3Service.authorizeBucketWrite(bucket, "s3:PutAnalyticsConfiguration", authorization);
+ s3Service.deleteBucketAnalyticsConfiguration(bucket, requireAnalyticsId(uriInfo));
+ return Response.noContent().build();
+ }
+ if (hasQueryParam(uriInfo, "inventory")) {
+ // Likewise this must not fall through to deleting the bucket.
+ S3Service.RequestAuthorization authorization = S3RequestAuthorizationParser.parseIfRequired(
+ s3Service.isAuthEnforced(), httpHeaders, uriInfo);
+ s3Service.authorizeBucketWrite(bucket, "s3:PutInventoryConfiguration", authorization);
+ s3Service.deleteBucketInventoryConfiguration(bucket, requireInventoryId(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.
@@ -579,6 +609,27 @@ public class S3Controller {
: s3Service.listBucketIntelligentTieringConfigurations(bucket);
return Response.ok(xml).type("application/xml").build();
}
+ // GetBucketAnalyticsConfiguration and ListBucketAnalyticsConfigurations share
+ // ?analytics and are told apart by the id, which only the single-configuration read
+ // carries.
+ if (hasQueryParam(uriInfo, "analytics")) {
+ s3Service.authorizeBucketRead(bucket, "s3:GetAnalyticsConfiguration", authorization);
+ String id = uriInfo.getQueryParameters().getFirst("id");
+ String xml = id != null
+ ? s3Service.getBucketAnalyticsConfiguration(bucket, id)
+ : s3Service.listBucketAnalyticsConfigurations(bucket);
+ return Response.ok(xml).type("application/xml").build();
+ }
+ // GetBucketInventoryConfiguration and ListBucketInventoryConfigurations share
+ // ?inventory and are told apart the same way.
+ if (hasQueryParam(uriInfo, "inventory")) {
+ s3Service.authorizeBucketRead(bucket, "s3:GetInventoryConfiguration", authorization);
+ String id = uriInfo.getQueryParameters().getFirst("id");
+ String xml = id != null
+ ? s3Service.getBucketInventoryConfiguration(bucket, id)
+ : s3Service.listBucketInventoryConfigurations(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
@@ -1947,6 +1998,64 @@ public class S3Controller {
return id;
}
+ // --- Analytics Configurations ---
+
+ private Response handlePutBucketAnalyticsConfiguration(String bucket, UriInfo uriInfo, byte[] body) {
+ String id = requireAnalyticsId(uriInfo);
+ String xml = body == null ? null : new String(body, StandardCharsets.UTF_8);
+ S3AnalyticsConfiguration configuration = S3AnalyticsConfiguration.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.putBucketAnalyticsConfiguration(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 requireAnalyticsId(UriInfo uriInfo) {
+ String id = uriInfo.getQueryParameters().getFirst("id");
+ if (id == null) {
+ throw new AwsException("InvalidArgument",
+ "The analytics configuration id must be specified.", 400);
+ }
+ return id;
+ }
+
+ // --- Inventory Configurations ---
+
+ private Response handlePutBucketInventoryConfiguration(String bucket, UriInfo uriInfo, byte[] body) {
+ String id = requireInventoryId(uriInfo);
+ String xml = body == null ? null : new String(body, StandardCharsets.UTF_8);
+ S3InventoryConfiguration configuration = S3InventoryConfiguration.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.putBucketInventoryConfiguration(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 requireInventoryId(UriInfo uriInfo) {
+ String id = uriInfo.getQueryParameters().getFirst("id");
+ if (id == null) {
+ throw new AwsException("InvalidArgument",
+ "The inventory configuration id must be specified.", 400);
+ }
+ return id;
+ }
+
// --- Object Tagging ---
private Response handlePutObjectTagging(String bucket, String key, byte[] body) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/s3/S3InventoryConfiguration.java b/src/main/java/io/github/hectorvent/floci/services/s3/S3InventoryConfiguration.java
new file mode 100644
index 0000000000..fba9c40919
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/s3/S3InventoryConfiguration.java
@@ -0,0 +1,176 @@
+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 io.github.hectorvent.floci.core.common.XmlParser.XmlElement;
+
+import java.util.List;
+
+/**
+ * A parsed {@code InventoryConfiguration} 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
+ * GetBucketInventoryConfiguration or ListBucketInventoryConfigurations 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 S3InventoryConfiguration(String id, String innerXml) {
+
+ private static final String ROOT = "InventoryConfiguration";
+
+ private static final List<String> ENABLED = List.of("true", "false");
+ private static final List<String> INCLUDED_OBJECT_VERSIONS = List.of("All", "Current");
+ private static final List<String> FREQUENCIES = List.of("Daily", "Weekly");
+ private static final List<String> FORMATS = List.of("CSV", "ORC", "Parquet");
+ private static final List<String> FIELDS = List.of(
+ "Size", "LastModifiedDate", "StorageClass", "ETag", "IsMultipartUploaded",
+ "ReplicationStatus", "EncryptionStatus", "ObjectLockRetainUntilDate", "ObjectLockMode",
+ "ObjectLockLegalHoldStatus", "IntelligentTieringAccessTier", "BucketKeyStatus",
+ "ChecksumAlgorithm", "ObjectAccessControlList", "ObjectOwner");
+
+ /** 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 S3InventoryConfiguration parse(String xml) {
+ if (xml == null || xml.isBlank() || !ROOT.equals(XmlParser.rootElementName(xml))) {
+ throw malformed();
+ }
+ XmlElement root = XmlParser.extractElementTree(xml, ROOT);
+ if (root == null) {
+ throw malformed();
+ }
+
+ // The configuration is one each of Id, IsEnabled, IncludedObjectVersions, Schedule and
+ // Destination, with Filter and OptionalFields at most once, so anything else under the
+ // root is a body AWS would not have accepted.
+ long filters = count(root, "Filter");
+ long optionalFields = count(root, "OptionalFields");
+ if (count(root, "Id") != 1 || count(root, "IsEnabled") != 1
+ || count(root, "IncludedObjectVersions") != 1 || count(root, "Schedule") != 1
+ || count(root, "Destination") != 1 || filters > 1 || optionalFields > 1
+ || root.children().size() != 5 + filters + optionalFields) {
+ throw malformed();
+ }
+
+ String id = root.child("Id").text();
+ String enabled = root.child("IsEnabled").text();
+ String versions = root.child("IncludedObjectVersions").text();
+ if (id == null || id.isBlank() || !ENABLED.contains(enabled)
+ || !INCLUDED_OBJECT_VERSIONS.contains(versions)) {
+ throw malformed();
+ }
+
+ XmlBuilder inner = new XmlBuilder()
+ .elem("Id", id)
+ .elem("IsEnabled", enabled)
+ .start("Destination").raw(destinationXml(root.child("Destination"))).end("Destination")
+ .start("Schedule").raw(scheduleXml(root.child("Schedule"))).end("Schedule");
+ if (filters == 1) {
+ inner.start("Filter").raw(filterXml(root.child("Filter"))).end("Filter");
+ }
+ inner.elem("IncludedObjectVersions", versions);
+ if (optionalFields == 1) {
+ inner.start("OptionalFields").raw(optionalFieldsXml(root.child("OptionalFields"))).end("OptionalFields");
+ }
+ return new S3InventoryConfiguration(id, inner.build());
+ }
+
+ /**
+ * Serializes the destination. An inventory report lands in exactly one S3 bucket, named by
+ * ARN with a required format, and the account id, prefix and encryption are optional.
+ */
+ private static String destinationXml(XmlElement destination) {
+ XmlElement bucketDestination = destination.child("S3BucketDestination");
+ if (bucketDestination == null || destination.children().size() != 1) {
+ throw malformed();
+ }
+ XmlElement accountId = bucketDestination.child("AccountId");
+ XmlElement bucket = bucketDestination.child("Bucket");
+ XmlElement format = bucketDestination.child("Format");
+ XmlElement prefix = bucketDestination.child("Prefix");
+ XmlElement encryption = bucketDestination.child("Encryption");
+ int expected = 2 + (accountId != null ? 1 : 0) + (prefix != null ? 1 : 0)
+ + (encryption != null ? 1 : 0);
+ if (bucket == null || bucket.text().isBlank()
+ || format == null || !FORMATS.contains(format.text())
+ || bucketDestination.children().size() != expected) {
+ throw malformed();
+ }
+
+ XmlBuilder out = new XmlBuilder().start("S3BucketDestination");
+ out.elem("Format", format.text());
+ if (accountId != null) {
+ out.elem("AccountId", accountId.text());
+ }
+ out.elem("Bucket", bucket.text());
+ if (prefix != null) {
+ out.elem("Prefix", prefix.text());
+ }
+ if (encryption != null) {
+ out.start("Encryption").raw(encryptionXml(encryption)).end("Encryption");
+ }
+ return out.end("S3BucketDestination").build();
+ }
+
+ /** The report is encrypted with exactly one of SSE-S3 or SSE-KMS, and SSE-KMS names its key. */
+ private static String encryptionXml(XmlElement encryption) {
+ if (encryption.children().size() != 1) {
+ throw malformed();
+ }
+ XmlElement method = encryption.children().getFirst();
+ return switch (method.name()) {
+ case "SSE-S3" -> {
+ if (!method.children().isEmpty()) {
+ throw malformed();
+ }
+ yield "<SSE-S3/>";
+ }
+ case "SSE-KMS" -> {
+ XmlElement keyId = method.child("KeyId");
+ if (keyId == null || keyId.text().isBlank() || method.children().size() != 1) {
+ throw malformed();
+ }
+ yield new XmlBuilder().start("SSE-KMS").elem("KeyId", keyId.text()).end("SSE-KMS").build();
+ }
+ default -> throw malformed();
+ };
+ }
+
+ private static String scheduleXml(XmlElement schedule) {
+ XmlElement frequency = schedule.child("Frequency");
+ if (frequency == null || !FREQUENCIES.contains(frequency.text()) || schedule.children().size() != 1) {
+ throw malformed();
+ }
+ return new XmlBuilder().elem("Frequency", frequency.text()).build();
+ }
+
+ /** An inventory filter is a prefix and nothing else. */
+ private static String filterXml(XmlElement filter) {
+ XmlElement prefix = filter.child("Prefix");
+ if (prefix == null || filter.children().size() != 1) {
+ throw malformed();
+ }
+ return new XmlBuilder().elem("Prefix", prefix.text()).build();
+ }
+
+ /** Every optional field has to be one AWS defines, or the stored report shape would be wrong. */
+ private static String optionalFieldsXml(XmlElement optionalFields) {
+ XmlBuilder out = new XmlBuilder();
+ for (XmlElement field : optionalFields.children()) {
+ if (!"Field".equals(field.name()) || !FIELDS.contains(field.text())) {
+ throw malformed();
+ }
+ out.elem("Field", field.text());
+ }
+ return out.build();
+ }
+
+ private static long count(XmlElement parent, String childName) {
+ return parent.children().stream().filter(child -> childName.equals(child.name())).count();
+ }
+}
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 b62c1a444a..43e546def9 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
@@ -2013,6 +2013,168 @@ public class S3Service implements Resettable, ResourceProvider {
return new AwsException("NoSuchConfiguration", "The specified configuration does not exist.", 404);
}
+ // --- Analytics Configurations ---
+
+ /**
+ * Stores an analytics configuration under {@code id}, replacing any configuration
+ * already stored under it. floci records the configuration and returns it; nothing is
+ * produced from it.
+ */
+ public void putBucketAnalyticsConfiguration(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.getAnalyticsConfigurations() != null
+ ? new java.util.LinkedHashMap<>(bucket.getAnalyticsConfigurations())
+ : new java.util.LinkedHashMap<>();
+ configurations.put(id, innerXml);
+ bucket.setAnalyticsConfigurations(configurations);
+ bucketStore.put(bucketName, bucket);
+ }
+ LOG.debugv("Put analytics configuration {0} on bucket: {1}", id, bucketName);
+ }
+
+ public String getBucketAnalyticsConfiguration(String bucketName, String id) {
+ Bucket bucket = requireBucket(bucketName);
+ String innerXml = bucket.getAnalyticsConfigurations() == null
+ ? null : bucket.getAnalyticsConfigurations().get(id);
+ if (innerXml == null) {
+ throw noSuchAnalyticsConfiguration();
+ }
+ return S3_XML_DECLARATION + new XmlBuilder()
+ .start("AnalyticsConfiguration", AwsNamespaces.S3)
+ .raw(innerXml)
+ .end("AnalyticsConfiguration")
+ .build();
+ }
+
+ /**
+ * Lists every analytics 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 listBucketAnalyticsConfigurations(String bucketName) {
+ Bucket bucket = requireBucket(bucketName);
+ Map<String, String> configurations = bucket.getAnalyticsConfigurations() != null
+ ? bucket.getAnalyticsConfigurations() : Map.of();
+
+ XmlBuilder xml = new XmlBuilder().start("ListBucketAnalyticsConfigurationResult", AwsNamespaces.S3);
+ configurations.keySet().stream().sorted().forEach(id -> xml
+ .start("AnalyticsConfiguration")
+ .raw(configurations.get(id))
+ .end("AnalyticsConfiguration"));
+ return S3_XML_DECLARATION + xml
+ .elem("IsTruncated", false)
+ .end("ListBucketAnalyticsConfigurationResult")
+ .build();
+ }
+
+ public void deleteBucketAnalyticsConfiguration(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.getAnalyticsConfigurations();
+ if (configurations == null || !configurations.containsKey(id)) {
+ throw noSuchAnalyticsConfiguration();
+ }
+ Map<String, String> remaining = new java.util.LinkedHashMap<>(configurations);
+ remaining.remove(id);
+ bucket.setAnalyticsConfigurations(remaining);
+ bucketStore.put(bucketName, bucket);
+ }
+ LOG.debugv("Deleted analytics configuration {0} from bucket: {1}", id, bucketName);
+ }
+
+ private static AwsException noSuchAnalyticsConfiguration() {
+ return new AwsException("NoSuchConfiguration", "The specified configuration does not exist.", 404);
+ }
+
+ // --- Inventory Configurations ---
+
+ /**
+ * Stores an inventory configuration under {@code id}, replacing any configuration
+ * already stored under it. floci records the configuration and returns it; nothing is
+ * produced from it.
+ */
+ public void putBucketInventoryConfiguration(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.getInventoryConfigurations() != null
+ ? new java.util.LinkedHashMap<>(bucket.getInventoryConfigurations())
+ : new java.util.LinkedHashMap<>();
+ configurations.put(id, innerXml);
+ bucket.setInventoryConfigurations(configurations);
+ bucketStore.put(bucketName, bucket);
+ }
+ LOG.debugv("Put inventory configuration {0} on bucket: {1}", id, bucketName);
+ }
+
+ public String getBucketInventoryConfiguration(String bucketName, String id) {
+ Bucket bucket = requireBucket(bucketName);
+ String innerXml = bucket.getInventoryConfigurations() == null
+ ? null : bucket.getInventoryConfigurations().get(id);
+ if (innerXml == null) {
+ throw noSuchInventoryConfiguration();
+ }
+ return S3_XML_DECLARATION + new XmlBuilder()
+ .start("InventoryConfiguration", AwsNamespaces.S3)
+ .raw(innerXml)
+ .end("InventoryConfiguration")
+ .build();
+ }
+
+ /**
+ * Lists every inventory 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 listBucketInventoryConfigurations(String bucketName) {
+ Bucket bucket = requireBucket(bucketName);
+ Map<String, String> configurations = bucket.getInventoryConfigurations() != null
+ ? bucket.getInventoryConfigurations() : Map.of();
+
+ XmlBuilder xml = new XmlBuilder().start("ListInventoryConfigurationsResult", AwsNamespaces.S3);
+ configurations.keySet().stream().sorted().forEach(id -> xml
+ .start("InventoryConfiguration")
+ .raw(configurations.get(id))
+ .end("InventoryConfiguration"));
+ return S3_XML_DECLARATION + xml
+ .elem("IsTruncated", false)
+ .end("ListInventoryConfigurationsResult")
+ .build();
+ }
+
+ public void deleteBucketInventoryConfiguration(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.getInventoryConfigurations();
+ if (configurations == null || !configurations.containsKey(id)) {
+ throw noSuchInventoryConfiguration();
+ }
+ Map<String, String> remaining = new java.util.LinkedHashMap<>(configurations);
+ remaining.remove(id);
+ bucket.setInventoryConfigurations(remaining);
+ bucketStore.put(bucketName, bucket);
+ }
+ LOG.debugv("Deleted inventory configuration {0} from bucket: {1}", id, bucketName);
+ }
+
+ private static AwsException noSuchInventoryConfiguration() {
+ return new AwsException("NoSuchConfiguration", "The specified configuration does not exist.", 404);
+ }
+
// --- Object Lock Configuration ---
public void setBucketObjectLockEnabled(String bucketName) {
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 3d789a992e..aba414dd02 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
@@ -36,6 +36,10 @@ public class Bucket {
private Map<String, String> metricsConfigurations;
/** Intelligent-Tiering configurations, keyed by the id they were stored under. */
private Map<String, String> intelligentTieringConfigurations;
+ /** Storage class analysis configurations, keyed by the id they were stored under. */
+ private Map<String, String> analyticsConfigurations;
+ /** Inventory configurations, keyed by the id they were stored under. */
+ private Map<String, String> inventoryConfigurations;
public Bucket() {
this.tags = new HashMap<>();
@@ -134,4 +138,14 @@ public class Bucket {
public void setIntelligentTieringConfigurations(Map<String, String> intelligentTieringConfigurations) {
this.intelligentTieringConfigurations = intelligentTieringConfigurations;
}
+
+ public Map<String, String> getAnalyticsConfigurations() { return analyticsConfigurations; }
+ public void setAnalyticsConfigurations(Map<String, String> analyticsConfigurations) {
+ this.analyticsConfigurations = analyticsConfigurations;
+ }
+
+ public Map<String, String> getInventoryConfigurations() { return inventoryConfigurations; }
+ public void setInventoryConfigurations(Map<String, String> inventoryConfigurations) {
+ this.inventoryConfigurations = inventoryConfigurations;
+ }
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfigurationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfigurationIntegrationTest.java
new file mode 100644
index 0000000000..b973b75e34
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfigurationIntegrationTest.java
@@ -0,0 +1,217 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class S3AnalyticsConfigurationIntegrationTest {
+
+ private static final String BUCKET = "analytics-int-test";
+
+ private static String configuration(String id, String filter) {
+ return """
+ <AnalyticsConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+ <Id>%s</Id>
+ %s
+ <StorageClassAnalysis>
+ <DataExport>
+ <OutputSchemaVersion>V_1</OutputSchemaVersion>
+ <Destination>
+ <S3BucketDestination>
+ <Format>CSV</Format>
+ <BucketAccountId>123456789012</BucketAccountId>
+ <Bucket>arn:aws:s3:::analytics-destination</Bucket>
+ <Prefix>exports/</Prefix>
+ </S3BucketDestination>
+ </Destination>
+ </DataExport>
+ </StorageClassAnalysis>
+ </AnalyticsConfiguration>
+ """.formatted(id, filter);
+ }
+
+ @Test
+ @Order(1)
+ void createBucket() {
+ given()
+ .when()
+ .put("/" + BUCKET)
+ .then()
+ .statusCode(200);
+ }
+
+ /**
+ * {@code PUT /{bucket}?analytics} must be handled before the unqualified CreateBucket, which
+ * would otherwise answer with BucketAlreadyOwnedByYou. Real S3 stores the configuration and
+ * returns 204.
+ */
+ @Test
+ @Order(2)
+ void putAnalyticsConfigurationIsNotTreatedAsCreateBucket() {
+ given()
+ .body(configuration("EntireBucket", ""))
+ .when()
+ .put("/" + BUCKET + "?analytics&id=EntireBucket")
+ .then()
+ .statusCode(204)
+ .body(not(containsString("BucketAlreadyOwnedByYou")));
+ }
+
+ @Test
+ @Order(3)
+ void getAnalyticsConfigurationReturnsWhatWasStored() {
+ given()
+ .when()
+ .get("/" + BUCKET + "?analytics&id=EntireBucket")
+ .then()
+ .statusCode(200)
+ .body(containsString("<AnalyticsConfiguration"))
+ .body(containsString("<Id>EntireBucket</Id>"))
+ .body(containsString("<OutputSchemaVersion>V_1</OutputSchemaVersion>"))
+ .body(containsString("<BucketAccountId>123456789012</BucketAccountId>"))
+ .body(containsString("<Bucket>arn:aws:s3:::analytics-destination</Bucket>"));
+ }
+
+ @Test
+ @Order(4)
+ void putFilteredConfigurationKeepsTheFilter() {
+ given()
+ .body(configuration("Filtered", """
+ <Filter>
+ <And>
+ <Prefix>logs/</Prefix>
+ <Tag><Key>env</Key><Value>prod</Value></Tag>
+ <Tag><Key>team</Key><Value>core</Value></Tag>
+ </And>
+ </Filter>
+ """))
+ .when()
+ .put("/" + BUCKET + "?analytics&id=Filtered")
+ .then()
+ .statusCode(204);
+
+ // AWS repeats <Tag> inside <And> with no wrapping element.
+ given()
+ .when()
+ .get("/" + BUCKET + "?analytics&id=Filtered")
+ .then()
+ .statusCode(200)
+ .body(containsString("<And><Prefix>logs/</Prefix>"
+ + "<Tag><Key>env</Key><Value>prod</Value></Tag>"
+ + "<Tag><Key>team</Key><Value>core</Value></Tag></And>"));
+ }
+
+ @Test
+ @Order(5)
+ void listWithoutAnIdReturnsEveryConfiguration() {
+ given()
+ .when()
+ .get("/" + BUCKET + "?analytics")
+ .then()
+ .statusCode(200)
+ .body(containsString("<ListBucketAnalyticsConfigurationResult"))
+ .body(containsString("<Id>EntireBucket</Id>"))
+ .body(containsString("<Id>Filtered</Id>"))
+ .body(containsString("<IsTruncated>false</IsTruncated>"));
+ }
+
+ @Test
+ @Order(6)
+ void idInTheBodyMustMatchTheIdInTheQuery() {
+ given()
+ .body(configuration("Different", ""))
+ .when()
+ .put("/" + BUCKET + "?analytics&id=Mismatch")
+ .then()
+ .statusCode(400)
+ .body(containsString("MalformedXML"));
+ }
+
+ @Test
+ @Order(7)
+ void unknownIdIsNotFound() {
+ given()
+ .when()
+ .get("/" + BUCKET + "?analytics&id=absent")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchConfiguration"));
+
+ // AWS does not treat deleting an absent configuration as a no-op.
+ given()
+ .when()
+ .delete("/" + BUCKET + "?analytics&id=absent")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchConfiguration"));
+ }
+
+ /**
+ * {@code DELETE /{bucket}?analytics} must not fall through to the unqualified DeleteBucket
+ * and remove the whole bucket.
+ */
+ @Test
+ @Order(8)
+ void deleteAnalyticsConfigurationDoesNotDeleteBucket() {
+ given()
+ .when()
+ .delete("/" + BUCKET + "?analytics&id=EntireBucket")
+ .then()
+ .statusCode(204);
+
+ given()
+ .when()
+ .get("/" + BUCKET + "?analytics&id=Filtered")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/" + BUCKET + "?analytics&id=EntireBucket")
+ .then()
+ .statusCode(404);
+ }
+
+ @Test
+ @Order(9)
+ void aRequestWithoutAnIdIsRefusedRatherThanGuessedAt() {
+ given()
+ .body(configuration("EntireBucket", ""))
+ .when()
+ .put("/" + BUCKET + "?analytics")
+ .then()
+ .statusCode(400)
+ .body(containsString("InvalidArgument"));
+
+ given()
+ .when()
+ .delete("/" + BUCKET + "?analytics")
+ .then()
+ .statusCode(400)
+ .body(containsString("InvalidArgument"));
+ }
+
+ @Test
+ @Order(10)
+ void unqualifiedDeleteStillRemovesBucket() {
+ given()
+ .when()
+ .delete("/" + BUCKET)
+ .then()
+ .statusCode(204);
+ given()
+ .when()
+ .get("/" + BUCKET + "?analytics")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchBucket"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfigurationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfigurationTest.java
new file mode 100644
index 0000000000..28f3ddc5f1
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3AnalyticsConfigurationTest.java
@@ -0,0 +1,133 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class S3AnalyticsConfigurationTest {
+
+ private static final String NS = "http://s3.amazonaws.com/doc/2006-03-01/";
+
+ private static final String EXPORT = "<StorageClassAnalysis><DataExport>"
+ + "<OutputSchemaVersion>V_1</OutputSchemaVersion>"
+ + "<Destination><S3BucketDestination>"
+ + "<Format>CSV</Format>"
+ + "<BucketAccountId>123456789012</BucketAccountId>"
+ + "<Bucket>arn:aws:s3:::destination-bucket</Bucket>"
+ + "<Prefix>reports/</Prefix>"
+ + "</S3BucketDestination></Destination>"
+ + "</DataExport></StorageClassAnalysis>";
+
+ private static String body(String inner) {
+ return "<AnalyticsConfiguration xmlns=\"" + NS + "\">" + inner + "</AnalyticsConfiguration>";
+ }
+
+ @Test
+ void parsesAnIdWithAnEmptyAnalysisAndNoFilter() {
+ S3AnalyticsConfiguration parsed = S3AnalyticsConfiguration.parse(
+ body("<Id>whole</Id><StorageClassAnalysis/>"));
+
+ assertEquals("whole", parsed.id());
+ assertEquals("<Id>whole</Id><StorageClassAnalysis></StorageClassAnalysis>", parsed.innerXml());
+ }
+
+ @Test
+ void serializesTheExportInAwsOrderWhateverOrderItArrivedIn() {
+ String shuffled = "<StorageClassAnalysis><DataExport>"
+ + "<Destination><S3BucketDestination>"
+ + "<Prefix>reports/</Prefix>"
+ + "<Bucket>arn:aws:s3:::destination-bucket</Bucket>"
+ + "<BucketAccountId>123456789012</BucketAccountId>"
+ + "<Format>CSV</Format>"
+ + "</S3BucketDestination></Destination>"
+ + "<OutputSchemaVersion>V_1</OutputSchemaVersion>"
+ + "</DataExport></StorageClassAnalysis>";
+
+ assertEquals("<Id>a</Id>" + EXPORT,
+ S3AnalyticsConfiguration.parse(body("<Id>a</Id>" + shuffled)).innerXml());
+ }
+
+ @Test
+ void parsesEachSingleFilterPredicate() {
+ assertEquals("<Id>a</Id><Filter><Prefix>logs/</Prefix></Filter><StorageClassAnalysis></StorageClassAnalysis>",
+ S3AnalyticsConfiguration.parse(body(
+ "<Id>a</Id><Filter><Prefix>logs/</Prefix></Filter><StorageClassAnalysis/>")).innerXml());
+
+ assertEquals("<Id>a</Id><Filter><Tag><Key>env</Key><Value>prod</Value></Tag></Filter>"
+ + "<StorageClassAnalysis></StorageClassAnalysis>",
+ S3AnalyticsConfiguration.parse(body(
+ "<Id>a</Id><Filter><Tag><Key>env</Key><Value>prod</Value></Tag></Filter>"
+ + "<StorageClassAnalysis/>")).innerXml());
+ }
+
+ @Test
+ void parsesAnAndConjunctionKeepingEveryTag() {
+ String parsed = S3AnalyticsConfiguration.parse(body("""
+ <Id>a</Id>
+ <Filter>
+ <And>
+ <Prefix>logs/</Prefix>
+ <Tag><Key>env</Key><Value>prod</Value></Tag>
+ <Tag><Key>team</Key><Value>core</Value></Tag>
+ </And>
+ </Filter>
+ <StorageClassAnalysis/>
+ """)).innerXml();
+
+ assertEquals("<Id>a</Id><Filter><And><Prefix>logs/</Prefix>"
+ + "<Tag><Key>env</Key><Value>prod</Value></Tag>"
+ + "<Tag><Key>team</Key><Value>core</Value></Tag></And></Filter>"
+ + "<StorageClassAnalysis></StorageClassAnalysis>", parsed);
+ }
+
+ @Test
+ void escapesValuesOnTheWayBackOut() {
+ String parsed = S3AnalyticsConfiguration.parse(
+ body("<Id>a&amp;b</Id><Filter><Prefix>x&lt;y</Prefix></Filter><StorageClassAnalysis/>")).innerXml();
+
+ assertEquals("<Id>a&amp;b</Id><Filter><Prefix>x&lt;y</Prefix></Filter>"
+ + "<StorageClassAnalysis></StorageClassAnalysis>", parsed);
+ }
+
+ @Test
+ void rejectsBodiesThatDoNotMatchTheSchema() {
+ // Missing id, missing analysis, stray elements, wrong root element, empty and non-XML
+ // bodies are all MalformedXML on AWS.
+ for (String invalid : new String[]{
+ body(""),
+ body("<Id> </Id><StorageClassAnalysis/>"),
+ body("<StorageClassAnalysis/>"),
+ body("<Id>a</Id>"),
+ body("<Id>a</Id><Unknown/><StorageClassAnalysis/>"),
+ body("<Id>a</Id><Filter></Filter><StorageClassAnalysis/>"),
+ body("<Id>a</Id><Filter><And><Prefix>p</Prefix></And></Filter><StorageClassAnalysis/>"),
+ body("<Id>a</Id><Filter><Tag><Key>k</Key></Tag></Filter><StorageClassAnalysis/>"),
+ "<SomethingElse><Id>a</Id></SomethingElse>",
+ "not xml at all",
+ ""}) {
+ AwsException e = assertThrows(AwsException.class, () -> S3AnalyticsConfiguration.parse(invalid),
+ () -> "expected rejection of: " + invalid);
+ assertEquals("MalformedXML", e.getErrorCode());
+ assertEquals(400, e.getHttpStatus());
+ }
+ }
+
+ @Test
+ void rejectsExportsOutsideTheSchema() {
+ String unknownVersion = EXPORT.replace("V_1", "V_2");
+ String unknownFormat = EXPORT.replace("CSV", "ORC");
+ String missingBucket = EXPORT.replace("<Bucket>arn:aws:s3:::destination-bucket</Bucket>", "");
+ String missingVersion = EXPORT.replace("<OutputSchemaVersion>V_1</OutputSchemaVersion>", "");
+ String strayElement = EXPORT.replace("<Format>CSV</Format>", "<Format>CSV</Format><Region>eu</Region>");
+
+ for (String invalid : new String[]{
+ unknownVersion, unknownFormat, missingBucket, missingVersion, strayElement}) {
+ AwsException e = assertThrows(AwsException.class,
+ () -> S3AnalyticsConfiguration.parse(body("<Id>a</Id>" + invalid)),
+ () -> "expected rejection of: " + invalid);
+ assertEquals("MalformedXML", e.getErrorCode());
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3InventoryConfigurationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3InventoryConfigurationIntegrationTest.java
new file mode 100644
index 0000000000..44151b2093
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3InventoryConfigurationIntegrationTest.java
@@ -0,0 +1,214 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class S3InventoryConfigurationIntegrationTest {
+
+ private static final String BUCKET = "inventory-int-test";
+
+ private static String configuration(String id, String extras) {
+ return """
+ <InventoryConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
+ <Id>%s</Id>
+ <IsEnabled>true</IsEnabled>
+ <Destination>
+ <S3BucketDestination>
+ <Format>CSV</Format>
+ <AccountId>123456789012</AccountId>
+ <Bucket>arn:aws:s3:::inventory-destination</Bucket>
+ <Prefix>inventory/</Prefix>
+ </S3BucketDestination>
+ </Destination>
+ <Schedule>
+ <Frequency>Daily</Frequency>
+ </Schedule>
+ <IncludedObjectVersions>All</IncludedObjectVersions>
+ %s
+ </InventoryConfiguration>
+ """.formatted(id, extras);
+ }
+
+ @Test
+ @Order(1)
+ void createBucket() {
+ given()
+ .when()
+ .put("/" + BUCKET)
+ .then()
+ .statusCode(200);
+ }
+
+ /**
+ * {@code PUT /{bucket}?inventory} must be handled before the unqualified CreateBucket, which
+ * would otherwise answer with BucketAlreadyOwnedByYou. Real S3 stores the configuration and
+ * returns 204.
+ */
+ @Test
+ @Order(2)
+ void putInventoryConfigurationIsNotTreatedAsCreateBucket() {
+ given()
+ .body(configuration("report1", ""))
+ .when()
+ .put("/" + BUCKET + "?inventory&id=report1")
+ .then()
+ .statusCode(204)
+ .body(not(containsString("BucketAlreadyOwnedByYou")));
+ }
+
+ @Test
+ @Order(3)
+ void getInventoryConfigurationReturnsWhatWasStored() {
+ given()
+ .when()
+ .get("/" + BUCKET + "?inventory&id=report1")
+ .then()
+ .statusCode(200)
+ .body(containsString("<InventoryConfiguration"))
+ .body(containsString("<Id>report1</Id>"))
+ .body(containsString("<IsEnabled>true</IsEnabled>"))
+ .body(containsString("<Frequency>Daily</Frequency>"))
+ .body(containsString("<IncludedObjectVersions>All</IncludedObjectVersions>"))
+ .body(containsString("<Bucket>arn:aws:s3:::inventory-destination</Bucket>"));
+ }
+
+ @Test
+ @Order(4)
+ void putConfigurationWithFilterAndOptionalFieldsKeepsThem() {
+ given()
+ .body(configuration("report2", """
+ <Filter><Prefix>docs/</Prefix></Filter>
+ <OptionalFields>
+ <Field>Size</Field>
+ <Field>LastModifiedDate</Field>
+ </OptionalFields>
+ """))
+ .when()
+ .put("/" + BUCKET + "?inventory&id=report2")
+ .then()
+ .statusCode(204);
+
+ given()
+ .when()
+ .get("/" + BUCKET + "?inventory&id=report2")
+ .then()
+ .statusCode(200)
+ .body(containsString("<Filter><Prefix>docs/</Prefix></Filter>"))
+ .body(containsString("<OptionalFields><Field>Size</Field><Field>LastModifiedDate</Field></OptionalFields>"));
+ }
+
+ @Test
+ @Order(5)
+ void listWithoutAnIdReturnsEveryConfiguration() {
+ given()
+ .when()
+ .get("/" + BUCKET + "?inventory")
+ .then()
+ .statusCode(200)
+ .body(containsString("<ListInventoryConfigurationsResult"))
+ .body(containsString("<Id>report1</Id>"))
+ .body(containsString("<Id>report2</Id>"))
+ .body(containsString("<IsTruncated>false</IsTruncated>"));
+ }
+
+ @Test
+ @Order(6)
+ void idInTheBodyMustMatchTheIdInTheQuery() {
+ given()
+ .body(configuration("Different", ""))
+ .when()
+ .put("/" + BUCKET + "?inventory&id=Mismatch")
+ .then()
+ .statusCode(400)
+ .body(containsString("MalformedXML"));
+ }
+
+ @Test
+ @Order(7)
+ void unknownIdIsNotFound() {
+ given()
+ .when()
+ .get("/" + BUCKET + "?inventory&id=absent")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchConfiguration"));
+
+ // AWS does not treat deleting an absent configuration as a no-op.
+ given()
+ .when()
+ .delete("/" + BUCKET + "?inventory&id=absent")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchConfiguration"));
+ }
+
+ /**
+ * {@code DELETE /{bucket}?inventory} must not fall through to the unqualified DeleteBucket
+ * and remove the whole bucket.
+ */
+ @Test
+ @Order(8)
+ void deleteInventoryConfigurationDoesNotDeleteBucket() {
+ given()
+ .when()
+ .delete("/" + BUCKET + "?inventory&id=report1")
+ .then()
+ .statusCode(204);
+
+ given()
+ .when()
+ .get("/" + BUCKET + "?inventory&id=report2")
+ .then()
+ .statusCode(200);
+
+ given()
+ .when()
+ .get("/" + BUCKET + "?inventory&id=report1")
+ .then()
+ .statusCode(404);
+ }
+
+ @Test
+ @Order(9)
+ void aRequestWithoutAnIdIsRefusedRatherThanGuessedAt() {
+ given()
+ .body(configuration("report1", ""))
+ .when()
+ .put("/" + BUCKET + "?inventory")
+ .then()
+ .statusCode(400)
+ .body(containsString("InvalidArgument"));
+
+ given()
+ .when()
+ .delete("/" + BUCKET + "?inventory")
+ .then()
+ .statusCode(400)
+ .body(containsString("InvalidArgument"));
+ }
+
+ @Test
+ @Order(10)
+ void unqualifiedDeleteStillRemovesBucket() {
+ given()
+ .when()
+ .delete("/" + BUCKET)
+ .then()
+ .statusCode(204);
+ given()
+ .when()
+ .get("/" + BUCKET + "?inventory")
+ .then()
+ .statusCode(404)
+ .body(containsString("NoSuchBucket"));
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3InventoryConfigurationTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3InventoryConfigurationTest.java
new file mode 100644
index 0000000000..b3e0426b16
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3InventoryConfigurationTest.java
@@ -0,0 +1,140 @@
+package io.github.hectorvent.floci.services.s3;
+
+import io.github.hectorvent.floci.core.common.AwsException;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+class S3InventoryConfigurationTest {
+
+ private static final String NS = "http://s3.amazonaws.com/doc/2006-03-01/";
+
+ private static final String DESTINATION = "<Destination><S3BucketDestination>"
+ + "<Format>CSV</Format>"
+ + "<AccountId>123456789012</AccountId>"
+ + "<Bucket>arn:aws:s3:::destination-bucket</Bucket>"
+ + "<Prefix>inventory/</Prefix>"
+ + "</S3BucketDestination></Destination>";
+
+ private static final String MINIMAL_DESTINATION = "<Destination><S3BucketDestination>"
+ + "<Format>CSV</Format>"
+ + "<Bucket>arn:aws:s3:::destination-bucket</Bucket>"
+ + "</S3BucketDestination></Destination>";
+
+ private static String body(String inner) {
+ return "<InventoryConfiguration xmlns=\"" + NS + "\">" + inner + "</InventoryConfiguration>";
+ }
+
+ private static String required(String destination) {
+ return "<Id>report1</Id><IsEnabled>true</IsEnabled>" + destination
+ + "<Schedule><Frequency>Daily</Frequency></Schedule>"
+ + "<IncludedObjectVersions>All</IncludedObjectVersions>";
+ }
+
+ @Test
+ void parsesTheRequiredElementsInAwsOrderWhateverOrderTheyArrivedIn() {
+ String shuffled = "<IncludedObjectVersions>All</IncludedObjectVersions>"
+ + "<Schedule><Frequency>Daily</Frequency></Schedule>"
+ + "<IsEnabled>true</IsEnabled>"
+ + MINIMAL_DESTINATION
+ + "<Id>report1</Id>";
+
+ S3InventoryConfiguration parsed = S3InventoryConfiguration.parse(body(shuffled));
+
+ assertEquals("report1", parsed.id());
+ assertEquals(required(MINIMAL_DESTINATION), parsed.innerXml());
+ }
+
+ @Test
+ void keepsTheFilterOptionalFieldsAndEncryption() {
+ String encrypted = DESTINATION.replace("</S3BucketDestination>",
+ "<Encryption><SSE-KMS><KeyId>arn:aws:kms:us-east-1:123456789012:key/k</KeyId></SSE-KMS></Encryption>"
+ + "</S3BucketDestination>");
+ String parsed = S3InventoryConfiguration.parse(body(
+ "<Id>report1</Id><IsEnabled>false</IsEnabled>"
+ + "<Filter><Prefix>docs/</Prefix></Filter>"
+ + encrypted
+ + "<IncludedObjectVersions>Current</IncludedObjectVersions>"
+ + "<Schedule><Frequency>Weekly</Frequency></Schedule>"
+ + "<OptionalFields><Field>Size</Field><Field>ETag</Field></OptionalFields>")).innerXml();
+
+ assertEquals("<Id>report1</Id><IsEnabled>false</IsEnabled>" + encrypted
+ + "<Schedule><Frequency>Weekly</Frequency></Schedule>"
+ + "<Filter><Prefix>docs/</Prefix></Filter>"
+ + "<IncludedObjectVersions>Current</IncludedObjectVersions>"
+ + "<OptionalFields><Field>Size</Field><Field>ETag</Field></OptionalFields>", parsed);
+ }
+
+ @Test
+ void serializesSseS3AsAnEmptyElement() {
+ String parsed = S3InventoryConfiguration.parse(body(required(
+ MINIMAL_DESTINATION.replace("</S3BucketDestination>",
+ "<Encryption><SSE-S3/></Encryption></S3BucketDestination>")))).innerXml();
+
+ assertEquals(required(MINIMAL_DESTINATION.replace("</S3BucketDestination>",
+ "<Encryption><SSE-S3/></Encryption></S3BucketDestination>")), parsed);
+ }
+
+ @Test
+ void escapesValuesOnTheWayBackOut() {
+ String parsed = S3InventoryConfiguration.parse(body(required(MINIMAL_DESTINATION)
+ .replace("<Id>report1</Id>", "<Id>a&amp;b</Id>")
+ + "<Filter><Prefix>x&lt;y</Prefix></Filter>")).innerXml();
+
+ assertEquals(required(MINIMAL_DESTINATION).replace("<Id>report1</Id>", "<Id>a&amp;b</Id>")
+ .replace("<IncludedObjectVersions>", "<Filter><Prefix>x&lt;y</Prefix></Filter><IncludedObjectVersions>"),
+ parsed);
+ }
+
+ @Test
+ void rejectsBodiesThatDoNotMatchTheSchema() {
+ // A missing required element, a stray element, wrong root, empty and non-XML bodies are
+ // all MalformedXML on AWS.
+ String all = required(MINIMAL_DESTINATION);
+ for (String invalid : new String[]{
+ body(""),
+ body(all.replace("<Id>report1</Id>", "<Id> </Id>")),
+ body(all.replace("<Id>report1</Id>", "")),
+ body(all.replace("<IsEnabled>true</IsEnabled>", "")),
+ body(all.replace("<IsEnabled>true</IsEnabled>", "<IsEnabled>yes</IsEnabled>")),
+ body(all.replace("<IncludedObjectVersions>All</IncludedObjectVersions>", "")),
+ body(all.replace("<IncludedObjectVersions>All</IncludedObjectVersions>",
+ "<IncludedObjectVersions>Latest</IncludedObjectVersions>")),
+ body(all.replace("<Schedule><Frequency>Daily</Frequency></Schedule>", "")),
+ body(all.replace("Daily", "Hourly")),
+ body(all.replace(MINIMAL_DESTINATION, "")),
+ body(all + "<Unknown/>"),
+ body(all + "<Filter><Tag><Key>k</Key><Value>v</Value></Tag></Filter>"),
+ body(all + "<OptionalFields><Field>Colour</Field></OptionalFields>"),
+ "<SomethingElse><Id>a</Id></SomethingElse>",
+ "not xml at all",
+ ""}) {
+ AwsException e = assertThrows(AwsException.class, () -> S3InventoryConfiguration.parse(invalid),
+ () -> "expected rejection of: " + invalid);
+ assertEquals("MalformedXML", e.getErrorCode());
+ assertEquals(400, e.getHttpStatus());
+ }
+ }
+
+ @Test
+ void rejectsDestinationsOutsideTheSchema() {
+ String unknownFormat = DESTINATION.replace("CSV", "JSON");
+ String missingFormat = DESTINATION.replace("<Format>CSV</Format>", "");
+ String missingBucket = DESTINATION.replace("<Bucket>arn:aws:s3:::destination-bucket</Bucket>", "");
+ String strayElement = DESTINATION.replace("<Prefix>inventory/</Prefix>",
+ "<Prefix>inventory/</Prefix><Region>eu</Region>");
+ String kmsWithoutKey = DESTINATION.replace("</S3BucketDestination>",
+ "<Encryption><SSE-KMS/></Encryption></S3BucketDestination>");
+ String twoEncryptions = DESTINATION.replace("</S3BucketDestination>",
+ "<Encryption><SSE-S3/><SSE-KMS><KeyId>k</KeyId></SSE-KMS></Encryption></S3BucketDestination>");
+
+ for (String invalid : new String[]{
+ unknownFormat, missingFormat, missingBucket, strayElement, kmsWithoutKey, twoEncryptions}) {
+ AwsException e = assertThrows(AwsException.class,
+ () -> S3InventoryConfiguration.parse(body(required(invalid))),
+ () -> "expected rejection of: " + invalid);
+ assertEquals("MalformedXML", e.getErrorCode());
+ }
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java
index 993c1e7a69..e9115492ed 100644
--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3ServiceTest.java
@@ -837,6 +837,59 @@ class S3ServiceTest {
}
}
+ @Test
+ void analyticsAndInventoryConfigurationsOnABucketWithoutAnyBehaveAsEmpty() {
+ // A bucket persisted before these fields existed deserializes with null maps, which is
+ // the same shape a freshly created bucket has, so neither may fault.
+ s3Service.createBucket("no-configs", "us-east-1");
+
+ assertTrue(s3Service.listBucketAnalyticsConfigurations("no-configs")
+ .contains("<IsTruncated>false</IsTruncated>"));
+ assertTrue(s3Service.listBucketInventoryConfigurations("no-configs")
+ .contains("<IsTruncated>false</IsTruncated>"));
+ assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
+ () -> s3Service.getBucketAnalyticsConfiguration("no-configs", "any")).getErrorCode());
+ assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
+ () -> s3Service.deleteBucketInventoryConfiguration("no-configs", "any")).getErrorCode());
+
+ // And the first put still lands on it, in its own map.
+ s3Service.putBucketAnalyticsConfiguration("no-configs", "first", "<Id>first</Id>");
+ s3Service.putBucketInventoryConfiguration("no-configs", "first", "<Id>first</Id>");
+ assertTrue(s3Service.getBucketAnalyticsConfiguration("no-configs", "first")
+ .contains("<AnalyticsConfiguration"));
+ assertTrue(s3Service.getBucketInventoryConfiguration("no-configs", "first")
+ .contains("<InventoryConfiguration"));
+ assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
+ () -> s3Service.getBucketMetricsConfiguration("no-configs", "first")).getErrorCode());
+ }
+
+ @Test
+ void analyticsAndInventoryConfigurationsDoNotOutliveTheirBucket() {
+ s3Service.createBucket("recycled-configs", "us-east-1");
+ s3Service.putBucketAnalyticsConfiguration("recycled-configs", "old", "<Id>old</Id>");
+ s3Service.putBucketInventoryConfiguration("recycled-configs", "old", "<Id>old</Id>");
+ s3Service.deleteBucket("recycled-configs");
+
+ s3Service.createBucket("recycled-configs", "us-east-1");
+
+ assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
+ () -> s3Service.getBucketAnalyticsConfiguration("recycled-configs", "old")).getErrorCode());
+ assertEquals("NoSuchConfiguration", assertThrows(AwsException.class,
+ () -> s3Service.getBucketInventoryConfiguration("recycled-configs", "old")).getErrorCode());
+ }
+
+ @Test
+ void analyticsAndInventoryConfigurationsSurviveAJacksonRoundTrip() throws Exception {
+ var mapper = new com.fasterxml.jackson.databind.ObjectMapper().findAndRegisterModules();
+ Bucket bucket = new Bucket("persisted-configs");
+ bucket.setAnalyticsConfigurations(new java.util.LinkedHashMap<>(Map.of("a", "<Id>a</Id>")));
+ bucket.setInventoryConfigurations(new java.util.LinkedHashMap<>(Map.of("i", "<Id>i</Id>")));
+
+ Bucket reloaded = mapper.readValue(mapper.writeValueAsString(bucket), Bucket.class);
+ assertEquals("<Id>a</Id>", reloaded.getAnalyticsConfigurations().get("a"));
+ assertEquals("<Id>i</Id>", reloaded.getInventoryConfigurations().get("i"));
+ }
+
@Test
void metricsConfigurationsSurviveAJacksonRoundTrip() throws Exception {
// Bucket records are persisted as JSON, so the configurations have to come back after a