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. + * + *

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 OUTPUT_SCHEMA_VERSIONS = List.of("V_1"); + private static final List 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 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. + * + *

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 ENABLED = List.of("true", "false"); + private static final List INCLUDED_OBJECT_VERSIONS = List.of("All", "Current"); + private static final List FREQUENCIES = List.of("Daily", "Weekly"); + private static final List FORMATS = List.of("CSV", "ORC", "Parquet"); + private static final List 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 ""; + } + 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 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 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 configurations = bucket.getAnalyticsConfigurations(); + if (configurations == null || !configurations.containsKey(id)) { + throw noSuchAnalyticsConfiguration(); + } + Map 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 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 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 configurations = bucket.getInventoryConfigurations(); + if (configurations == null || !configurations.containsKey(id)) { + throw noSuchInventoryConfiguration(); + } + Map 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 metricsConfigurations; /** Intelligent-Tiering configurations, keyed by the id they were stored under. */ private Map intelligentTieringConfigurations; + /** Storage class analysis configurations, keyed by the id they were stored under. */ + private Map analyticsConfigurations; + /** Inventory configurations, keyed by the id they were stored under. */ + private Map inventoryConfigurations; public Bucket() { this.tags = new HashMap<>(); @@ -134,4 +138,14 @@ public class Bucket { public void setIntelligentTieringConfigurations(Map intelligentTieringConfigurations) { this.intelligentTieringConfigurations = intelligentTieringConfigurations; } + + public Map getAnalyticsConfigurations() { return analyticsConfigurations; } + public void setAnalyticsConfigurations(Map analyticsConfigurations) { + this.analyticsConfigurations = analyticsConfigurations; + } + + public Map getInventoryConfigurations() { return inventoryConfigurations; } + public void setInventoryConfigurations(Map 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 """ + + %s + %s + + + V_1 + + + CSV + 123456789012 + arn:aws:s3:::analytics-destination + exports/ + + + + + + """.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("EntireBucket")) + .body(containsString("V_1")) + .body(containsString("123456789012")) + .body(containsString("arn:aws:s3:::analytics-destination")); + } + + @Test + @Order(4) + void putFilteredConfigurationKeepsTheFilter() { + given() + .body(configuration("Filtered", """ + + + logs/ + envprod + teamcore + + + """)) + .when() + .put("/" + BUCKET + "?analytics&id=Filtered") + .then() + .statusCode(204); + + // AWS repeats inside with no wrapping element. + given() + .when() + .get("/" + BUCKET + "?analytics&id=Filtered") + .then() + .statusCode(200) + .body(containsString("logs/" + + "envprod" + + "teamcore")); + } + + @Test + @Order(5) + void listWithoutAnIdReturnsEveryConfiguration() { + given() + .when() + .get("/" + BUCKET + "?analytics") + .then() + .statusCode(200) + .body(containsString("EntireBucket")) + .body(containsString("Filtered")) + .body(containsString("false")); + } + + @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 = "" + + "V_1" + + "" + + "CSV" + + "123456789012" + + "arn:aws:s3:::destination-bucket" + + "reports/" + + "" + + ""; + + private static String body(String inner) { + return "" + inner + ""; + } + + @Test + void parsesAnIdWithAnEmptyAnalysisAndNoFilter() { + S3AnalyticsConfiguration parsed = S3AnalyticsConfiguration.parse( + body("whole")); + + assertEquals("whole", parsed.id()); + assertEquals("whole", parsed.innerXml()); + } + + @Test + void serializesTheExportInAwsOrderWhateverOrderItArrivedIn() { + String shuffled = "" + + "" + + "reports/" + + "arn:aws:s3:::destination-bucket" + + "123456789012" + + "CSV" + + "" + + "V_1" + + ""; + + assertEquals("a" + EXPORT, + S3AnalyticsConfiguration.parse(body("a" + shuffled)).innerXml()); + } + + @Test + void parsesEachSingleFilterPredicate() { + assertEquals("alogs/", + S3AnalyticsConfiguration.parse(body( + "alogs/")).innerXml()); + + assertEquals("aenvprod" + + "", + S3AnalyticsConfiguration.parse(body( + "aenvprod" + + "")).innerXml()); + } + + @Test + void parsesAnAndConjunctionKeepingEveryTag() { + String parsed = S3AnalyticsConfiguration.parse(body(""" + a + + + logs/ + envprod + teamcore + + + + """)).innerXml(); + + assertEquals("alogs/" + + "envprod" + + "teamcore" + + "", parsed); + } + + @Test + void escapesValuesOnTheWayBackOut() { + String parsed = S3AnalyticsConfiguration.parse( + body("a&bx<y")).innerXml(); + + assertEquals("a&bx<y" + + "", 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(" "), + body(""), + body("a"), + body("a"), + body("a"), + body("ap"), + body("ak"), + "a", + "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("arn:aws:s3:::destination-bucket", ""); + String missingVersion = EXPORT.replace("V_1", ""); + String strayElement = EXPORT.replace("CSV", "CSVeu"); + + for (String invalid : new String[]{ + unknownVersion, unknownFormat, missingBucket, missingVersion, strayElement}) { + AwsException e = assertThrows(AwsException.class, + () -> S3AnalyticsConfiguration.parse(body("a" + 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 """ + + %s + true + + + CSV + 123456789012 + arn:aws:s3:::inventory-destination + inventory/ + + + + Daily + + All + %s + + """.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("report1")) + .body(containsString("true")) + .body(containsString("Daily")) + .body(containsString("All")) + .body(containsString("arn:aws:s3:::inventory-destination")); + } + + @Test + @Order(4) + void putConfigurationWithFilterAndOptionalFieldsKeepsThem() { + given() + .body(configuration("report2", """ + docs/ + + Size + LastModifiedDate + + """)) + .when() + .put("/" + BUCKET + "?inventory&id=report2") + .then() + .statusCode(204); + + given() + .when() + .get("/" + BUCKET + "?inventory&id=report2") + .then() + .statusCode(200) + .body(containsString("docs/")) + .body(containsString("SizeLastModifiedDate")); + } + + @Test + @Order(5) + void listWithoutAnIdReturnsEveryConfiguration() { + given() + .when() + .get("/" + BUCKET + "?inventory") + .then() + .statusCode(200) + .body(containsString("report1")) + .body(containsString("report2")) + .body(containsString("false")); + } + + @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 = "" + + "CSV" + + "123456789012" + + "arn:aws:s3:::destination-bucket" + + "inventory/" + + ""; + + private static final String MINIMAL_DESTINATION = "" + + "CSV" + + "arn:aws:s3:::destination-bucket" + + ""; + + private static String body(String inner) { + return "" + inner + ""; + } + + private static String required(String destination) { + return "report1true" + destination + + "Daily" + + "All"; + } + + @Test + void parsesTheRequiredElementsInAwsOrderWhateverOrderTheyArrivedIn() { + String shuffled = "All" + + "Daily" + + "true" + + MINIMAL_DESTINATION + + "report1"; + + S3InventoryConfiguration parsed = S3InventoryConfiguration.parse(body(shuffled)); + + assertEquals("report1", parsed.id()); + assertEquals(required(MINIMAL_DESTINATION), parsed.innerXml()); + } + + @Test + void keepsTheFilterOptionalFieldsAndEncryption() { + String encrypted = DESTINATION.replace("", + "arn:aws:kms:us-east-1:123456789012:key/k" + + ""); + String parsed = S3InventoryConfiguration.parse(body( + "report1false" + + "docs/" + + encrypted + + "Current" + + "Weekly" + + "SizeETag")).innerXml(); + + assertEquals("report1false" + encrypted + + "Weekly" + + "docs/" + + "Current" + + "SizeETag", parsed); + } + + @Test + void serializesSseS3AsAnEmptyElement() { + String parsed = S3InventoryConfiguration.parse(body(required( + MINIMAL_DESTINATION.replace("", + "")))).innerXml(); + + assertEquals(required(MINIMAL_DESTINATION.replace("", + "")), parsed); + } + + @Test + void escapesValuesOnTheWayBackOut() { + String parsed = S3InventoryConfiguration.parse(body(required(MINIMAL_DESTINATION) + .replace("report1", "a&b") + + "x<y")).innerXml(); + + assertEquals(required(MINIMAL_DESTINATION).replace("report1", "a&b") + .replace("", "x<y"), + 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("report1", " ")), + body(all.replace("report1", "")), + body(all.replace("true", "")), + body(all.replace("true", "yes")), + body(all.replace("All", "")), + body(all.replace("All", + "Latest")), + body(all.replace("Daily", "")), + body(all.replace("Daily", "Hourly")), + body(all.replace(MINIMAL_DESTINATION, "")), + body(all + ""), + body(all + "kv"), + body(all + "Colour"), + "a", + "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("CSV", ""); + String missingBucket = DESTINATION.replace("arn:aws:s3:::destination-bucket", ""); + String strayElement = DESTINATION.replace("inventory/", + "inventory/eu"); + String kmsWithoutKey = DESTINATION.replace("", + ""); + String twoEncryptions = DESTINATION.replace("", + "k"); + + 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("false")); + assertTrue(s3Service.listBucketInventoryConfigurations("no-configs") + .contains("false")); + 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", "first"); + s3Service.putBucketInventoryConfiguration("no-configs", "first", "first"); + assertTrue(s3Service.getBucketAnalyticsConfiguration("no-configs", "first") + .contains(" s3Service.getBucketMetricsConfiguration("no-configs", "first")).getErrorCode()); + } + + @Test + void analyticsAndInventoryConfigurationsDoNotOutliveTheirBucket() { + s3Service.createBucket("recycled-configs", "us-east-1"); + s3Service.putBucketAnalyticsConfiguration("recycled-configs", "old", "old"); + s3Service.putBucketInventoryConfiguration("recycled-configs", "old", "old"); + 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", "a"))); + bucket.setInventoryConfigurations(new java.util.LinkedHashMap<>(Map.of("i", "i"))); + + Bucket reloaded = mapper.readValue(mapper.writeValueAsString(bucket), Bucket.class); + assertEquals("a", reloaded.getAnalyticsConfigurations().get("a")); + assertEquals("i", reloaded.getInventoryConfigurations().get("i")); + } + @Test void metricsConfigurationsSurviveAJacksonRoundTrip() throws Exception { // Bucket records are persisted as JSON, so the configurations have to come back after a