Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): apply an S3 bucket's NotificationConfiguration (#5493)
Jay669548277fbc
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationS3BucketNotificationTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationS3BucketNotificationTest.javanew file mode 100644index 0000000000..9c80d9772b--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationS3BucketNotificationTest.java@@ -0,0 +1,153 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+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 software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;+import software.amazon.awssdk.services.cloudformation.model.Stack;+import software.amazon.awssdk.services.s3.S3Client;+import software.amazon.awssdk.services.s3.model.FilterRule;+import software.amazon.awssdk.services.s3.model.GetBucketNotificationConfigurationResponse;+import software.amazon.awssdk.services.s3.model.QueueConfiguration;++import java.util.List;++import static org.assertj.core.api.Assertions.assertThat;++/**+ * Wires a bucket to a queue through an {@code AWS::S3::Bucket} {@code NotificationConfiguration}+ * with the CloudFormation SDK and reads the result back with the S3 SDK, which is how a template's+ * notifications are checked against AWS. Removing the property in an update clears the bucket's+ * configuration, as it does on AWS.+ */+@DisplayName("CloudFormation AWS::S3::Bucket NotificationConfiguration")+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class CloudFormationS3BucketNotificationTest {++ private static CloudFormationClient cloudFormation;+ private static S3Client s3;+ private static String stackName;+ private static String bucketName;++ @BeforeAll+ static void setup() {+ cloudFormation = TestFixtures.cloudFormationClient();+ s3 = TestFixtures.s3Client();+ stackName = TestFixtures.uniqueName("compat-cfn-s3-notify");+ bucketName = TestFixtures.uniqueName("compat-cfn-s3-notify").toLowerCase();+ }++ @AfterAll+ static void cleanup() {+ if (cloudFormation != null) {+ try {+ cloudFormation.deleteStack(r -> r.stackName(stackName));+ awaitStatus("DELETE_COMPLETE");+ } catch (Exception e) {+ System.err.println("CloudFormation S3 notification cleanup skipped: " + e.getMessage());+ }+ cloudFormation.close();+ }+ if (s3 != null) {+ s3.close();+ }+ }++ private static String template(String notificationConfiguration) {+ return """+ {+ "Resources": {+ "Queue": { "Type": "AWS::SQS::Queue" },+ "QueuePolicy": {+ "Type": "AWS::SQS::QueuePolicy",+ "Properties": {+ "Queues": [ { "Ref": "Queue" } ],+ "PolicyDocument": { "Version": "2012-10-17", "Statement": [ {+ "Effect": "Allow", "Principal": { "Service": "s3.amazonaws.com" },+ "Action": "sqs:SendMessage", "Resource": { "Fn::GetAtt": ["Queue", "Arn"] } } ] }+ }+ },+ "Bucket": {+ "Type": "AWS::S3::Bucket",+ "DependsOn": "QueuePolicy",+ "Properties": { "BucketName": "%s" %s }+ }+ }+ }+ """.formatted(bucketName, notificationConfiguration);+ }++ @Test+ @Order(1)+ void theBucketCarriesTheTemplatesQueueConfiguration() throws InterruptedException {+ cloudFormation.createStack(r -> r.stackName(stackName).templateBody(template("""+ , "NotificationConfiguration": { "QueueConfigurations": [ {+ "Event": "s3:ObjectCreated:*",+ "Queue": { "Fn::GetAtt": ["Queue", "Arn"] },+ "Filter": { "S3Key": { "Rules": [ { "Name": "prefix", "Value": "uploads/" } ] } } } ] }+ """)));+ awaitStatus("CREATE_COMPLETE");++ GetBucketNotificationConfigurationResponse config =+ s3.getBucketNotificationConfiguration(r -> r.bucket(bucketName));++ assertThat(config.queueConfigurations()).hasSize(1);+ QueueConfiguration queue = config.queueConfigurations().get(0);+ assertThat(queue.queueArn()).startsWith("arn:").contains(":sqs:");+ assertThat(queue.eventsAsStrings()).containsExactly("s3:ObjectCreated:*");+ List<FilterRule> rules = queue.filter().key().filterRules();+ assertThat(rules).hasSize(1);+ // AWS returns the rule name as "Prefix"; compare it the way S3 matches it.+ assertThat(rules.get(0).nameAsString()).isEqualToIgnoringCase("prefix");+ assertThat(rules.get(0).value()).isEqualTo("uploads/");+ assertThat(config.lambdaFunctionConfigurations()).isEmpty();+ assertThat(config.topicConfigurations()).isEmpty();+ }++ @Test+ @Order(2)+ void removingThePropertyInAnUpdateClearsTheBucketsConfiguration() throws InterruptedException {+ assertThat(s3.getBucketNotificationConfiguration(r -> r.bucket(bucketName)).queueConfigurations())+ .as("the configuration the update removes").hasSize(1);++ cloudFormation.updateStack(r -> r.stackName(stackName).templateBody(template("")));+ awaitStatus("UPDATE_COMPLETE");++ GetBucketNotificationConfigurationResponse config =+ s3.getBucketNotificationConfiguration(r -> r.bucket(bucketName));++ assertThat(config.queueConfigurations()).isEmpty();+ assertThat(config.topicConfigurations()).isEmpty();+ assertThat(config.lambdaFunctionConfigurations()).isEmpty();+ }++ private static void awaitStatus(String status) throws InterruptedException {+ String current = "";+ long deadline = System.currentTimeMillis() + 60_000;+ while (System.currentTimeMillis() < deadline) {+ try {+ Stack stack = cloudFormation.describeStacks(r -> r.stackName(stackName)).stacks().get(0);+ current = stack.stackStatusAsString();+ } catch (CloudFormationException e) {+ if ("DELETE_COMPLETE".equals(status) && e.getMessage() != null+ && e.getMessage().contains("does not exist")) {+ return;+ }+ throw e;+ }+ if (status.equals(current)) {+ return;+ }+ if (current.endsWith("_FAILED") || current.endsWith("ROLLBACK_COMPLETE")) {+ break;+ }+ Thread.sleep(250);+ }+ throw new AssertionError("Stack " + stackName + " did not reach " + status + "; last status " + current);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.javaindex 36565a81ed..fb4931e515 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;import com.fasterxml.jackson.core.type.TypeReference;import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;import io.github.hectorvent.floci.config.EmulatorConfig;import io.github.hectorvent.floci.core.common.AwsArnUtils;import io.github.hectorvent.floci.core.common.AwsException;@@ -1436,6 +1437,9 @@ public class CloudFormationService implements ResourceProvider {Set<String> changedResourceIds = isCreate? Set.of(): changedResourceIds(stack, templateBody, params, region);+ JsonNode previousResources = isCreate+ ? objectMapper.missingNode()+ : previousResources(stack, previousState, region, accountId);JsonNode template = parseTemplate(templateBody);stack.setOriginalTemplateBody(templateBody);@@ -1545,11 +1549,16 @@ public class CloudFormationService implements ResourceProvider {props.isMissingNode() ? null : props,engine, region, accountId, isCreate, previousResource);} else {+ JsonNode previousDefinition = previousResources.path(logicalId);+ JsonNode priorProps = type.equals(previousDefinition.path("Type").asText())+ && previousDefinition.path("Properties").isObject()+ ? previousDefinition.path("Properties") : null;resource = dispatcher.provision(logicalId, type, props.isMissingNode() ? null : props,engine, region, accountId, stack.getStackName(),resource.getPhysicalId(), resource.getAttributes(),event -> addEvent(stack, logicalId, event.getPhysicalResourceId(), type,- event.getResourceStatus(), event.getResourceStatusReason()));+ event.getResourceStatus(), event.getResourceStatusReason()),+ priorProps);}resource.setUpdateReplacePolicy(resDef.path("UpdateReplacePolicy").asText(null));@@ -2170,6 +2179,71 @@ public class CloudFormationService implements ResourceProvider {return existing;}+ /**+ * The resources of the processed template an update replaces, so a provisioner can tell a+ * property the update removes from one the stack never declared. All of them, since an update+ * can provision a resource whose own definition did not change. Evaluated under the previous+ * deployment's conditions: a top-level property whose {@code Fn::If} chose {@code AWS::NoValue}+ * was never applied and is left out. Missing when there is no previous template, and when it no+ * longer parses: the update then proceeds as if nothing had been declared.+ */+ private JsonNode previousResources(Stack stack, StackUpdateSnapshot previousState, String region,+ String accountId) {+ if (previousState.templateBody() == null) {+ return objectMapper.missingNode();+ }+ try {+ JsonNode previousTemplate = parseTemplate(previousState.templateBody());+ // As the change-set preview does: raw parameters for a stack persisted before+ // resolvedParameters existed.+ Map<String, String> previousParams = previousState.resolvedParameters().isEmpty()+ ? previousState.parameters() : previousState.resolvedParameters();+ Map<String, Boolean> conditions = resolveConditions(previousTemplate, previousParams, stack, region,+ accountId);+ ObjectNode resources = objectMapper.createObjectNode();+ for (Map.Entry<String, JsonNode> entry : previousTemplate.path("Resources").properties()) {+ JsonNode definition = entry.getValue();+ ObjectNode applied = resources.putObject(entry.getKey());+ applied.set("Type", definition.path("Type"));+ if (definition.path("Properties").isObject()) {+ applied.set("Properties", appliedProperties(definition.path("Properties"), conditions));+ }+ }+ return resources;+ } catch (Exception e) {+ LOG.warnv("Previous template of stack {0} could not be evaluated ({1}); its updated resources see no prior properties",+ stack.getStackName(), e.getMessage());+ return objectMapper.missingNode();+ }+ }++ /**+ * The top-level properties left after each one's {@code Fn::If} is decided, without those that+ * chose {@code AWS::NoValue}. Decided as the template engine decides it: a condition the+ * template does not define is false.+ */+ private ObjectNode appliedProperties(JsonNode properties, Map<String, Boolean> conditions) {+ ObjectNode applied = objectMapper.createObjectNode();+ for (Map.Entry<String, JsonNode> property : properties.properties()) {+ JsonNode value = decideIf(property.getValue(), conditions);+ boolean noValue = value.isObject() && value.size() == 1 && "AWS::NoValue".equals(value.path("Ref").asText());+ if (!noValue) {+ applied.set(property.getKey(), property.getValue());+ }+ }+ return applied;+ }++ /** The branch an {@code Fn::If} chose, following nested ones; any other value as it is. */+ private static JsonNode decideIf(JsonNode value, Map<String, Boolean> conditions) {+ while (value.isObject() && value.size() == 1 && value.path("Fn::If").isArray()+ && value.path("Fn::If").size() >= 3) {+ JsonNode branches = value.path("Fn::If");+ value = conditions.getOrDefault(branches.get(0).asText(), false) ? branches.get(1) : branches.get(2);+ }+ return value;+ }+private StackUpdateSnapshot snapshotForUpdate(Stack stack) {return new StackUpdateSnapshot(stack.getTemplateBody(),diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.javaindex 9cd316fc77..e00e14783e 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcher.java@@ -72,13 +72,18 @@ public class CfnResourceDispatcher {String stackName, String existingPhysicalId,Map<String, String> existingAttributes) {return provision(logicalId, resourceType, properties, engine, region, accountId, stackName,- existingPhysicalId, existingAttributes, event -> {});+ existingPhysicalId, existingAttributes, event -> {}, null);}+ /**+ * {@code priorProperties} are the resource's properties in the previous template, unresolved,+ * or null when there is none; see {@link ProvisionContext#previouslyDeclared(String)}.+ */public StackResource provision(String logicalId, String resourceType, JsonNode properties,CloudFormationTemplateEngine engine, String region, String accountId,String stackName, String existingPhysicalId,- Map<String, String> existingAttributes, Consumer<StackEvent> progress) {+ Map<String, String> existingAttributes, Consumer<StackEvent> progress,+ JsonNode priorProperties) {StackResource resource = new StackResource();resource.setLogicalId(logicalId);resource.setResourceType(resourceType);@@ -89,7 +94,8 @@ public class CfnResourceDispatcher {CfnResourceProvisioner owner = registry.forType(resourceType).orElse(null);if (owner != null) {owner.provision(resource, properties,- new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress));+ new ProvisionContext(engine, region, accountId, stackName, existingPhysicalId, progress,+ priorProperties));// A provisioner that migrated a stub without writing its own Arn would leave the// stub's, and the real resource would read as a stub on its next update.String arn = resource.getAttributes().get("Arn");diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.javaindex 4ae55d9678..31784aa80e 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContext.java@@ -19,11 +19,11 @@ import java.util.function.Consumer;*/public record ProvisionContext(CloudFormationTemplateEngine engine, String region,String accountId, String stackName, String priorPhysicalId,- Consumer<StackEvent> progress) {+ Consumer<StackEvent> progress, JsonNode priorProperties) {public ProvisionContext(CloudFormationTemplateEngine engine, String region,String accountId, String stackName, String priorPhysicalId) {- this(engine, region, accountId, stackName, priorPhysicalId, event -> {});+ this(engine, region, accountId, stackName, priorPhysicalId, event -> {}, null);}/** Intermediate resource events retain the stack pipeline's event IDs and metadata. */@@ -58,6 +58,20 @@ public record ProvisionContext(CloudFormationTemplateEngine engine, String regioreturn priorPhysicalId != null && !priorPhysicalId.isBlank();}+ /**+ * Whether the previous template declared {@code name} on this resource, which tells an update+ * that removes a property apart from one the stack never declared.+ *+ * <p>Reads the previous template's properties after its conditions chose each top-level+ * {@code Fn::If}, so one that chose {@code AWS::NoValue} was not declared. False for a resource+ * that was never provisioned, which has no prior physical id: a create, a resource the previous+ * template did not have, and one whose {@code Condition} kept it out.+ */+ public boolean previouslyDeclared(String name) {+ return isUpdate() && priorProperties != null && priorProperties.has(name)+ && !priorProperties.get(name).isNull();+ }+/*** Resolves a CloudFormation tag property to a map, preserving template order. Both registry* shapes are read: the {@code [{Key, Value}]} list most types declare, and thediff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.javaindex b4a8866908..b79b12afc0 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisioner.java@@ -10,9 +10,15 @@ import io.github.hectorvent.floci.core.common.AwsRegions;import io.github.hectorvent.floci.core.common.XmlBuilder;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.s3.S3Service;+import io.github.hectorvent.floci.services.s3.model.FilterRule;+import io.github.hectorvent.floci.services.s3.model.LambdaNotification;+import io.github.hectorvent.floci.services.s3.model.NotificationConfiguration;+import io.github.hectorvent.floci.services.s3.model.QueueNotification;+import io.github.hectorvent.floci.services.s3.model.TopicNotification;import jakarta.enterprise.context.ApplicationScoped;import org.jboss.logging.Logger;+import java.util.ArrayList;import java.util.List;import java.util.Set;@@ -21,14 +27,17 @@ import java.util.Set;** <p>A property this class covers is translated into the XML its own S3 API call takes and handed* to the same service method, so the service validates and stores it exactly as it would a direct- * {@code PutBucket*} request. A property the template does not declare is left alone.+ * {@code PutBucket*} request. A property the template does not declare is left alone, except that+ * an update removing {@code NotificationConfiguration} clears it.** <p>Covered on {@code AWS::S3::Bucket}: {@code BucketName}, {@code CorsConfiguration},* {@code VersioningConfiguration}, {@code PublicAccessBlockConfiguration},- * {@code BucketEncryption}, {@code LifecycleConfiguration} and {@code Tags}.+ * {@code BucketEncryption}, {@code LifecycleConfiguration}, {@code NotificationConfiguration} and+ * {@code Tags}. {@code NotificationConfiguration} is the exception to the XML translation: its+ * service method takes the parsed model, so the provisioner builds that model instead.** <p><b>Silently dropped</b>, each of which has a service method waiting for it:- * {@code NotificationConfiguration}, {@code WebsiteConfiguration}, {@code LoggingConfiguration},+ * {@code WebsiteConfiguration}, {@code LoggingConfiguration},* {@code ObjectLockConfiguration}, {@code OwnershipControls}, {@code ReplicationConfiguration},* {@code AccelerateConfiguration}, {@code AccessControl}, and the four numbered configuration* lists ({@code AnalyticsConfigurations}, {@code IntelligentTieringConfigurations},@@ -77,15 +86,37 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {// AWS. With the name now stable across updates, the second UpdateStack must skip the create// and only reconcile the bucket's configuration. A replacing update derives a different// name and still creates, hence reusesPriorEntity rather than isUpdate.- if (!ctx.reusesPriorEntity(bucketName)) {- s3Service.createBucket(bucketName, ctx.region());- }- applyBucketCorsConfiguration(bucketName, props, ctx);- applyBucketVersioningConfiguration(bucketName, props, ctx);- applyPublicAccessBlockConfiguration(bucketName, props, ctx);- applyBucketEncryption(bucketName, props, ctx);- applyLifecycleConfiguration(bucketName, props, ctx);- applyBucketTags(bucketName, props, ctx);+ Unwind unwind = new Unwind();+ try {+ // Built before anything is created, so a configuration that fails validation creates nothing.+ NotificationConfiguration notifications = notificationConfiguration(props, ctx);+ if (!ctx.reusesPriorEntity(bucketName)) {+ // In us-east-1 CreateBucket also answers for a bucket the account already owns,+ // which this resource must never delete.+ boolean owned = s3Service.ownsBucket(bucketName);+ s3Service.createBucket(bucketName, ctx.region());+ unwind.created = !owned;+ }+ // Ahead of the other properties, so a destination S3 cannot validate fails the resource+ // before any of them has changed the bucket. An unchanged configuration is not put again:+ // each put sends a fresh s3:TestEvent to every queue and topic.+ if (notifications != null) {+ NotificationConfiguration current = s3Service.getBucketNotificationConfiguration(bucketName);+ if (!sameConfiguration(notifications, current)) {+ s3Service.putBucketNotificationConfiguration(bucketName, notifications);+ unwind.replacedNotifications = current;+ }+ }+ applyBucketCorsConfiguration(bucketName, props, ctx);+ applyBucketVersioningConfiguration(bucketName, props, ctx);+ applyPublicAccessBlockConfiguration(bucketName, props, ctx);+ applyBucketEncryption(bucketName, props, ctx);+ applyLifecycleConfiguration(bucketName, props, ctx);+ applyBucketTags(bucketName, props, ctx);+ } catch (RuntimeException failure) {+ unwind(r, bucketName, unwind, ctx, failure);+ throw failure;+ }r.setPhysicalId(bucketName);r.getAttributes().put("Arn",AwsArnUtils.Arn.global(AwsRegions.partitionFor(ctx.region()), "s3", "", bucketName).toString());@@ -204,6 +235,188 @@ public class S3CfnProvisioner implements CfnResourceProvisioner {s3Service.putBucketTagging(bucketName, ctx.resolveTags(props, "Tags"));}+ /** What a provision changed that a failure has to undo. */+ private static final class Unwind {+ private boolean created;+ private NotificationConfiguration replacedNotifications;+ }++ /**+ * Undoes what a failed provision changed. On a failed update the engine restores the previous+ * resource record and reports it rolled back unless the provisioner records why it could not+ * be, so the bucket itself has to be put back: one this attempt created is deleted, and a+ * notification configuration it replaced is put back. The other properties have no restore;+ * the notification configuration goes ahead of them, so a destination S3 rejects leaves them+ * untouched.+ */+ private void unwind(StackResource r, String bucketName, Unwind unwind, ProvisionContext ctx,+ RuntimeException failure) {+ try {+ if (unwind.created) {+ s3Service.deleteBucket(bucketName);+ } else if (unwind.replacedNotifications != null) {+ // Valid when it was put; its destinations are not checked again on the way back.+ s3Service.putBucketNotificationConfiguration(bucketName, unwind.replacedNotifications, true);+ }+ } catch (RuntimeException e) {+ LOG.warnv("Could not undo the failed provision of bucket {0}: {1}", bucketName, e.getMessage());+ failure.addSuppressed(e);+ if (ctx.isUpdate()) {+ r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR,+ "Could not restore bucket " + bucketName + ": " + e.getMessage());+ }+ }+ }++ private static boolean sameConfiguration(NotificationConfiguration desired, NotificationConfiguration current) {+ return desired.getQueueConfigurations().equals(current.getQueueConfigurations())+ && desired.getTopicConfigurations().equals(current.getTopicConfigurations())+ && desired.getLambdaFunctionConfigurations().equals(current.getLambdaFunctionConfigurations())+ && desired.isEventBridgeEnabled() == current.isEventBridgeEnabled();+ }++ /**+ * The configuration to put on the bucket through the same service method as+ * {@code PutBucketNotificationConfiguration}, whose destination validation then fails the+ * resource for a queue, topic or function that does not exist. Empty when the template declares+ * an empty one, and when an update removes the property, both of which clear the bucket's, as+ * on AWS. Null when the stack never declared it: the bucket's own configuration, one put+ * outside the stack, is left alone, as AWS leaves it.+ *+ * <p>CloudFormation names one {@code Event} per entry where the API takes a list, and has no+ * {@code Id}. Each entry becomes one API configuration with a blank id, which is what the+ * service stores for an API request that omits {@code Id}.+ */+ private NotificationConfiguration notificationConfiguration(JsonNode props, ProvisionContext ctx) {+ JsonNode declaredNode = declared(props, "NotificationConfiguration");+ JsonNode notifications = declaredNode == null+ ? null : ctx.engine().resolveNodeOmittingNoValue(declaredNode);+ if (notifications == null || notifications.isMissingNode() || notifications.isNull()) {+ return ctx.previouslyDeclared("NotificationConfiguration") ? new NotificationConfiguration() : null;+ }+ String path = "#/NotificationConfiguration";+ requireObject(notifications, path);+ NotificationConfiguration config = new NotificationConfiguration();+ for (NotificationEntry entry : notificationEntries(notifications, "QueueConfigurations", "Queue", path)) {+ config.getQueueConfigurations().add(+ new QueueNotification("", entry.arn(), List.of(entry.event()), entry.filterRules()));+ }+ for (NotificationEntry entry : notificationEntries(notifications, "TopicConfigurations", "Topic", path)) {+ config.getTopicConfigurations().add(+ new TopicNotification("", entry.arn(), List.of(entry.event()), entry.filterRules()));+ }+ for (NotificationEntry entry : notificationEntries(notifications, "LambdaConfigurations", "Function", path)) {+ config.getLambdaFunctionConfigurations().add(+ new LambdaNotification("", entry.arn(), List.of(entry.event()), entry.filterRules()));+ }+ JsonNode eventBridge = declared(notifications, "EventBridgeConfiguration");+ if (eventBridge != null) {+ String eventBridgePath = path + "/EventBridgeConfiguration";+ JsonNode enabledNode = requiredNode(eventBridge, "EventBridgeEnabled", eventBridgePath);+ String enabled = enabledNode.asText();+ if (!"true".equalsIgnoreCase(enabled) && !"false".equalsIgnoreCase(enabled)) {+ throw typeMismatch(eventBridgePath + "/EventBridgeEnabled", "Boolean", enabledNode);+ }+ config.setEventBridgeEnabled(Boolean.parseBoolean(enabled));+ }+ return config;+ }++ private record NotificationEntry(String event, String arn, List<FilterRule> filterRules) {}++ private static List<NotificationEntry> notificationEntries(JsonNode notifications, String listName,+ String arnProperty, String path) {+ JsonNode list = declaredArray(notifications, listName, path);+ List<NotificationEntry> entries = new ArrayList<>();+ if (list == null) {+ return entries;+ }+ for (int index = 0; index < list.size(); index++) {+ String entryPath = path + "/" + listName + "/" + index;+ JsonNode entry = requireObject(list.get(index), entryPath);+ String event = required(entry, "Event", entryPath);+ String arn = required(entry, arnProperty, entryPath);+ entries.add(new NotificationEntry(event, arn, filterRules(entry, entryPath)));+ }+ return entries;+ }++ private static List<FilterRule> filterRules(JsonNode entry, String entryPath) {+ JsonNode filter = declared(entry, "Filter");+ if (filter == null) {+ return List.of();+ }+ requireObject(filter, entryPath + "/Filter");+ JsonNode s3Key = requireObject(requiredNode(filter, "S3Key", entryPath + "/Filter"), entryPath + "/Filter/S3Key");+ requiredNode(s3Key, "Rules", entryPath + "/Filter/S3Key");+ JsonNode rules = declaredArray(s3Key, "Rules", entryPath + "/Filter/S3Key");+ List<FilterRule> filterRules = new ArrayList<>();+ for (int index = 0; index < rules.size(); index++) {+ String rulePath = entryPath + "/Filter/S3Key/Rules/" + index;+ JsonNode rule = requireObject(rules.get(index), rulePath);+ filterRules.add(new FilterRule(required(rule, "Name", rulePath), required(rule, "Value", rulePath)));+ }+ return filterRules;+ }++ /**+ * A string the registry schema marks required. Reads a configuration already resolved, so the+ * value is not resolved a second time.+ */+ private static String required(JsonNode props, String name, String path) {+ JsonNode value = requiredNode(props, name, path);+ if (value.isContainerNode()) {+ throw typeMismatch(path + "/" + name, "String", value);+ }+ return value.asText();+ }++ /** A key the registry schema marks required, with its JSON pointer in the message. */+ private static JsonNode requiredNode(JsonNode props, String name, String path) {+ JsonNode value = declared(props, name);+ if (value == null) {+ throw new AwsException("InvalidRequest",+ "Model validation failed (" + path + ": required key [" + name + "] not found)", 400);+ }+ return value;+ }++ /**+ * The named list, or null when it is not declared. Anything other than a list fails, as the+ * schema's array type does, rather than being read as an empty one: an empty rule list matches+ * every key.+ */+ private static JsonNode declaredArray(JsonNode props, String name, String path) {+ JsonNode value = declared(props, name);+ if (value != null && !value.isArray()) {+ throw typeMismatch(path + "/" + name, "JSONArray", value);+ }+ return value;+ }++ /** The value itself when it is an object. Anything else fails, rather than reading as an empty one. */+ private static JsonNode requireObject(JsonNode value, String pointer) {+ if (!value.isObject()) {+ throw typeMismatch(pointer, "JSONObject", value);+ }+ return value;+ }++ private static AwsException typeMismatch(String pointer, String expected, JsonNode value) {+ return new AwsException("InvalidRequest", "Model validation failed (" + pointer+ + ": expected type: " + expected + ", found: " + schemaTypeName(value) + ")", 400);+ }++ private static String schemaTypeName(JsonNode value) {+ return switch (value.getNodeType()) {+ case OBJECT -> "JSONObject";+ case ARRAY -> "JSONArray";+ case BOOLEAN -> "Boolean";+ case NUMBER -> value.isIntegralNumber() ? "Integer" : "Double";+ default -> "String";+ };+ }+/** CloudFormation's lifecycle rule property names, spelled as the S3 API's XML. */private String lifecycleXml(JsonNode rules, ProvisionContext ctx) {XmlBuilder xml = new XmlBuilder().start("LifecycleConfiguration", AwsNamespaces.S3);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.javaindex 0e5407121f..7dfe9dccfa 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@@ -5909,6 +5909,14 @@ public class S3Service implements Resettable, ResourceProvider {return resolveBucket(bucketName).isPresent();}+ /**+ * Whether the calling account has the bucket, which is the lookup {@link #createBucket} makes.+ * Unlike {@link #bucketExists}, it never spans other accounts' buckets.+ */+ public boolean ownsBucket(String bucketName) {+ return bucketStore.get(bucketName).isPresent();+ }+/*** Resolves a bucket for existence/access. With {@code globalBucketNamespace} enabled, the* lookup spans every account's partition (AWS bucket names are globally unique and reachablediff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.javaindex d248cb48e2..2717b77459 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnStackWaits.java@@ -73,6 +73,50 @@ final class CfnStackWaits {return last;}+ /**+ * Waits until DescribeStacks reports {@code expectedStatus} and returns that state. Unlike+ * {@link #awaitTerminal}, a rollback is waited out: a stack rolling back shows CREATE_FAILED or+ * UPDATE_FAILED for a moment before ROLLBACK_IN_PROGRESS, so while a rollback status is expected+ * only a failed rollback is final. Any other terminal status fails at once with its reason, as+ * do a DescribeStacks that is not 200 and ten seconds without the expected status.+ */+ static StackState awaitStatus(String stackName, String expectedStatus) {+ long deadline = System.currentTimeMillis() + 10_000;+ boolean rollbackExpected = expectedStatus.contains("ROLLBACK");+ StackState last = new StackState(null, "");+ while (System.currentTimeMillis() < deadline) {+ Response response = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/");+ if (response.statusCode() != 200) {+ fail("DescribeStacks " + stackName + " answered " + response.statusCode() + ": " + response.asString());+ }+ XmlPath xml = response.xmlPath();+ String status = xml.getString("**.find { it.name() == 'StackStatus' }");+ String reason = xml.getString("**.find { it.name() == 'StackStatusReason' }");+ last = new StackState(status == null || status.isEmpty() ? null : status, reason == null ? "" : reason);+ if (expectedStatus.equals(last.status())) {+ return last;+ }+ boolean onTheWayToRollback = rollbackExpected+ && ("CREATE_FAILED".equals(last.status()) || "UPDATE_FAILED".equals(last.status()));+ if (last.status() != null && TERMINAL.contains(last.status()) && !onTheWayToRollback) {+ fail("Stack " + stackName + " reached " + last.status() + " instead of " + expectedStatus+ + ": " + last.reason());+ }+ try {+ Thread.sleep(50);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new AssertionError("Interrupted while waiting for stack " + stackName, e);+ }+ }+ fail("Stack " + stackName + " did not reach " + expectedStatus + " within ten seconds, last: " + last);+ return last;+ }+/*** Waits until DescribeStacks answers 400, which is how a missing stack is reported. Fails on* DELETE_FAILED or after ten seconds.diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationS3BucketNotificationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationS3BucketNotificationIntegrationTest.javanew file mode 100644index 0000000000..4fb3bec85c--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationS3BucketNotificationIntegrationTest.java@@ -0,0 +1,465 @@+package io.github.hectorvent.floci.services.cloudformation;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.sqs.SqsService;+import io.github.hectorvent.floci.services.sqs.model.Message;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.http.ContentType;+import io.restassured.response.ValidatableResponse;+import jakarta.inject.Inject;+import org.junit.jupiter.api.Test;++import java.util.ArrayList;+import java.util.List;++import static io.restassured.RestAssured.config;+import static io.restassured.RestAssured.given;+import static io.restassured.config.EncoderConfig.encoderConfig;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.not;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertTrue;++/**+ * An {@code AWS::S3::Bucket}'s {@code NotificationConfiguration} reaches the bucket and delivers.+ *+ * <p>Before this, {@code S3CfnProvisioner} dropped the property, so a stack wiring a bucket to a+ * queue or a function reported {@code CREATE_COMPLETE} and no event was ever sent. Delivery is+ * asserted through SQS, which needs no container; the Lambda and SNS entries are asserted as stored+ * configuration.+ *+ * <p>The template has the shape a real SAM stack uses to avoid a circular dependency: the bucket+ * depends on the function through its notification, so the function's role and the permission's+ * {@code SourceArn} name the bucket by string instead of referring back to it.+ */+@QuarkusTest+class CloudFormationS3BucketNotificationIntegrationTest {++ private static final String REGION = "us-east-1";++ @Inject+ SqsService sqsService;++ @Inject+ ObjectMapper objectMapper;++ private static String template(String name, String notificationConfiguration) {+ return """+ {+ "Resources": {+ "Queue": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "%1$s" } },+ "Topic": { "Type": "AWS::SNS::Topic", "Properties": { "TopicName": "%1$s" } },+ "Role": {+ "Type": "AWS::IAM::Role",+ "Properties": {+ "AssumeRolePolicyDocument": { "Version": "2012-10-17", "Statement": [+ { "Effect": "Allow", "Principal": { "Service": "lambda.amazonaws.com" }, "Action": "sts:AssumeRole" } ] },+ "Policies": [ { "PolicyName": "read-images", "PolicyDocument": { "Version": "2012-10-17", "Statement": [+ { "Effect": "Allow", "Action": "s3:GetObject",+ "Resource": { "Fn::Sub": "arn:${AWS::Partition}:s3:::%1$s/*" } } ] } } ]+ }+ },+ "Fn": {+ "Type": "AWS::Lambda::Function",+ "Properties": {+ "FunctionName": "%1$s",+ "Runtime": "python3.12",+ "Handler": "index.handler",+ "Role": { "Fn::GetAtt": ["Role", "Arn"] },+ "Code": { "ZipFile": "def handler(e, c): return 'ok'" }+ }+ },+ "FnPermission": {+ "Type": "AWS::Lambda::Permission",+ "Properties": {+ "FunctionName": { "Fn::GetAtt": ["Fn", "Arn"] },+ "Action": "lambda:InvokeFunction",+ "Principal": "s3.amazonaws.com",+ "SourceAccount": { "Ref": "AWS::AccountId" },+ "SourceArn": { "Fn::Sub": "arn:${AWS::Partition}:s3:::%1$s" }+ }+ },+ "Bucket": {+ "Type": "AWS::S3::Bucket",+ "DependsOn": ["FnPermission"],+ "Properties": { "BucketName": "%1$s" %2$s }+ }+ }+ }+ """.formatted(name, notificationConfiguration);+ }++ /** A queue for new objects under {@code uploads/}, a topic for restores, and the function for removals. */+ private static final String QUEUE_AND_FUNCTION = """+ , "NotificationConfiguration": {+ "QueueConfigurations": [ {+ "Event": "s3:ObjectCreated:*",+ "Queue": { "Fn::GetAtt": ["Queue", "Arn"] },+ "Filter": { "S3Key": { "Rules": [ { "Name": "prefix", "Value": "uploads/" } ] } }+ } ],+ "TopicConfigurations": [ {+ "Event": "s3:ObjectRestore:Completed",+ "Topic": { "Ref": "Topic" }+ } ],+ "LambdaConfigurations": [ {+ "Event": "s3:ObjectRemoved:*",+ "Function": { "Fn::GetAtt": ["Fn", "Arn"] }+ } ]+ }+ """;++ @Test+ void theBucketCarriesItsNotificationConfigurationAndDeliversThroughIt() throws Exception {+ String name = "cfn-notify-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, QUEUE_AND_FUNCTION));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");++ bucketGet(name, "notification")+ .body(containsString("<Queue>arn:aws:sqs:us-east-1:000000000000:" + name + "</Queue>"))+ .body(containsString("<Event>s3:ObjectCreated:*</Event>"))+ .body(containsString("<Name>prefix</Name>"))+ .body(containsString("<Value>uploads/</Value>"))+ .body(containsString("<CloudFunction>arn:aws:lambda:us-east-1:000000000000:function:" + name+ + "</CloudFunction>"))+ .body(containsString("<Event>s3:ObjectRemoved:*</Event>"))+ .body(containsString("<Topic>arn:aws:sns:us-east-1:000000000000:" + name + "</Topic>"))+ .body(containsString("<Event>s3:ObjectRestore:Completed</Event>"));++ putObject(name, "elsewhere/skipped.txt");+ putObject(name, "uploads/delivered.txt");++ // S3 sends its test event when the configuration is put, then one record per matching object.+ List<String> keys = new ArrayList<>();+ int testEvents = 0;+ for (Message message : drain(name)) {+ JsonNode body = objectMapper.readTree(message.getBody());+ if (body.has("Records")) {+ JsonNode record = body.path("Records").get(0);+ assertEquals("ObjectCreated:Put", record.path("eventName").asText());+ keys.add(record.path("s3").path("object").path("key").asText());+ } else {+ assertEquals("s3:TestEvent", body.path("Event").asText());+ testEvents++;+ }+ }+ assertEquals(1, testEvents, "S3 validates the queue with one test event");+ assertEquals(List.of("uploads/delivered.txt"), keys, "the prefix filter selects the delivered objects");+ }++ /**+ * An {@code Fn::If} resolving to {@code AWS::NoValue} omits what it wraps: the false entry is+ * dropped from the list, and a false configuration is not declared at all, so it neither applies+ * nor clears anything.+ */+ @Test+ void conditionalEntriesAndConfigurationsFollowTheirConditions() throws Exception {+ String name = "cfn-notify-if-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, """+ {+ "Parameters": { "WithBucketNotifications": { "Type": "String", "Default": "true" } },+ "Conditions": {+ "Never": { "Fn::Equals": ["a", "b"] },+ "Notify": { "Fn::Equals": [{ "Ref": "WithBucketNotifications" }, "true"] }+ },+ "Resources": {+ "Queue": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "%1$s" } },+ "Bucket": {+ "Type": "AWS::S3::Bucket",+ "Properties": {+ "BucketName": "%1$s",+ "NotificationConfiguration": { "Fn::If": ["Notify", {+ "QueueConfigurations": [+ { "Event": "s3:ObjectCreated:*", "Queue": { "Fn::GetAtt": ["Queue", "Arn"] } },+ { "Fn::If": ["Never",+ { "Event": "s3:ObjectRemoved:*", "Queue": { "Fn::GetAtt": ["Queue", "Arn"] } },+ { "Ref": "AWS::NoValue" }] }+ ] }, { "Ref": "AWS::NoValue" }] }+ }+ }+ }+ }+ """.formatted(name));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");++ bucketGet(name, "notification")+ .body(containsString("<Event>s3:ObjectCreated:*</Event>"))+ .body(not(containsString("s3:ObjectRemoved")));+ }++ /**+ * A queue that does not exist fails the bucket as S3's destination validation does for+ * {@code PutBucketNotificationConfiguration}, rather than reporting a bucket that never delivers.+ */+ @Test+ void aDestinationThatDoesNotExistFailsTheStack() throws Exception {+ String name = "cfn-notify-missing-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, """+ , "NotificationConfiguration": { "QueueConfigurations": [ {+ "Event": "s3:ObjectCreated:*",+ "Queue": "arn:aws:sqs:us-east-1:000000000000:%s-absent" } ] }+ """.formatted(name)));+ CfnStackWaits.awaitStatus(stackId, "ROLLBACK_COMPLETE");+ given().when().head("/" + name).then().statusCode(404);++ String events = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackEvents")+ .formParam("StackName", stackId)+ .when().post("/").then().statusCode(200).extract().asString();+ assertTrue(events.contains("Unable to validate the following destination configurations"), events);+ }++ /**+ * An update whose destination S3 rejects fails before anything changed the bucket, rolls back+ * cleanly, and leaves the configuration the stack had.+ */+ @Test+ void anUpdateWithARejectedDestinationRollsBackToTheConfigurationItHad() throws Exception {+ String name = "cfn-notify-reject-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, QUEUE_AND_FUNCTION));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");++ stack("UpdateStack", name, template(name, """+ , "VersioningConfiguration": { "Status": "Enabled" },+ "NotificationConfiguration": { "QueueConfigurations": [ {+ "Event": "s3:ObjectCreated:*",+ "Queue": "arn:aws:sqs:us-east-1:000000000000:%s-absent" } ] }+ """.formatted(name)));+ CfnStackWaits.awaitStatus(stackId, "UPDATE_ROLLBACK_COMPLETE");++ bucketGet(name, "notification")+ .body(containsString("<Queue>arn:aws:sqs:us-east-1:000000000000:" + name + "</Queue>"))+ .body(not(containsString("-absent")));+ bucketGet(name, "versioning").body(not(containsString("<Status>Enabled</Status>")));+ }++ /**+ * A property that fails after the new configuration was put has the configuration it replaced+ * put back, so the stack's UPDATE_ROLLBACK_COMPLETE describes the bucket truthfully.+ */+ @Test+ void anUpdateFailingAfterTheNotificationPutRestoresTheConfigurationItReplaced() throws Exception {+ String name = "cfn-notify-later-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, QUEUE_AND_FUNCTION));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");++ stack("UpdateStack", name, template(name, """+ , "VersioningConfiguration": { "Status": "Bogus" },+ "NotificationConfiguration": { "QueueConfigurations": [ {+ "Event": "s3:ObjectRemoved:*", "Queue": { "Fn::GetAtt": ["Queue", "Arn"] } } ] }+ """));+ CfnStackWaits.awaitStatus(stackId, "UPDATE_ROLLBACK_COMPLETE");++ bucketGet(name, "notification")+ .body(containsString("<Event>s3:ObjectCreated:*</Event>"))+ .body(containsString("<Value>uploads/</Value>"))+ .body(containsString("<CloudFunction>"))+ .body(containsString("<TopicConfiguration>"));+ }++ @Test+ void aCreateFailingAfterTheBucketExistsDeletesTheBucket() throws Exception {+ String name = "cfn-notify-later-create-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, QUEUE_AND_FUNCTION+ + ", \"VersioningConfiguration\": { \"Status\": \"Bogus\" }"));+ CfnStackWaits.awaitStatus(stackId, "ROLLBACK_COMPLETE");++ given().when().head("/" + name).then().statusCode(404);+ }++ /**+ * A configuration whose {@code Fn::If} chose {@code AWS::NoValue} was never applied, so the+ * stack never declared one: a configuration put outside the stack survives a later update.+ */+ @Test+ void aConfigurationThatWasConditionallyOmittedIsNotClearedByALaterUpdate() throws Exception {+ String name = "cfn-notify-omitted-" + Long.toString(System.nanoTime(), 36);+ String template = """+ {+ "Parameters": { "Notify": { "Type": "String", "Default": "false" },+ "Owner": { "Type": "String", "Default": "%2$s" } },+ "Conditions": { "WithNotifications": { "Fn::Equals": [{ "Ref": "Notify" }, "true"] } },+ "Resources": {+ "Queue": { "Type": "AWS::SQS::Queue", "Properties": { "QueueName": "%1$s" } },+ "Bucket": {+ "Type": "AWS::S3::Bucket",+ "Properties": {+ "BucketName": "%1$s",+ "Tags": [ { "Key": "owner", "Value": { "Ref": "Owner" } } ],+ "NotificationConfiguration": { "Fn::If": ["WithNotifications",+ { "QueueConfigurations": [ { "Event": "s3:ObjectCreated:*",+ "Queue": { "Fn::GetAtt": ["Queue", "Arn"] } } ] },+ { "Ref": "AWS::NoValue" }] }+ }+ }+ }+ }+ """;+ String stackId = stack("CreateStack", name, template.formatted(name, "first"));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");+ String queueArn = "arn:aws:sqs:us-east-1:000000000000:" + name;+ given().contentType("application/xml").body("""+ <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <QueueConfiguration><Queue>%s</Queue><Event>s3:ObjectRemoved:*</Event></QueueConfiguration>+ </NotificationConfiguration>+ """.formatted(queueArn))+ .when().put("/" + name + "?notification").then().statusCode(200);++ stack("UpdateStack", name, template.formatted(name, "second"));+ CfnStackWaits.awaitStatus(stackId, "UPDATE_COMPLETE");++ bucketGet(name, "tagging").body(containsString("<Value>second</Value>"));+ bucketGet(name, "notification").body(containsString("<Event>s3:ObjectRemoved:*</Event>"));+ }++ /** An update that leaves the configuration as it was does not put it again, so no new test event. */+ @Test+ void anUpdateThatKeepsTheConfigurationSendsNoNewTestEvent() throws Exception {+ String name = "cfn-notify-same-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, QUEUE_AND_FUNCTION));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");+ drain(name);++ stack("UpdateStack", name, template(name, QUEUE_AND_FUNCTION+ + ", \"Tags\": [ { \"Key\": \"touched\", \"Value\": \"yes\" } ]"));+ CfnStackWaits.awaitStatus(stackId, "UPDATE_COMPLETE");++ bucketGet(name, "tagging").body(containsString("<Key>touched</Key>"));+ assertEquals(List.of(), drain(name));+ }++ /**+ * Cloud Control reads a resource without an id as a failed create. A rejected destination+ * must reach it that way, with the bucket the attempt made deleted.+ */+ @Test+ void cloudControlReportsARejectedDestinationAsAFailedCreate() throws Exception {+ String name = "cc-notify-reject-" + Long.toString(System.nanoTime(), 36);+ String desiredState = """+ {"BucketName": "%1$s", "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:%1$s-absent"}]}}+ """.formatted(name);+ String ct = "application/x-amz-json-1.0";+ String token = given()+ .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, ContentType.TEXT)))+ .contentType(ct)+ .header("X-Amz-Target", "CloudApiService.CreateResource")+ .body(objectMapper.writeValueAsString(objectMapper.createObjectNode()+ .put("TypeName", "AWS::S3::Bucket").put("DesiredState", desiredState)))+ .when().post("/").then().statusCode(200)+ .extract().jsonPath().getString("ProgressEvent.RequestToken");++ String status = "";+ long deadline = System.currentTimeMillis() + 10_000;+ while (System.currentTimeMillis() < deadline) {+ status = given()+ .config(config().encoderConfig(encoderConfig().encodeContentTypeAs(ct, ContentType.TEXT)))+ .contentType(ct)+ .header("X-Amz-Target", "CloudApiService.GetResourceRequestStatus")+ .body("{\"RequestToken\":\"" + token + "\"}")+ .when().post("/").then().statusCode(200)+ .extract().jsonPath().getString("ProgressEvent.OperationStatus");+ if ("SUCCESS".equals(status) || "FAILED".equals(status)) {+ break;+ }+ Thread.sleep(50);+ }+ assertEquals("FAILED", status);+ given().when().head("/" + name).then().statusCode(404);+ }++ /** A declared but empty configuration is applied, which takes the stack's entries off the bucket. */+ @Test+ void anUpdateToAnEmptyConfigurationClearsTheBucket() throws Exception {+ String name = "cfn-notify-clear-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, QUEUE_AND_FUNCTION));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");+ bucketGet(name, "notification").body(containsString("<QueueConfiguration>"));++ stack("UpdateStack", name, template(name, ", \"NotificationConfiguration\": {}"));+ CfnStackWaits.awaitStatus(stackId, "UPDATE_COMPLETE");++ bucketGet(name, "notification")+ .body(not(containsString("<QueueConfiguration>")))+ .body(not(containsString("<CloudFunctionConfiguration>")));+ }++ /** As on AWS, an update that removes the property takes the configuration off the bucket. */+ @Test+ void anUpdateThatRemovesTheConfigurationClearsTheBucket() throws Exception {+ String name = "cfn-notify-remove-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, QUEUE_AND_FUNCTION));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");+ bucketGet(name, "notification").body(containsString("<QueueConfiguration>"));++ stack("UpdateStack", name, template(name, ""));+ CfnStackWaits.awaitStatus(stackId, "UPDATE_COMPLETE");++ bucketGet(name, "notification")+ .body(not(containsString("<QueueConfiguration>")))+ .body(not(containsString("<TopicConfiguration>")))+ .body(not(containsString("<CloudFunctionConfiguration>")));+ }++ /**+ * A configuration the stack never declared is left alone, so one put on the bucket outside the+ * stack survives an update, as it does on AWS. This passes with or without the property being+ * applied; it guards against treating an undeclared property as a removed one.+ */+ @Test+ void anUpdateThatDoesNotDeclareTheConfigurationLeavesTheBucketsOwn() throws Exception {+ String name = "cfn-notify-keep-" + Long.toString(System.nanoTime(), 36);+ String stackId = stack("CreateStack", name, template(name, ""));+ CfnStackWaits.awaitStatus(stackId, "CREATE_COMPLETE");++ String queueArn = "arn:aws:sqs:us-east-1:000000000000:" + name;+ given().contentType("application/xml").body("""+ <NotificationConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">+ <QueueConfiguration><Queue>%s</Queue><Event>s3:ObjectCreated:*</Event></QueueConfiguration>+ </NotificationConfiguration>+ """.formatted(queueArn))+ .when().put("/" + name + "?notification").then().statusCode(200);++ stack("UpdateStack", name, template(name, ", \"Tags\": [ { \"Key\": \"touched\", \"Value\": \"yes\" } ]"));+ CfnStackWaits.awaitStatus(stackId, "UPDATE_COMPLETE");++ bucketGet(name, "tagging").body(containsString("<Key>touched</Key>"));+ bucketGet(name, "notification").body(containsString("<Queue>" + queueArn + "</Queue>"));+ }++ private List<Message> drain(String queueName) {+ String queueUrl = sqsService.getQueueUrl(queueName, REGION);+ List<Message> all = new ArrayList<>();+ List<Message> batch;+ do {+ batch = sqsService.receiveMessage(queueUrl, 10, 30, 0, REGION);+ all.addAll(batch);+ } while (!batch.isEmpty());+ return all;+ }++ private static void putObject(String bucket, String key) {+ given().contentType("text/plain").body("payload")+ .when().put("/" + bucket + "/" + key).then().statusCode(200);+ }++ private static ValidatableResponse bucketGet(String bucket, String subresource) {+ return given().when().get("/" + bucket + "?" + subresource).then().statusCode(200);+ }++ private static String stack(String action, String stackName, String template) {+ String xml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", action)+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ int start = xml.indexOf("<StackId>") + "<StackId>".length();+ return xml.substring(start, xml.indexOf("</StackId>", start));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.javaindex b7876eeb00..59bdd1cc25 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/CfnResourceDispatcherTest.java@@ -74,6 +74,18 @@ class CfnResourceDispatcherTest {assertEquals("CREATE_COMPLETE", resource.getStatus());}+ @Test+ void provisionHandsThePriorPropertiesToTheContext() {+ AtomicReference<ProvisionContext> seenContext = new AtomicReference<>();+ when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) -> seenContext.set(ctx))));+ JsonNode prior = mapper.createObjectNode().put("Removed", "value");++ dispatcher.provision("Thing", TYPE, mapper.createObjectNode(), null, "us-east-1", "000000000000",+ "my-stack", "thing-prior", Map.of(), event -> { }, prior);++ assertEquals(prior, seenContext.get().priorProperties());+ }+@Testvoid aProvisionerThatMigratesAStubWithoutWritingAnArnDropsTheStubArn() {when(registry.forType(TYPE)).thenReturn(Optional.of(provisioner((resource, ctx) ->diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.javaindex 12a344e79d..aaf8935c3f 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/ProvisionContextTest.java@@ -50,6 +50,38 @@ class ProvisionContextTest {}}+ private ProvisionContext contextWithPriorProperties(String priorProperties) {+ return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", "prior-id",+ event -> { }, priorProperties == null ? null : props(priorProperties));+ }++ @Test+ void previouslyDeclaredReadsThePreviousTemplatesProperties() {+ ProvisionContext ctx = contextWithPriorProperties("""+ {"Declared": {"Fn::GetAtt": ["Other", "Arn"]}, "ExplicitNull": null}+ """);++ assertTrue(ctx.previouslyDeclared("Declared"), "declared, whatever it resolved to");+ assertFalse(ctx.previouslyDeclared("ExplicitNull"), "null is how a template omits a property");+ assertFalse(ctx.previouslyDeclared("Absent"));+ }++ /** A resource the previous deployment never provisioned, such as one its Condition kept out, declared nothing. */+ @Test+ void aResourceWithoutAPriorPhysicalIdDeclaredNothing() {+ ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", null,+ event -> { }, props("{\"Declared\": \"value\"}"));++ assertFalse(ctx.previouslyDeclared("Declared"));+ }++ @Test+ void nothingIsPreviouslyDeclaredWithoutAPreviousTemplate() {+ assertFalse(contextWithPriorProperties(null).previouslyDeclared("Declared"));+ assertFalse(context("prior-id").previouslyDeclared("Declared"),+ "the constructors without prior properties have none");+ }+@Testvoid isUpdateReflectsWhetherAPriorPhysicalIdExists() {assertFalse(context(null).isUpdate(), "a first-time create has no prior physical id");diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.javaindex 0c6a0e44fc..a6bdf02c8d 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/S3CfnProvisionerTest.java@@ -6,10 +6,18 @@ import io.github.hectorvent.floci.core.common.AwsException;import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;import io.github.hectorvent.floci.services.cloudformation.model.StackResource;import io.github.hectorvent.floci.services.s3.S3Service;+import io.github.hectorvent.floci.services.s3.model.FilterRule;+import io.github.hectorvent.floci.services.s3.model.LambdaNotification;+import io.github.hectorvent.floci.services.s3.model.NotificationConfiguration;+import io.github.hectorvent.floci.services.s3.model.QueueNotification;+import io.github.hectorvent.floci.services.s3.model.TopicNotification;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.CsvSource;import org.mockito.ArgumentCaptor;+import java.util.List;import java.util.Map;import static org.junit.jupiter.api.Assertions.assertEquals;@@ -18,6 +26,7 @@ import static org.junit.jupiter.api.Assertions.assertThrows;import static org.junit.jupiter.api.Assertions.assertTrue;import static org.mockito.ArgumentMatchers.any;import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;import static org.mockito.Mockito.doThrow;import static org.mockito.Mockito.mock;import static org.mockito.Mockito.never;@@ -45,6 +54,9 @@ class S3CfnProvisionerTest {return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();});when(engine.resolveNode(any())).thenAnswer(i -> i.getArgument(0));+ when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> i.getArgument(0));+ // A bucket carrying a configuration no test declares, so every declared one is a change.+ when(s3.getBucketNotificationConfiguration(anyString())).thenReturn(queueNotification("existing"));ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack");}@@ -232,6 +244,385 @@ class S3CfnProvisionerTest {verify(s3, never()).putBucketVersioning("c", null);}+ private NotificationConfiguration provisionedNotifications(String json) {+ ArgumentCaptor<NotificationConfiguration> config = ArgumentCaptor.forClass(NotificationConfiguration.class);+ provisionBucket(json);+ verify(s3).putBucketNotificationConfiguration(eq("b"), config.capture());+ return config.getValue();+ }++ /**+ * CloudFormation names one Event per entry and the API takes a list, so each entry is one API+ * configuration. Two entries for the same function stay two configurations.+ */+ @Test+ void notificationEntriesBecomeOneApiConfigurationEachWithTheirFilters() {+ NotificationConfiguration config = provisionedNotifications("""+ {+ "BucketName": "b",+ "NotificationConfiguration": {+ "QueueConfigurations": [+ {"Event": "s3:ObjectRemoved:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:q"}+ ],+ "TopicConfigurations": [+ {"Event": "s3:ObjectRestore:Completed", "Topic": "arn:aws:sns:us-east-1:000000000000:t"}+ ],+ "LambdaConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Function": "arn:aws:lambda:us-east-1:000000000000:function:f",+ "Filter": {"S3Key": {"Rules": [{"Name": "prefix", "Value": "images/"},+ {"Name": "suffix", "Value": ".webp"}]}}},+ {"Event": "s3:ObjectTagging:Put", "Function": "arn:aws:lambda:us-east-1:000000000000:function:f"}+ ]+ }+ }+ """);++ assertEquals(List.of(new QueueNotification("", "arn:aws:sqs:us-east-1:000000000000:q",+ List.of("s3:ObjectRemoved:*"), List.of())), config.getQueueConfigurations());+ assertEquals(List.of(new TopicNotification("", "arn:aws:sns:us-east-1:000000000000:t",+ List.of("s3:ObjectRestore:Completed"), List.of())), config.getTopicConfigurations());+ assertEquals(List.of(+ new LambdaNotification("", "arn:aws:lambda:us-east-1:000000000000:function:f",+ List.of("s3:ObjectCreated:*"),+ List.of(new FilterRule("prefix", "images/"), new FilterRule("suffix", ".webp"))),+ new LambdaNotification("", "arn:aws:lambda:us-east-1:000000000000:function:f",+ List.of("s3:ObjectTagging:Put"), List.of())),+ config.getLambdaFunctionConfigurations());+ assertFalse(config.isEventBridgeEnabled());+ }++ @ParameterizedTest+ @CsvSource({"true,true", "false,false"})+ void eventBridgeConfigurationSetsDeliveryAsDeclared(String declared, boolean enabled) {+ NotificationConfiguration config = provisionedNotifications("""+ {"BucketName": "b",+ "NotificationConfiguration": {"EventBridgeConfiguration": {"EventBridgeEnabled": %s}}}+ """.formatted(declared));++ assertEquals(enabled, config.isEventBridgeEnabled());+ }++ /**+ * Omitted and explicitly empty differ. An undeclared configuration is left alone, as the other+ * properties here are, so a configuration put on the bucket outside the stack survives an+ * update. A declared empty one is applied, which clears the bucket's.+ */+ @Test+ void anUndeclaredNotificationConfigurationLeavesTheBucketAlone() {+ provisionBucket("""+ {"BucketName": "b"}+ """);++ verify(s3, never()).putBucketNotificationConfiguration(anyString(), any());+ }++ private void updateBucket(String priorProperties, String properties) {+ StackResource r = resource("Bucket", "AWS::S3::Bucket");+ r.setPhysicalId("b");+ provisioner.provision(r, props(properties), new ProvisionContext(ctx.engine(), REGION,+ "000000000000", "my-stack", "b", event -> { }, props(priorProperties)));+ }++ /** AWS clears the configuration when an update removes the property. */+ @Test+ void anUpdateThatRemovesTheNotificationConfigurationClearsIt() {+ ArgumentCaptor<NotificationConfiguration> config = ArgumentCaptor.forClass(NotificationConfiguration.class);++ updateBucket("""+ {"BucketName": "b", "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:q"}]}}+ """, """+ {"BucketName": "b"}+ """);++ verify(s3).putBucketNotificationConfiguration(eq("b"), config.capture());+ assertTrue(config.getValue().isEmpty());+ }++ /** An update of a bucket whose template never declared the property leaves its configuration alone. */+ @Test+ void anUpdateOfABucketThatNeverDeclaredTheNotificationConfigurationLeavesItAlone() {+ updateBucket("""+ {"BucketName": "b"}+ """, """+ {"BucketName": "b", "Tags": [{"Key": "k", "Value": "v"}]}+ """);++ verify(s3, never()).putBucketNotificationConfiguration(anyString(), any());+ }++ @Test+ void aDeclaredEmptyNotificationConfigurationClearsTheBucket() {+ NotificationConfiguration config = provisionedNotifications("""+ {"BucketName": "b", "NotificationConfiguration": {}}+ """);++ assertTrue(config.isEmpty());+ }++ /** The registry schema's required keys at each level, reported before S3 is called. */+ @ParameterizedTest+ @CsvSource(delimiter = '|', textBlock = """+ {"QueueConfigurations": [{"Queue": "arn:aws:sqs:us-east-1:000000000000:q"}]} | #/NotificationConfiguration/QueueConfigurations/0: required key [Event] not found+ {"QueueConfigurations": [{"Event": "s3:ObjectCreated:*"}]} | #/NotificationConfiguration/QueueConfigurations/0: required key [Queue] not found+ {"TopicConfigurations": [{"Event": "s3:ObjectCreated:*"}]} | #/NotificationConfiguration/TopicConfigurations/0: required key [Topic] not found+ {"LambdaConfigurations": [{"Event": "s3:ObjectCreated:*"}]} | #/NotificationConfiguration/LambdaConfigurations/0: required key [Function] not found+ {"LambdaConfigurations": [{"Event": "e", "Function": "f", "Filter": {}}]} | #/NotificationConfiguration/LambdaConfigurations/0/Filter: required key [S3Key] not found+ {"LambdaConfigurations": [{"Event": "e", "Function": "f", "Filter": {"S3Key": {}}}]} | #/NotificationConfiguration/LambdaConfigurations/0/Filter/S3Key: required key [Rules] not found+ {"LambdaConfigurations": [{"Event": "e", "Function": "f", "Filter": {"S3Key": {"Rules": [{"Value": "v"}]}}}]} | #/NotificationConfiguration/LambdaConfigurations/0/Filter/S3Key/Rules/0: required key [Name] not found+ {"LambdaConfigurations": [{"Event": "e", "Function": "f", "Filter": {"S3Key": {"Rules": [{"Name": "prefix"}]}}}]} | #/NotificationConfiguration/LambdaConfigurations/0/Filter/S3Key/Rules/0: required key [Value] not found+ {"EventBridgeConfiguration": {}} | #/NotificationConfiguration/EventBridgeConfiguration: required key [EventBridgeEnabled] not found+ {"EventBridgeConfiguration": {"EventBridgeEnabled": "yes"}} | #/NotificationConfiguration/EventBridgeConfiguration/EventBridgeEnabled: expected type: Boolean, found: String+ {"QueueConfigurations": {"Event": "e", "Queue": "q"}} | #/NotificationConfiguration/QueueConfigurations: expected type: JSONArray, found: JSONObject+ {"TopicConfigurations": 5} | #/NotificationConfiguration/TopicConfigurations: expected type: JSONArray, found: Integer+ {"LambdaConfigurations": true} | #/NotificationConfiguration/LambdaConfigurations: expected type: JSONArray, found: Boolean+ {"QueueConfigurations": [{"Event": ["s3:ObjectCreated:*"], "Queue": "q"}]} | #/NotificationConfiguration/QueueConfigurations/0/Event: expected type: String, found: JSONArray+ {"EventBridgeConfiguration": {"EventBridgeEnabled": {"Ref": "Flag"}}} | #/NotificationConfiguration/EventBridgeConfiguration/EventBridgeEnabled: expected type: Boolean, found: JSONObject+ "not-a-configuration" | #/NotificationConfiguration: expected type: JSONObject, found: String+ [{"QueueConfigurations": []}] | #/NotificationConfiguration: expected type: JSONObject, found: JSONArray+ {"QueueConfigurations": ["s3:ObjectCreated:*"]} | #/NotificationConfiguration/QueueConfigurations/0: expected type: JSONObject, found: String+ {"QueueConfigurations": [{"Event": "e", "Queue": "q", "Filter": "prefix"}]} | #/NotificationConfiguration/QueueConfigurations/0/Filter: expected type: JSONObject, found: String+ {"QueueConfigurations": [{"Event": "e", "Queue": "q", "Filter": {"S3Key": []}}]} | #/NotificationConfiguration/QueueConfigurations/0/Filter/S3Key: expected type: JSONObject, found: JSONArray+ {"QueueConfigurations": [{"Event": "e", "Queue": "q", "Filter": {"S3Key": {"Rules": ["x/"]}}}]} | #/NotificationConfiguration/QueueConfigurations/0/Filter/S3Key/Rules/0: expected type: JSONObject, found: String+ {"LambdaConfigurations": [{"Event": "e", "Function": "f", "Filter": {"S3Key": {"Rules": {"Name": "prefix", "Value": "x/"}}}}]} | #/NotificationConfiguration/LambdaConfigurations/0/Filter/S3Key/Rules: expected type: JSONArray, found: JSONObject+ """)+ void aMissingRequiredNotificationKeyFailsTheResource(String notificationConfiguration, String reason) {+ AwsException e = assertThrows(AwsException.class, () -> provisionBucket("""+ {"BucketName": "b", "NotificationConfiguration": %s}+ """.formatted(notificationConfiguration)));++ assertEquals("Model validation failed (" + reason + ")", e.getMessage());+ verify(s3, never()).createBucket(anyString(), anyString());+ verify(s3, never()).putBucketNotificationConfiguration(anyString(), any());+ }++ private static final String REJECTED_QUEUE = """+ "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:missing"}]}+ """;++ private void rejectDestinations() {+ doThrow(new AwsException("InvalidArgument", "Unable to validate the following destination configurations", 400))+ .when(s3).putBucketNotificationConfiguration(anyString(), any());+ }++ /**+ * A destination S3 cannot validate fails the resource instead of reporting CREATE_COMPLETE, and+ * the bucket the attempt created is deleted rather than orphaned. The resource is left without+ * an id, which is how Cloud Control tells a failed create from a successful one.+ */+ @Test+ void aRejectedDestinationFailsTheCreateAndDeletesTheBucketItCreated() {+ rejectDestinations();+ StackResource r = resource("Bucket", "AWS::S3::Bucket");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"BucketName": "b", "Tags": [{"Key": "k", "Value": "v"}], %s}+ """.formatted(REJECTED_QUEUE)), ctx));++ assertEquals("InvalidArgument", e.getErrorCode());+ verify(s3).createBucket("b", REGION);+ verify(s3).deleteBucket("b");+ verify(s3, never()).putBucketTagging(anyString(), any());+ assertEquals(null, r.getPhysicalId());+ }++ /** CreateBucket also answers in us-east-1 for a bucket the account already owns; that one stays. */+ @Test+ void aRejectedDestinationNeverDeletesABucketTheAttemptDidNotCreate() {+ rejectDestinations();+ when(s3.ownsBucket("b")).thenReturn(true);++ assertThrows(AwsException.class, () -> provisionBucket("""+ {"BucketName": "b", %s}+ """.formatted(REJECTED_QUEUE)));++ verify(s3, never()).deleteBucket(anyString());+ }++ @Test+ void aBucketThatCannotBeDeletedAfterARejectionKeepsTheOriginalFailure() {+ rejectDestinations();+ AwsException deleteFailure = new AwsException("InternalError", "disk", 500);+ doThrow(deleteFailure).when(s3).deleteBucket("b");++ AwsException e = assertThrows(AwsException.class, () -> provisionBucket("""+ {"BucketName": "b", %s}+ """.formatted(REJECTED_QUEUE)));++ assertEquals("InvalidArgument", e.getErrorCode());+ assertEquals(List.of(deleteFailure), List.of(e.getSuppressed()));+ }++ /** An update rejected before any property changed the bucket leaves the bucket as it was. */+ @Test+ void aRejectedUpdateLeavesTheBucketAsItWas() {+ rejectDestinations();+ StackResource r = resource("Bucket", "AWS::S3::Bucket");+ r.setPhysicalId("b");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"BucketName": "b", %s}+ """.formatted(REJECTED_QUEUE)), new ProvisionContext(ctx.engine(), REGION, "000000000000",+ "my-stack", "b", event -> { }, props("{\"BucketName\": \"b\"}"))));++ verify(s3, never()).deleteBucket(anyString());+ verify(s3, never()).putBucketNotificationConfiguration(anyString(), any(), eq(true));+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));+ }++ /** A replacing update creates a new bucket; rejected, that one is deleted and the original stays. */+ @Test+ void aRejectedReplacingUpdateDeletesOnlyTheReplacementBucket() {+ rejectDestinations();+ StackResource r = resource("Bucket", "AWS::S3::Bucket");+ r.setPhysicalId("old");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"BucketName": "new", %s}+ """.formatted(REJECTED_QUEUE)), new ProvisionContext(ctx.engine(), REGION, "000000000000",+ "my-stack", "old", event -> { }, props("{\"BucketName\": \"old\"}"))));++ verify(s3).createBucket("new", REGION);+ verify(s3).deleteBucket("new");+ verify(s3, never()).deleteBucket("old");+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));+ }++ /** A CreateBucket that is itself rejected created nothing, so there is nothing to delete. */+ @Test+ void aRejectedCreateBucketLeavesNothingToUndo() {+ doThrow(new AwsException("InvalidBucketName", "The specified bucket is not valid.", 400))+ .when(s3).createBucket("new", REGION);+ StackResource r = resource("Bucket", "AWS::S3::Bucket");+ r.setPhysicalId("old");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"BucketName": "new"}+ """), new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", "old",+ event -> { }, props("{\"BucketName\": \"old\"}"))));++ verify(s3, never()).deleteBucket(anyString());+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));+ }++ @Test+ void anUpdateFailingModelValidationChangesNothing() {+ StackResource r = resource("Bucket", "AWS::S3::Bucket");+ r.setPhysicalId("b");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"BucketName": "b", "VersioningConfiguration": {"Status": "Enabled"},+ "NotificationConfiguration": {"QueueConfigurations": [{"Event": "s3:ObjectCreated:*"}]}}+ """), new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", "b",+ event -> { }, props("{\"BucketName\": \"b\"}"))));++ verify(s3, never()).putBucketVersioning(anyString(), anyString());+ verify(s3, never()).putBucketNotificationConfiguration(anyString(), any());+ }++ private static NotificationConfiguration queueNotification(String queueName) {+ NotificationConfiguration config = new NotificationConfiguration();+ config.getQueueConfigurations().add(new QueueNotification("", "arn:aws:sqs:us-east-1:000000000000:" + queueName,+ List.of("s3:ObjectCreated:*"), List.of()));+ return config;+ }++ /**+ * A property that fails after the configuration was put has the replaced configuration put back,+ * since the engine reports a failed update as rolled back. Its destinations were valid when it+ * was put, so they are not checked again.+ */+ @Test+ void aLaterFailurePutsTheReplacedNotificationConfigurationBack() {+ NotificationConfiguration before = queueNotification("old");+ when(s3.getBucketNotificationConfiguration("b")).thenReturn(before);+ doThrow(new AwsException("MalformedXML", "bad", 400)).when(s3).putBucketVersioning("b", "Bogus");+ StackResource r = resource("Bucket", "AWS::S3::Bucket");+ r.setPhysicalId("b");++ assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"BucketName": "b", "VersioningConfiguration": {"Status": "Bogus"},+ "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:new"}]}}+ """), new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", "b",+ event -> { }, props("{\"BucketName\": \"b\"}"))));++ verify(s3).putBucketNotificationConfiguration(eq("b"), any());+ verify(s3).putBucketNotificationConfiguration("b", before, true);+ assertFalse(r.getAttributes().containsKey(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));+ }++ @Test+ void aLaterFailureOnCreateDeletesTheBucketItCreated() {+ doThrow(new AwsException("MalformedXML", "bad", 400)).when(s3).putBucketVersioning("b", "Bogus");++ assertThrows(AwsException.class, () -> provisionBucket("""+ {"BucketName": "b", "VersioningConfiguration": {"Status": "Bogus"}}+ """));++ verify(s3).deleteBucket("b");+ }++ /** An update whose own undo fails is reported as a rollback failure, not as rolled back. */+ @Test+ void anUndoThatFailsOnAnUpdateIsReportedAsARollbackFailure() {+ when(s3.getBucketNotificationConfiguration("b")).thenReturn(queueNotification("old"));+ doThrow(new AwsException("MalformedXML", "bad", 400)).when(s3).putBucketVersioning("b", "Bogus");+ doThrow(new AwsException("InternalError", "disk", 500))+ .when(s3).putBucketNotificationConfiguration(eq("b"), any(), eq(true));+ StackResource r = resource("Bucket", "AWS::S3::Bucket");+ r.setPhysicalId("b");++ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""+ {"BucketName": "b", "VersioningConfiguration": {"Status": "Bogus"},+ "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:new"}]}}+ """), new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", "b",+ event -> { }, props("{\"BucketName\": \"b\"}"))));++ assertEquals("MalformedXML", e.getErrorCode());+ assertEquals("Could not restore bucket b: disk", r.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_FAILURE_ATTR));+ }++ /** Each put sends a fresh s3:TestEvent to every queue and topic, so an unchanged one is not put again. */+ @Test+ void anUnchangedNotificationConfigurationIsNotPutAgain() {+ NotificationConfiguration current = new NotificationConfiguration();+ current.getQueueConfigurations().add(new QueueNotification("", "arn:aws:sqs:us-east-1:000000000000:q",+ List.of("s3:ObjectCreated:*"), List.of()));+ when(s3.getBucketNotificationConfiguration("b")).thenReturn(current);++ updateBucket("""+ {"BucketName": "b", "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:q"}]}}+ """, """+ {"BucketName": "b", "Tags": [{"Key": "k", "Value": "v"}],+ "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:q"}]}}+ """);++ verify(s3, never()).putBucketNotificationConfiguration(anyString(), any());+ }++ /** An update that a destination rejects has changed nothing else on the bucket. */+ @Test+ void aRejectedDestinationFailsAnUpdateBeforeAnyOtherPropertyIsApplied() {+ doThrow(new AwsException("InvalidArgument", "Unable to validate the following destination configurations", 400))+ .when(s3).putBucketNotificationConfiguration(eq("b"), any());++ assertThrows(AwsException.class, () -> updateBucket("""+ {"BucketName": "b"}+ """, """+ {"BucketName": "b", "VersioningConfiguration": {"Status": "Enabled"},+ "NotificationConfiguration": {"QueueConfigurations": [+ {"Event": "s3:ObjectCreated:*", "Queue": "arn:aws:sqs:us-east-1:000000000000:missing"}]}}+ """));++ verify(s3, never()).putBucketVersioning(anyString(), anyString());+ verify(s3, never()).deleteBucketCors(anyString());+ }+/*** primaryIdentifier in the registry schema is /properties/Bucket, so the bucket name is the* physical id. The type has no readOnlyProperties, so it has no Fn::GetAtt and the attributediff --git a/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.java b/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.javaindex a23643da72..1cd8e9627e 100644--- a/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/s3/S3GlobalBucketNamespaceTest.java@@ -53,6 +53,28 @@ class S3GlobalBucketNamespaceTest {return inst;}+ /**+ * CreateBucket only sees the caller's own buckets, so a caller that wants to know whether it+ * just created one asks ownsBucket, which stays owner-scoped where bucketExists spans accounts.+ */+ @Test+ void ownsBucketIsOwnerScopedWhereBucketExistsSpansAccounts() {+ Instance<RequestContext> ctx = mutableContext();+ AccountAwareStorageBackend<Bucket> buckets =+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);+ AccountAwareStorageBackend<S3Object> objects =+ new AccountAwareStorageBackend<>(new InMemoryStorage<>(), ctx, DEFAULT_ACCT);+ S3Service globalNs = new S3Service(buckets, objects, Path.of("s3-gns-test"), true, true);++ caller.set(ACCOUNT_A);+ globalNs.createBucket("owned-by-a", "us-west-2");+ assertTrue(globalNs.ownsBucket("owned-by-a"));++ caller.set(ACCOUNT_B);+ assertTrue(globalNs.bucketExists("owned-by-a"));+ assertFalse(globalNs.ownsBucket("owned-by-a"));+ }+@Testvoid bucketOwnedByOneAccountIsResolvableCrossAccountButNotListed() {Instance<RequestContext> ctx = mutableContext();