Light, fluffy, and always free - The AWS Local Emulator alternative
feat(cloudformation): provision AWS::Events::EventBus as a real custom bus (#1807)
Alex Bannabc21367cc4de
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventBusTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventBusTest.javanew file mode 100644index 0000000000..e9e9e8ce19--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationEventBusTest.java@@ -0,0 +1,195 @@+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.Test;+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;+import software.amazon.awssdk.services.cloudformation.model.CreateStackRequest;+import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest;+import software.amazon.awssdk.services.cloudformation.model.DescribeStacksRequest;+import software.amazon.awssdk.services.cloudformation.model.Output;+import software.amazon.awssdk.services.cloudformation.model.Stack;+import software.amazon.awssdk.services.eventbridge.EventBridgeClient;+import software.amazon.awssdk.services.eventbridge.model.DescribeEventBusRequest;+import software.amazon.awssdk.services.eventbridge.model.DescribeEventBusResponse;+import software.amazon.awssdk.services.eventbridge.model.ListTagsForResourceRequest;+import software.amazon.awssdk.services.eventbridge.model.ResourceNotFoundException;++import java.util.List;+import java.util.Map;+import java.util.stream.Collectors;++import static org.assertj.core.api.Assertions.assertThat;+import static org.assertj.core.api.Assertions.assertThatThrownBy;++@DisplayName("CloudFormation AWS::Events::EventBus")+class CloudFormationEventBusTest {++ private static CloudFormationClient cloudFormation;+ private static EventBridgeClient eventBridge;+ private static String stackName;+ private static String busName;++ @BeforeAll+ static void setup() {+ cloudFormation = TestFixtures.cloudFormationClient();+ eventBridge = TestFixtures.eventBridgeClient();+ stackName = TestFixtures.uniqueName("compat-cfn-eventbus");+ busName = TestFixtures.uniqueName("compat-eventbus");+ }++ @AfterAll+ static void cleanup() {+ if (cloudFormation != null) {+ try {+ cloudFormation.deleteStack(+ DeleteStackRequest.builder().stackName(stackName).build());+ } catch (Exception e) {+ System.err.println("CloudFormation EventBus cleanup skipped: " + e.getMessage());+ }+ cloudFormation.close();+ }+ if (eventBridge != null) {+ eventBridge.close();+ }+ }++ @Test+ void createsValidatesUpdatesAndDeletesEventBusThroughAwsSdk() throws InterruptedException {+ cloudFormation.createStack(CreateStackRequest.builder()+ .stackName(stackName)+ .templateBody(template("before", "old", "remove"))+ .build());+ assertThat(waitForTerminal(stackName, 30)).isEqualTo("CREATE_COMPLETE");++ Stack createdStack = cloudFormation.describeStacks(+ DescribeStacksRequest.builder().stackName(stackName).build())+ .stacks().get(0);+ Map<String, String> outputs = createdStack.outputs().stream()+ .collect(Collectors.toMap(Output::outputKey, Output::outputValue));+ String busArn = "arn:aws:events:us-east-1:000000000000:event-bus/" + busName;+ assertThat(outputs)+ .containsEntry("BusRef", busName)+ .containsEntry("BusName", busName)+ .containsEntry("BusArn", busArn);++ DescribeEventBusResponse created = eventBridge.describeEventBus(+ DescribeEventBusRequest.builder().name(busName).build());+ assertThat(created.name()).isEqualTo(busName);+ assertThat(created.arn()).isEqualTo(busArn);+ assertThat(created.description()).isEqualTo("before");+ assertThat(tags(busArn))+ .containsEntry("keep", "old")+ .containsEntry("remove", "old");++ cloudFormation.updateStack(r -> r+ .stackName(stackName)+ .templateBody(template("before", "old", "remove")));+ assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_COMPLETE");++ cloudFormation.updateStack(r -> r+ .stackName(stackName)+ .templateBody(template("after", "new", "add")));+ assertThat(waitForTerminal(stackName, 30)).isEqualTo("UPDATE_ROLLBACK_COMPLETE");++ DescribeEventBusResponse afterRejectedUpdate = eventBridge.describeEventBus(+ DescribeEventBusRequest.builder().name(busName).build());+ assertThat(afterRejectedUpdate.description()).isEqualTo("before");+ assertThat(tags(busArn))+ .containsEntry("keep", "old")+ .containsEntry("remove", "old")+ .doesNotContainKey("add");++ cloudFormation.deleteStack(DeleteStackRequest.builder().stackName(stackName).build());+ waitForDeleted(stackName, 30);+ assertThatThrownBy(() -> eventBridge.describeEventBus(+ DescribeEventBusRequest.builder().name(busName).build()))+ .isInstanceOf(ResourceNotFoundException.class);+ }++ private static Map<String, String> tags(String busArn) {+ return eventBridge.listTagsForResource(ListTagsForResourceRequest.builder()+ .resourceARN(busArn)+ .build())+ .tags().stream()+ .collect(Collectors.toMap(+ software.amazon.awssdk.services.eventbridge.model.Tag::key,+ software.amazon.awssdk.services.eventbridge.model.Tag::value));+ }++ private static String template(String description, String keepValue, String secondTagKey) {+ return """+ {+ "Resources": {+ "Bus": {+ "Type": "AWS::Events::EventBus",+ "Properties": {+ "Name": "%s",+ "Description": "%s",+ "Tags": [+ {"Key": "keep", "Value": "%s"},+ {"Key": "%s", "Value": "%s"}+ ]+ }+ },+ "Rule": {+ "Type": "AWS::Events::Rule",+ "Properties": {+ "Name": "%s",+ "EventBusName": {"Ref": "Bus"},+ "EventPattern": {"source": ["com.example.orders"]},+ "State": "ENABLED"+ }+ }+ },+ "Outputs": {+ "BusRef": {"Value": {"Ref": "Bus"}},+ "BusArn": {"Value": {"Fn::GetAtt": ["Bus", "Arn"]}},+ "BusName": {"Value": {"Fn::GetAtt": ["Bus", "Name"]}}+ }+ }+ """.formatted(+ busName, description, keepValue, secondTagKey, keepValue, busName + "-rule");+ }++ private static String waitForTerminal(String name, int maxSeconds) throws InterruptedException {+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;+ while (System.currentTimeMillis() < deadline) {+ List<Stack> stacks = cloudFormation.describeStacks(+ DescribeStacksRequest.builder().stackName(name).build()).stacks();+ if (!stacks.isEmpty()) {+ String status = stacks.get(0).stackStatusAsString();+ if (!status.endsWith("_IN_PROGRESS")) {+ return status;+ }+ }+ Thread.sleep(500);+ }+ throw new AssertionError(+ "Stack " + name + " did not reach a terminal state within " + maxSeconds + "s");+ }++ private static void waitForDeleted(String name, int maxSeconds) throws InterruptedException {+ long deadline = System.currentTimeMillis() + maxSeconds * 1000L;+ while (System.currentTimeMillis() < deadline) {+ try {+ List<Stack> stacks = cloudFormation.describeStacks(+ DescribeStacksRequest.builder().stackName(name).build()).stacks();+ if (stacks.isEmpty()+ || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString())) {+ return;+ }+ } catch (CloudFormationException e) {+ if (e.getMessage() != null && e.getMessage().contains("does not exist")) {+ return;+ }+ throw e;+ }+ Thread.sleep(500);+ }+ throw new AssertionError(+ "Stack " + name + " was not deleted within " + maxSeconds + "s");+ }+}diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.mdindex 4ad8ea6c45..f3f9148b6c 100644--- a/docs/services/cloudformation.md+++ b/docs/services/cloudformation.md@@ -88,6 +88,20 @@ All other resource types are accepted without error and assigned a synthetic phy`arn:aws:stub:::<logicalId>` ARN attribute), so templates with unsupported types still reach`CREATE_COMPLETE` rather than failing.+## EventBridge Event Buses++`AWS::Events::EventBus` creates a real custom EventBridge bus. `Name` is required, `Ref` returns+the bus name, and `Fn::GetAtt` supports `Arn` and `Name`. `Description` and `Tags` are applied when+the bus is created. Rules that reference the bus are removed before stack deletion.++The current implementation is limited to custom buses with the `Name`, `Description`, `Tags`, and+`Policy` properties. `EventSourceName`, `KmsKeyIdentifier`, `DeadLetterConfig`, and `LogConfig` are+rejected with `ValidationError` instead of being silently ignored. AWS models a `Name` change as+resource replacement; Floci currently rejects that update until generic replacement handling is+available. `Policy` is applied when the bus is created. Changing `Description`, `Tags`, or `Policy`+during `UpdateStack` is rejected until transactional resource rollback is available; this prevents a+failed stack update from leaving the live bus in the rejected configuration.+## Secrets Manager Target Attachments`AWS::SecretsManager::SecretTargetAttachment` adds the target's database connection fields to thediff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.javaindex ae8c741889..73c154ab93 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java@@ -102,6 +102,7 @@ import java.nio.charset.StandardCharsets;import java.time.Duration;import java.util.*;import java.util.concurrent.TimeoutException;+import java.util.regex.Pattern;import java.util.zip.ZipEntry;import java.util.zip.ZipOutputStream;@@ -120,6 +121,13 @@ public class CloudFormationResourceProvisioner {private static final String INLINE_CLEANUP_ROLE_TARGETS_ATTR = "__FlociInlineCleanupRoleTargets";private static final String INLINE_CLEANUP_USER_TARGETS_ATTR = "__FlociInlineCleanupUserTargets";private static final String INLINE_CLEANUP_GROUP_TARGETS_ATTR = "__FlociInlineCleanupGroupTargets";+ private static final String EVENT_BUS_CREATED_TIME_ATTR = "FlociEventBusCreatedTime";+ private static final String EVENT_BUS_MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys";+ private static final String EVENT_BUS_MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy";+ private static final Set<String> EVENT_BUS_SUPPORTED_PROPERTIES =+ Set.of("Name", "Description", "Tags", "Policy");+ private static final Pattern EVENT_BUS_TAG_PATTERN =+ Pattern.compile("[\\p{L}\\p{N}\\p{Z}_.:/=+\\-@]*");private static final String NAME_MODE_EXPLICIT = "explicit";private static final String NAME_MODE_GENERATED = "generated";private static final String LOG_GROUP_NAME_MODE_ATTR = "FlociLogGroupNameMode";@@ -306,7 +314,7 @@ public class CloudFormationResourceProvisioner {case "AWS::Route53::HostedZone" -> provisionRoute53HostedZone(resource, properties, engine);case "AWS::Route53::RecordSet" -> provisionRoute53RecordSet(resource, properties, engine);case "AWS::Events::Rule" -> provisionEventBridgeRule(resource, properties, engine, region, stackName);- case "AWS::Events::EventBus" -> provisionEventBus(resource, properties, engine, region, stackName);+ case "AWS::Events::EventBus" -> provisionEventBridgeEventBus(resource, properties, engine, region);case "AWS::Events::EventBusPolicy" -> provisionEventBusPolicy(resource, properties, engine, region);case "AWS::ApiGateway::RestApi" -> provisionApiGatewayRestApi(resource, properties, engine, region, accountId, stackName);case "AWS::ApiGateway::Resource" -> provisionApiGatewayResource(resource, properties, engine, region);@@ -465,6 +473,18 @@ public class CloudFormationResourceProvisioner {deleteManagedPolicy(resource);return;}+ // A Rule on a custom bus is keyed by that bus; the physical id is only the rule name, so the+ // type/physicalId path resolves to the "default" bus and never finds it — leaving the rule (and+ // then its bus) undeletable. Pass the bus name captured at provision time.+ if ("AWS::Events::Rule".equals(resourceType)) {+ deleteEventBridgeRuleSafe(resource.getPhysicalId(),+ resource.getAttributes().get("EventBusName"), region);+ return;+ }+ if ("AWS::Events::EventBus".equals(resourceType)) {+ deleteEventBusSafe(resource, region);+ return;+ }delete(resourceType, resource.getPhysicalId(), region);}@@ -503,6 +523,7 @@ public class CloudFormationResourceProvisioner {"ValidationError","SecretTargetAttachment deletion requires the StackResource metadata that records its managed fields.",400);+ // No bus context on the type/physicalId path (e.g. CREATE-rollback); targets the default bus.case "AWS::Events::Rule" -> deleteEventBridgeRuleSafe(physicalId, null, region);case "AWS::Events::EventBus" -> deleteEventBusSafe(physicalId, region);case "AWS::Events::EventBusPolicy" -> removeEventBusPolicySafe(physicalId, region);@@ -2810,6 +2831,8 @@ public class CloudFormationResourceProvisioner {state, description, roleArn, Map.of(), region);r.setPhysicalId(ruleName);r.getAttributes().put("Arn", rule.getArn());+ // A rule on a custom bus is keyed by that bus; remember it so the resource delete can target+ // the right bus (the physical id is only the rule name, which resolves to the default bus).if (busName != null && !busName.isBlank()) {r.getAttributes().put("EventBusName", busName);}@@ -2857,70 +2880,321 @@ public class CloudFormationResourceProvisioner {}}+ /**+ * Provisions an {@code AWS::Events::EventBus} (a custom EventBridge event bus). Without this the+ * resource would fall through to the generic stub, which assigns a physical id but never registers+ * the bus with the EventBridge service — so any {@code AWS::Events::Rule} (or PutEvents) targeting+ * the bus fails "EventBus not found". Per the AWS spec, {@code Ref} returns the bus <em>name</em>+ * (not the ARN), so the physical id is the name; {@code Fn::GetAtt "Arn"} exposes the ARN.+ */+ private void provisionEventBridgeEventBus(StackResource r, JsonNode props,+ CloudFormationTemplateEngine engine, String region) {+ validateEventBusProperties(props);+ String existingBusName = r.getPhysicalId();+ String busName = resolveOptional(props, "Name", engine);+ validateEventBusName(busName);+ if (existingBusName != null && !existingBusName.equals(busName)) {+ throw new AwsException("ValidationError",+ "Updating EventBus Name requires resource replacement, which is not supported.", 400);+ }+ String description = resolveOptional(props, "Description", engine);+ if (description != null && description.length() > 512) {+ throw new AwsException("ValidationError",+ "AWS::Events::EventBus Description must not exceed 512 characters.", 400);+ }+ Map<String, String> tags = parseEventBusTags(+ props != null ? props.get("Tags") : null, engine);+ JsonNode policy = resolveEventBusPolicy(props, engine);++ EventBus bus;+ boolean createdBus = false;+ try {+ bus = eventBridgeService.createEventBus(busName, description, tags, region);+ createdBus = true;+ r.getAttributes().put(CfnRollback.ROLLBACK_OWNED_ATTR, "true");+ } catch (AwsException e) {+ boolean stackAlreadyOwnsBus = existingBusName != null && existingBusName.equals(busName);+ if (!stackAlreadyOwnsBus || !"ResourceAlreadyExistsException".equals(e.getErrorCode())) {+ throw e;+ }+ bus = eventBridgeService.describeEventBus(busName, region);+ // A missing created-time means ownership was never tracked, not that it changed: stacks+ // provisioned before this attribute existed are restored without it. Refusing there would+ // wedge every later UpdateStack, including no-op ones. Only a recorded time that actually+ // disagrees means the bus was recreated out of band and belongs to its new owner.+ String existingCreatedTime = r.getAttributes().get(EVENT_BUS_CREATED_TIME_ATTR);+ String actualCreatedTime = eventBusCreatedTime(bus);+ if (existingCreatedTime != null && !existingCreatedTime.equals(actualCreatedTime)) {+ r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR);+ throw e;+ }+ validateEventBusMutablePropertiesUnchanged(r, bus, description, tags, policy);+ }++ // Record identity before applying the policy: rollbackCreatedResources skips any resource+ // whose physicalId is still null, so a putPermission failure after the bus exists would+ // otherwise orphan it with no way for rollback to find it.+ r.setPhysicalId(busName); // Ref → EventBus name (AWS-faithful)+ r.getAttributes().put("Arn", bus.getArn());+ r.getAttributes().put("Name", busName);+ r.getAttributes().put(EVENT_BUS_CREATED_TIME_ATTR, eventBusCreatedTime(bus));+ recordEventBusManagedTagKeys(r, tags.keySet());+ recordEventBusManagedPolicy(r, policy);++ // Apply an optional inline resource policy only during creation. Updating it is rejected by+ // validateEventBusMutablePropertiesUnchanged until stack updates can roll back live resource+ // mutations transactionally.+ if (createdBus && !policy.isNull()) {+ eventBridgeService.putPermission(busName, null, null, null, null, policy.toString(), region);+ }+ }++ private void validateEventBusProperties(JsonNode props) {+ if (props == null || props.isNull()) {+ return;+ }+ if (!props.isObject()) {+ throw new AwsException("ValidationError",+ "AWS::Events::EventBus Properties must be an object.", 400);+ }+ List<String> unsupported = new ArrayList<>();+ props.fieldNames().forEachRemaining(name -> {+ if (!EVENT_BUS_SUPPORTED_PROPERTIES.contains(name)) {+ unsupported.add(name);+ }+ });+ if (!unsupported.isEmpty()) {+ Collections.sort(unsupported);+ throw new AwsException("ValidationError",+ "Unsupported AWS::Events::EventBus properties: "+ + String.join(", ", unsupported), 400);+ }+ }++ private void validateEventBusName(String busName) {+ if (busName == null || busName.isBlank()) {+ throw new AwsException("ValidationError",+ "Name is required for AWS::Events::EventBus.", 400);+ }+ if (busName.length() > 256+ || !busName.matches("[.\\-_A-Za-z0-9]+")+ || "default".equals(busName)) {+ throw new AwsException("ValidationError",+ "Invalid custom event bus Name: " + busName, 400);+ }+ }++ private Map<String, String> parseEventBusTags(+ JsonNode tagsNode, CloudFormationTemplateEngine engine) {+ if (tagsNode == null || tagsNode.isNull()) {+ return Map.of();+ }+ JsonNode resolvedTags = engine.resolveNode(tagsNode);+ if (!resolvedTags.isArray()) {+ throw new AwsException("ValidationError",+ "AWS::Events::EventBus Tags must be an array.", 400);+ }+ if (resolvedTags.size() > 50) {+ throw new AwsException("ValidationError",+ "AWS::Events::EventBus supports at most 50 tags.", 400);+ }+ Map<String, String> tags = new LinkedHashMap<>();+ for (JsonNode entry : resolvedTags) {+ if (!entry.isObject()) {+ throw new AwsException("ValidationError",+ "Each AWS::Events::EventBus tag must be an object.", 400);+ }+ String key = entry.path("Key").asText(null);+ String value = entry.path("Value").asText(null);+ if (key == null || key.isEmpty() || key.length() > 128) {+ throw new AwsException("ValidationError",+ "Event bus tag Key must contain 1 to 128 characters.", 400);+ }+ if (key.regionMatches(true, 0, "aws:", 0, 4)) {+ throw new AwsException("ValidationError",+ "Event bus tag Key must not use the reserved aws: prefix.", 400);+ }+ if (!EVENT_BUS_TAG_PATTERN.matcher(key).matches()) {+ throw new AwsException("ValidationError",+ "Event bus tag Key contains unsupported characters.", 400);+ }+ if (value == null || value.length() > 256) {+ throw new AwsException("ValidationError",+ "Event bus tag Value must contain at most 256 characters.", 400);+ }+ if (!EVENT_BUS_TAG_PATTERN.matcher(value).matches()) {+ throw new AwsException("ValidationError",+ "Event bus tag Value contains unsupported characters.", 400);+ }+ if (tags.putIfAbsent(key, value) != null) {+ throw new AwsException("ValidationError",+ "Duplicate event bus tag Key: " + key, 400);+ }+ }+ return tags;+ }++ private void validateEventBusMutablePropertiesUnchanged(+ StackResource resource, EventBus bus, String requestedDescription,+ Map<String, String> requestedTags, JsonNode requestedPolicy) {+ if (!Objects.equals(bus.getDescription(), requestedDescription)) {+ throw unsupportedEventBusMutableUpdate();+ }++ // Stacks persisted by the older EventBus provisioner have no managed-key metadata. There+ // is no reliable way to distinguish their CloudFormation tags from tags added out of band,+ // so allow this one-time adoption and start tracking the requested keys afterwards.+ if (resource.getAttributes().containsKey(EVENT_BUS_MANAGED_TAG_KEYS_ATTR)) {+ Map<String, String> currentManagedTags = new LinkedHashMap<>();+ for (String key : eventBusManagedTagKeys(resource)) {+ if (bus.getTags().containsKey(key)) {+ currentManagedTags.put(key, bus.getTags().get(key));+ }+ }+ if (!currentManagedTags.equals(requestedTags)) {+ throw unsupportedEventBusMutableUpdate();+ }+ }++ String managedPolicy = resource.getAttributes().get(EVENT_BUS_MANAGED_POLICY_ATTR);+ JsonNode policyToCompare = managedPolicy != null+ ? parseEventBusPolicy(managedPolicy, "stored CloudFormation metadata")+ : parseEventBusPolicy(bus.getPolicy(), "the existing event bus");+ if (managedPolicy != null || !requestedPolicy.isNull()) {+ if (!policyToCompare.equals(requestedPolicy)) {+ throw unsupportedEventBusMutableUpdate();+ }+ }+ }++ private JsonNode resolveEventBusPolicy(JsonNode props, CloudFormationTemplateEngine engine) {+ if (props == null || !props.has("Policy") || props.get("Policy").isNull()) {+ return JsonNodeFactory.instance.nullNode();+ }+ return engine.resolveNode(props.get("Policy"));+ }++ private JsonNode parseEventBusPolicy(String policy, String source) {+ if (policy == null) {+ return JsonNodeFactory.instance.nullNode();+ }+ try {+ JsonNode parsed = objectMapper.readTree(policy);+ return parsed != null ? parsed : JsonNodeFactory.instance.nullNode();+ } catch (Exception e) {+ throw new AwsException("InternalFailure",+ "Invalid EventBus policy in " + source + ": " + e.getMessage(), 500);+ }+ }++ private void recordEventBusManagedPolicy(StackResource resource, JsonNode policy) {+ try {+ resource.getAttributes().put(EVENT_BUS_MANAGED_POLICY_ATTR,+ objectMapper.writeValueAsString(policy));+ } catch (Exception e) {+ throw new AwsException("InternalFailure",+ "Failed to store EventBus managed-policy metadata: " + e.getMessage(), 500);+ }+ }++ private AwsException unsupportedEventBusMutableUpdate() {+ return new AwsException("ValidationError",+ "Updating AWS::Events::EventBus Description, Tags, or Policy is not supported "+ + "until transactional rollback is available.", 400);+ }++ private Set<String> eventBusManagedTagKeys(StackResource resource) {+ String value = resource.getAttributes().get(EVENT_BUS_MANAGED_TAG_KEYS_ATTR);+ if (value == null || value.isBlank()) {+ return Set.of();+ }+ try {+ JsonNode keys = objectMapper.readTree(value);+ if (!keys.isArray()) {+ throw new IllegalArgumentException("managed tag keys are not an array");+ }+ Set<String> result = new HashSet<>();+ keys.forEach(key -> result.add(key.asText()));+ return result;+ } catch (Exception e) {+ throw new AwsException("InternalFailure",+ "Invalid stored EventBus managed-tag metadata: " + e.getMessage(), 500);+ }+ }++ private void recordEventBusManagedTagKeys(StackResource resource, Set<String> keys) {+ try {+ resource.getAttributes().put(+ EVENT_BUS_MANAGED_TAG_KEYS_ATTR,+ objectMapper.writeValueAsString(new TreeSet<>(keys)));+ } catch (Exception e) {+ throw new AwsException("InternalFailure",+ "Failed to store EventBus managed-tag metadata: " + e.getMessage(), 500);+ }+ }++ private String eventBusCreatedTime(EventBus bus) {+ return bus.getCreatedTime() != null ? bus.getCreatedTime().toString() : "";+ }+private void deleteEventBridgeRuleSafe(String ruleName, String busName, String region) {try {- // Remove all targets before deleting the rule+ // Remove all targets before deleting the rule (busName scopes the lookup to the rule's bus).var targets = eventBridgeService.listTargetsByRule(ruleName, busName, region);if (!targets.isEmpty()) {List<String> targetIds = targets.stream().map(Target::getId).toList();eventBridgeService.removeTargets(ruleName, busName, targetIds, region);}eventBridgeService.deleteRule(ruleName, busName, region);+ } catch (AwsException e) {+ // An already-deleted rule is the one failure that genuinely means "done". Anything else+ // is a real error worth surfacing rather than hiding behind a debug line.+ if (!"ResourceNotFoundException".equals(e.getErrorCode())) {+ throw e;+ }+ LOG.debugv("EventBridge rule already gone, treating as deleted: {0}", ruleName);} catch (Exception e) {- LOG.debugv("Could not delete EventBridge rule {0}: {1}", ruleName, e.getMessage());+ throw new AwsException("InternalFailure",+ "Could not delete EventBridge rule " + ruleName + ": " + e.getMessage(), 500);}}- private void provisionEventBus(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,- String region, String stackName) {- String name = resolveOptional(props, "Name", engine);- if (name == null || name.isBlank()) {- name = generatePhysicalName(stackName, r.getLogicalId(), 256, false);- }- String description = resolveOptional(props, "Description", engine);-- Map<String, String> tags = new HashMap<>();- if (props != null && props.has("Tags") && props.get("Tags").isArray()) {- for (JsonNode tag : props.get("Tags")) {- String key = engine.resolve(tag.path("Key"));- if (!key.isEmpty()) {- tags.put(key, engine.resolve(tag.path("Value")));- }+ private void deleteEventBusSafe(String busName, String region) {+ try {+ eventBridgeService.deleteEventBus(busName, region);+ } catch (AwsException e) {+ if (!"ResourceNotFoundException".equals(e.getErrorCode())) {+ throw e;}+ LOG.debugv("Event bus already gone, treating as deleted: {0}", busName);}+ }+ private void deleteEventBusSafe(StackResource resource, String region) {+ String busName = resource.getPhysicalId();EventBus bus;try {- bus = eventBridgeService.createEventBus(name, description, tags, region);+ bus = eventBridgeService.describeEventBus(busName, region);} catch (AwsException e) {- if ("ResourceAlreadyExistsException".equals(e.getErrorCode())) {- bus = eventBridgeService.describeEventBus(name, region);- } else {- throw e;+ if ("ResourceNotFoundException".equals(e.getErrorCode())) {+ LOG.debugv("Event bus already gone, treating as deleted: {0}", busName);+ return;}+ throw e;}- // Optional inline resource policy (rare for CDK EventBus constructs).- if (props != null && props.has("Policy") && !props.get("Policy").isNull()) {- String policyJson = engine.resolveNode(props.get("Policy")).toString();- eventBridgeService.putPermission(name, null, null, null, null, policyJson, region);+ // A missing attribute means ownership was never tracked, not that it changed: stacks+ // provisioned before this attribute existed are restored from cloudformation-stacks.json+ // without it. Refusing there would leave every such stack permanently in DELETE_FAILED, so+ // fall back to the pre-tracking behaviour of deleting what the stack recorded it created.+ String expectedCreatedTime = resource.getAttributes().get(EVENT_BUS_CREATED_TIME_ATTR);+ if (expectedCreatedTime != null && !expectedCreatedTime.equals(eventBusCreatedTime(bus))) {+ throw new AwsException("ValidationError",+ "EventBus ownership changed; refusing to delete: " + busName, 400);}-- r.setPhysicalId(name);- r.getAttributes().put("Arn", bus.getArn());- r.getAttributes().put("Name", name);+ deleteEventBusSafe(busName, region);}- private void deleteEventBusSafe(String name, String region) {- try {- eventBridgeService.deleteEventBus(name, region);- } catch (Exception e) {- // Warn (not debug): the stack still records the resource as DELETE_COMPLETE, so a bus- // left alive here (e.g. rules deleted out of dependency order) is a silent divergence- // that must stay diagnosable.- LOG.warnv("Could not delete event bus {0}: {1}", name, e.getMessage());- }- }private void provisionEventBusPolicy(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,String region) {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 b74aed46f9..b1b4dc1aca 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@@ -407,6 +407,7 @@ public class CloudFormationService {private void executeTemplate(Stack stack, String templateBody, Map<String, String> params,boolean isCreate, String region, String accountId) {+ String previousTemplateBody = stack.getTemplateBody();try {JsonNode template = parseTemplate(templateBody);@@ -459,6 +460,7 @@ public class CloudFormationService {name -> exports.get(exportKey(region, name)));StackResource resource = stack.getResources().get(logicalId);+ StackResource previousResource = resource;if (resource == null) {resource = new StackResource();resource.setLogicalId(logicalId);@@ -490,6 +492,12 @@ public class CloudFormationService {if ("CREATE_FAILED".equals(resource.getStatus())|| "UPDATE_FAILED".equals(resource.getStatus())) {failedResource = resource;+ if (!isCreate && previousResource != null) {+ // Provisioners work on a copy of the stored resource metadata. Keep the+ // last known-good identity and status when an update attempt fails so a+ // later retry or stack deletion still manages the original resource.+ stack.getResources().put(logicalId, previousResource);+ }break;}}@@ -498,6 +506,9 @@ public class CloudFormationService {// A resource failed to provision: stop, and (on create) roll back what we built so a// corrected re-deploy starts from a clean slate (acceptance criterion #9).if (failedResource != null) {+ if (!isCreate) {+ stack.setTemplateBody(previousTemplateBody);+ }rollbackFailedExecution(stack, region, isCreate, failedResource);return;}@@ -556,6 +567,9 @@ public class CloudFormationService {} catch (Exception e) {LOG.errorv("Stack {0} execution failed: {1}", stack.getStackName(), e.getMessage());+ if (!isCreate) {+ stack.setTemplateBody(previousTemplateBody);+ }String failStatus = isCreate ? "CREATE_FAILED" : "UPDATE_FAILED";stack.setStatus(failStatus);stack.setStatusReason(e.getMessage());@@ -570,9 +584,10 @@ public class CloudFormationService {** <p>On a <b>create</b>, rolls back by deleting the resources that were successfully created in* this execution, leaving a clean slate ({@code ROLLBACK_COMPLETE}) so a corrected re-deploy can- * start from scratch. On an <b>update</b>, marks {@code UPDATE_ROLLBACK_COMPLETE} and keeps the- * prior physical IDs so a corrected re-deploy proceeds (full prior-template restoration is out- * of scope — see plan Part 7).+ * start from scratch. On an <b>update</b>, marks {@code UPDATE_ROLLBACK_COMPLETE}; the caller+ * restores the prior template and failed-resource metadata so retries and deletion continue to+ * manage the last known-good physical resource. Rolling back side effects from resources that+ * completed earlier in the failed update remains out of scope.*/private void rollbackFailedExecution(Stack stack, String region, boolean isCreate,StackResource failedResource) {diff --git a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.javaindex 60dd8f1561..c8f131d677 100644--- a/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java+++ b/src/main/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeService.java@@ -137,9 +137,8 @@ public class EventBridgeService {public EventBus createEventBus(String name, String description,Map<String, String> tags, String region) {- if (name == null || name.isBlank()) {- throw new AwsException("ValidationException", "EventBus name is required.", 400);- }+ validateCustomEventBusName(name);+ validateEventBusDescription(description);String key = busKey(region, name);if (busStore.get(key).isPresent()) {throw new AwsException("ResourceAlreadyExistsException",@@ -166,13 +165,15 @@ public class EventBridgeService {throw new AwsException("ValidationException", "EventBus name is required.", 400);}String effectiveName = resolvedBusName(name);+ validateEventBusNameForMutation(effectiveName);if ("default".equals(effectiveName)) {throw new AwsException("ValidationException", "Cannot delete the default event bus.", 400);}String key = busKey(region, effectiveName);- EventBus bus = busStore.get(key)- .orElseThrow(() -> new AwsException("ResourceNotFoundException",- "EventBus not found: " + effectiveName, 404));+ EventBus bus = busStore.get(key).orElse(null);+ if (bus == null) {+ return;+ }String rulePrefix = ruleKeyPrefix(region, effectiveName);boolean hasRules = ruleStore.keys().stream().anyMatch(k -> k.startsWith(rulePrefix));if (hasRules) {@@ -192,7 +193,7 @@ public class EventBridgeService {}return busStore.get(busKey(region, effectiveName)).orElseThrow(() -> new AwsException("ResourceNotFoundException",- "EventBus not found: " + name, 404));+ "EventBus not found: " + name, 400));}public EventBus updateEventBus(String name,@@ -201,19 +202,22 @@ public class EventBridgeService {String deadLetterConfig,String logConfig,String region) {+ validateEventBusDescription(description);+ if (name != null) {+ validateEventBusNameForMutation(name);+ }// Name identifies the bus; never mutated (AWS does not support rename).- String effectiveName = name == null || name.isBlank() ? "default" : name;+ String effectiveName = name == null ? "default" : name;EventBus bus = "default".equals(effectiveName)? getOrCreateDefaultBus(region): busStore.get(busKey(region, effectiveName)).orElseThrow(() -> new AwsException("ResourceNotFoundException",- "EventBus not found: " + effectiveName, 404));+ "EventBus not found: " + effectiveName, 400));- // Only mark dirty when a field is both non-blank AND different from- // the value currently on the bus — re-sending the same value is a no-op.+ // Description accepts an explicit empty string so callers can clear it. A null value means+ // the field was omitted and must remain unchanged.boolean dirty = false;- if (description != null && !description.isBlank()- && !description.equals(bus.getDescription())) {+ if (description != null && !description.equals(bus.getDescription())) {bus.setDescription(description);dirty = true;}@@ -241,6 +245,34 @@ public class EventBridgeService {return bus;}+ private void validateCustomEventBusName(String name) {+ if (name == null || name.isBlank()) {+ throw new AwsException("ValidationException", "EventBus name is required.", 400);+ }+ if (name.length() > 256+ || !name.matches("[.\\-_A-Za-z0-9]+")+ || "default".equals(name)) {+ throw new AwsException("ValidationException",+ "Invalid custom event bus name: " + name, 400);+ }+ }++ private void validateEventBusDescription(String description) {+ if (description != null && description.length() > 512) {+ throw new AwsException("ValidationException",+ "EventBus description must not exceed 512 characters.", 400);+ }+ }++ private void validateEventBusNameForMutation(String name) {+ if (name.isEmpty()+ || name.length() > 256+ || !name.matches("[/\\.\\-_A-Za-z0-9]+")) {+ throw new AwsException("ValidationException",+ "Invalid event bus name: " + name, 400);+ }+ }+public List<EventBus> listEventBuses(String namePrefix, String region) {getOrCreateDefaultBus(region);String storagePrefix = "bus:" + region + ":";diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventBusIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventBusIntegrationTest.javanew file mode 100644index 0000000000..d6c5d1a71b--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEventBusIntegrationTest.java@@ -0,0 +1,765 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;+import io.quarkus.test.junit.QuarkusTest;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;++/**+ * Verifies CloudFormation provisions {@code AWS::Events::EventBus} as a real custom EventBridge bus.+ *+ * <p>Previously the type had no provisioner case, so it fell through to the generic stub: the resource+ * reported CREATE_COMPLETE with a physical id but the bus was never registered with the EventBridge+ * service. Any {@code AWS::Events::Rule} referencing it via {@code {"Ref": bus}} then failed+ * "EventBus not found", rolling the whole stack back. Per the AWS spec {@code Ref} returns the bus+ * <em>name</em> and {@code Fn::GetAtt "Arn"} the ARN.+ *+ * <p>All resources are metadata-only (no container), so the test is Docker-free.+ */+@QuarkusTest+class CloudFormationEventBusIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";+ private static final String EVENTS_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/events/aws4_request";++ @BeforeAll+ static void configureRestAssured() {+ RestAssuredJsonUtils.configureAwsContentTypes();+ }++ private void createStack(String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private void assertStackStatus(String stackName, String status) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>" + status + "</StackStatus>"));+ }++ private void deleteStack(String stackName) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DeleteStack")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private void updateStack(String stackName, String template) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "UpdateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private String describeStackResources(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStackResources")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ }++ private String describeStackEvents(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStackEvents")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ }++ private String getTemplate(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "GetTemplate")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ }++ private static String eventBusOnlyTemplate(String busName, String description) {+ String nameProperty = busName == null ? "" : "\"Name\": \"" + busName + "\",";+ return """+ {+ "Resources": {+ "Bus": {+ "Type": "AWS::Events::EventBus",+ "Properties": {+ %s+ "Description": "%s"+ }+ }+ }+ }+ """.formatted(nameProperty, description);+ }++ private static String eventBusWithTagsTemplate(String busName, String tags) {+ return """+ {+ "Resources": {+ "Bus": {+ "Type": "AWS::Events::EventBus",+ "Properties": {+ "Name": "%s",+ "Description": "tagged bus",+ "Tags": %s+ }+ }+ }+ }+ """.formatted(busName, tags);+ }++ private static String eventBusWithPolicyTemplate(String busName, String statementId) {+ return """+ {+ "Resources": {+ "Bus": {+ "Type": "AWS::Events::EventBus",+ "Properties": {+ "Name": "%s",+ "Policy": {+ "Version": "2012-10-17",+ "Statement": [{+ "Sid": "%s",+ "Effect": "Allow",+ "Principal": "*",+ "Action": "events:PutEvents",+ "Resource": "*"+ }]+ }+ }+ }+ }+ }+ """.formatted(busName, statementId);+ }++ private void callEventBridge(String target, String body, int expectedStatus) {+ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", target)+ .body(body)+ .when()+ .post("/")+ .then()+ .statusCode(expectedStatus);+ }++ private static String eventBusAndRuleTemplate(String busName) {+ return """+ {+ "Resources": {+ "Bus": {+ "Type": "AWS::Events::EventBus",+ "Properties": { "Name": "%s" }+ },+ "Rule": {+ "Type": "AWS::Events::Rule",+ "Properties": {+ "EventBusName": { "Ref": "Bus" },+ "EventPattern": { "source": ["com.example.orders"] },+ "State": "ENABLED"+ }+ }+ },+ "Outputs": {+ "BusRef": { "Value": { "Ref": "Bus" } },+ "BusArn": { "Value": { "Fn::GetAtt": ["Bus", "Arn"] } }+ }+ }+ """.formatted(busName);+ }++ @Test+ void customEventBusIsRegisteredSoRuleReferencingItSucceeds() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "domain-events-" + suffix;+ String stackName = "eventbus-stack-" + suffix;++ // The stub-only behaviour failed the Rule with "EventBus not found" -> ROLLBACK.+ createStack(stackName, eventBusAndRuleTemplate(busName));+ assertStackStatus(stackName, "CREATE_COMPLETE");++ // Ref returns the bus NAME (not the ARN) per the AWS spec.+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<OutputKey>BusRef</OutputKey>"))+ .body(containsString("<OutputValue>" + busName + "</OutputValue>"))+ .body(containsString("event-bus/" + busName));++ // The bus is really registered with the EventBridge service (not just a stub).+ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", "AWSEvents.DescribeEventBus")+ .body("{\"Name\":\"" + busName + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString(busName));++ // Deleting the stack must remove the bus (and its rule) from EventBridge, not leak it: the+ // rule lives on the custom bus, so its cleanup must target that bus or the bus delete fails.+ deleteStack(stackName);+ awaitStackDeleted(stackName);+ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", "AWSEvents.DescribeEventBus")+ .body("{\"Name\":\"" + busName + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body(containsString("ResourceNotFoundException"));+ }++ private void awaitStackDeleted(String stackName) throws InterruptedException {+ String lastBody = null;+ for (int i = 0; i < 100; i++) {+ lastBody = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().extract().asString();+ if (lastBody.contains("does not exist")+ || lastBody.contains("<StackStatus>DELETE_COMPLETE</StackStatus>")) {+ return;+ }+ if (lastBody.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {+ throw new AssertionError("Stack " + stackName + " deletion failed: " + lastBody);+ }+ Thread.sleep(50);+ }+ throw new AssertionError(+ "Timed out waiting for stack " + stackName + " to be deleted. Last response: " + lastBody);+ }++ private void awaitStackStatus(String stackName, String expectedStatus) throws InterruptedException {+ String lastBody = null;+ for (int i = 0; i < 100; i++) {+ lastBody = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when().post("/").then().extract().asString();+ if (lastBody.contains("<StackStatus>" + expectedStatus + "</StackStatus>")) {+ return;+ }+ Thread.sleep(50);+ }+ throw new AssertionError("Timed out waiting for stack " + stackName + " to reach "+ + expectedStatus + ". Last response: " + lastBody);+ }++ @Test+ void eventBusWithExistingNameInAnotherStackFailsWithoutAdoption() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "collision-bus-" + suffix;+ String stackA = "eventbus-collision-a-" + suffix;+ String stackB = "eventbus-collision-b-" + suffix;++ createStack(stackA, eventBusAndRuleTemplate(busName));+ assertStackStatus(stackA, "CREATE_COMPLETE");++ // A second stack must not adopt a bus owned by the first stack.+ createStack(stackB, eventBusAndRuleTemplate(busName));+ assertStackStatus(stackB, "ROLLBACK_COMPLETE");+ String resources = describeStackResources(stackB);+ if (!resources.contains("<ResourceStatus>CREATE_FAILED</ResourceStatus>")) {+ throw new AssertionError("collision failure was not preserved: " + resources);+ }+ String events = describeStackEvents(stackB);+ if (!events.contains("EventBus already exists: " + busName)) {+ throw new AssertionError("collision reason was not preserved: " + events);+ }++ deleteStack(stackB);+ awaitStackDeleted(stackB);+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);++ deleteStack(stackA);+ awaitStackDeleted(stackA);++ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", "AWSEvents.DescribeEventBus")+ .body("{\"Name\":\"" + busName + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body(containsString("ResourceNotFoundException"));+ }++ @Test+ void sameStackNoOpUpdateReusesOwnedBusAndMutableDescriptionIsRejected()+ throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "update-bus-" + suffix;+ String stackName = "eventbus-update-" + suffix;+ String originalTemplate = eventBusOnlyTemplate(busName, "before");++ createStack(stackName, originalTemplate);+ assertStackStatus(stackName, "CREATE_COMPLETE");++ updateStack(stackName, originalTemplate);+ assertStackStatus(stackName, "UPDATE_COMPLETE");++ updateStack(stackName, eventBusOnlyTemplate(busName, "after"));+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");++ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", "AWSEvents.DescribeEventBus")+ .body("{\"Name\":\"" + busName + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("\"Description\":\"before\""));++ String activeTemplate = getTemplate(stackName);+ if (!activeTemplate.contains("before") || activeTemplate.contains("after")) {+ throw new AssertionError("failed update replaced the active template: " + activeTemplate);+ }++ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }++ @Test+ void explicitBusNameChangeFailsWithoutReplacingOwnedBus() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String originalName = "original-bus-" + suffix;+ String replacementName = "replacement-bus-" + suffix;+ String stackName = "eventbus-rename-" + suffix;++ createStack(stackName, eventBusOnlyTemplate(originalName, "original"));+ assertStackStatus(stackName, "CREATE_COMPLETE");++ updateStack(stackName, eventBusOnlyTemplate(replacementName, "replacement"));+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");++ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + originalName + "\"}", 200);+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + replacementName + "\"}", 400);+ String activeTemplate = getTemplate(stackName);+ if (!activeTemplate.contains(originalName) || activeTemplate.contains(replacementName)) {+ throw new AssertionError("failed update replaced the active template: " + activeTemplate);+ }++ updateStack(stackName, eventBusOnlyTemplate(null, "missing"));+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + originalName + "\"}", 200);++ deleteStack(stackName);+ awaitStackDeleted(stackName);+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + originalName + "\"}", 400);+ }++ @Test+ void eventBusNameIsRequired() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "eventbus-missing-name-" + suffix;++ createStack(stackName, eventBusOnlyTemplate(null, "missing"));+ assertStackStatus(stackName, "ROLLBACK_COMPLETE");+ String events = describeStackEvents(stackName);+ if (!events.contains("Name is required for AWS::Events::EventBus")) {+ throw new AssertionError("missing-name failure was not preserved: " + events);+ }+ }++ @ParameterizedTest+ @ValueSource(strings = {"default", "contains/slash", "contains space", "contains*star"})+ void invalidCustomEventBusNamesFailValidation(String busName) {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "eventbus-invalid-name-" + suffix;++ createStack(stackName, eventBusOnlyTemplate(busName, "invalid"));+ assertStackStatus(stackName, "ROLLBACK_COMPLETE");+ String events = describeStackEvents(stackName);+ if (!events.contains("Invalid custom event bus Name")) {+ throw new AssertionError("invalid-name failure was not preserved: " + events);+ }+ }++ @Test+ void eventBusNameAndDescriptionLengthLimitsAreValidated() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String longNameStack = "eventbus-long-name-" + suffix;+ createStack(longNameStack, eventBusOnlyTemplate("n".repeat(257), "invalid"));+ assertStackStatus(longNameStack, "ROLLBACK_COMPLETE");+ if (!describeStackEvents(longNameStack).contains("Invalid custom event bus Name")) {+ throw new AssertionError("long-name validation failure was not preserved");+ }++ String longDescriptionStack = "eventbus-long-description-" + suffix;+ createStack(longDescriptionStack,+ eventBusOnlyTemplate("valid-bus-" + suffix, "d".repeat(513)));+ assertStackStatus(longDescriptionStack, "ROLLBACK_COMPLETE");+ if (!describeStackEvents(longDescriptionStack).contains(+ "Description must not exceed 512 characters")) {+ throw new AssertionError("long-description validation failure was not preserved");+ }+ }++ // "Policy" is deliberately absent: an inline resource policy is supported (see+ // provisionEventBridgeEventBus), so rejecting it would regress templates main supports today.+ @ParameterizedTest+ @ValueSource(strings = {+ "EventSourceName", "KmsKeyIdentifier", "DeadLetterConfig", "LogConfig"+ })+ void unsupportedEventBusPropertiesFailInsteadOfBeingIgnored(String propertyName) {+ String suffix = Long.toString(System.nanoTime(), 36);+ String stackName = "eventbus-unsupported-property-" + suffix;+ String template = """+ {+ "Resources": {+ "Bus": {+ "Type": "AWS::Events::EventBus",+ "Properties": {+ "Name": "unsupported-property-%s",+ "%s": "unsupported"+ }+ }+ }+ }+ """.formatted(suffix, propertyName);++ createStack(stackName, template);+ assertStackStatus(stackName, "ROLLBACK_COMPLETE");+ String events = describeStackEvents(stackName);+ if (!events.contains("Unsupported AWS::Events::EventBus properties: " + propertyName)) {+ throw new AssertionError("unsupported-property failure was not preserved: " + events);+ }+ }++ @Test+ void mutableEventBusTagUpdateRollsBackWithoutChangingTags() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "tagged-bus-" + suffix;+ String stackName = "eventbus-tags-" + suffix;++ createStack(stackName, eventBusWithTagsTemplate(busName, """+ [{"Key":"keep","Value":"before"},{"Key":"remove","Value":"old"}]+ """));+ assertStackStatus(stackName, "CREATE_COMPLETE");++ String busArn = "arn:aws:events:us-east-1:000000000000:event-bus/" + busName;+ callEventBridge("AWSEvents.TagResource", """+ {"ResourceARN":"%s","Tags":[{"Key":"external","Value":"preserve"}]}+ """.formatted(busArn), 200);++ updateStack(stackName, eventBusWithTagsTemplate(busName, """+ [{"Key":"keep","Value":"after"},{"Key":"add","Value":"new"}]+ """));+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");++ String tags = given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", "AWSEvents.ListTagsForResource")+ .body("{\"ResourceARN\":\"" + busArn + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();+ if (!tags.contains("\"Key\":\"keep\",\"Value\":\"before\"")+ || !tags.contains("\"Key\":\"remove\",\"Value\":\"old\"")+ || !tags.contains("\"Key\":\"external\",\"Value\":\"preserve\"")+ || tags.contains("\"Key\":\"add\"")+ || tags.contains("\"Value\":\"after\"")) {+ throw new AssertionError("failed update changed event bus tags: " + tags);+ }++ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }++ @Test+ void mutableEventBusPolicyUpdateRollsBackWithoutChangingPolicy() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "policy-bus-" + suffix;+ String stackName = "eventbus-policy-" + suffix;+ String originalTemplate = eventBusWithPolicyTemplate(busName, "Before");++ createStack(stackName, originalTemplate);+ assertStackStatus(stackName, "CREATE_COMPLETE");++ updateStack(stackName, originalTemplate);+ assertStackStatus(stackName, "UPDATE_COMPLETE");++ updateStack(stackName, eventBusWithPolicyTemplate(busName, "After"));+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");++ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", "AWSEvents.DescribeEventBus")+ .body("{\"Name\":\"" + busName + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body("Policy", containsString("Before"));++ String activeTemplate = getTemplate(stackName);+ if (!activeTemplate.contains("Before") || activeTemplate.contains("After")) {+ throw new AssertionError("failed policy update replaced the active template: " + activeTemplate);+ }++ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }++ @Test+ void invalidEventBusTagsFailValidation() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String[][] cases = {+ {"reserved-lower", """+ [{"Key":"aws:reserved","Value":"value"}]+ """, "reserved aws: prefix"},+ {"reserved-upper", """+ [{"Key":"AWS:reserved","Value":"value"}]+ """, "reserved aws: prefix"},+ {"invalid-key", """+ [{"Key":"bad*key","Value":"value"}]+ """, "Key contains unsupported characters"},+ {"invalid-value", """+ [{"Key":"key","Value":"bad*value"}]+ """, "Value contains unsupported characters"},+ {"duplicate-key", """+ [{"Key":"duplicate","Value":"one"},{"Key":"duplicate","Value":"two"}]+ """, "Duplicate event bus tag Key"}+ };++ for (String[] testCase : cases) {+ String stackName = "eventbus-invalid-tag-" + testCase[0] + "-" + suffix;+ createStack(stackName,+ eventBusWithTagsTemplate("invalid-tag-" + testCase[0] + "-" + suffix,+ testCase[1]));+ assertStackStatus(stackName, "ROLLBACK_COMPLETE");+ String events = describeStackEvents(stackName);+ if (!events.contains(testCase[2])) {+ throw new AssertionError(+ testCase[0] + " tag failure was not preserved: " + events);+ }+ }+ }++ @Test+ void eventBusTagCountAndLengthLimitsAreValidated() {+ String suffix = Long.toString(System.nanoTime(), 36);+ StringBuilder tooManyTags = new StringBuilder("[");+ for (int i = 0; i < 51; i++) {+ if (i > 0) {+ tooManyTags.append(',');+ }+ tooManyTags.append("""+ {"Key":"key-%d","Value":"value"}+ """.formatted(i).strip());+ }+ tooManyTags.append(']');++ String[][] cases = {+ {"too-many", tooManyTags.toString(), "supports at most 50 tags"},+ {"long-key", """+ [{"Key":"%s","Value":"value"}]+ """.formatted("k".repeat(129)), "Key must contain 1 to 128 characters"},+ {"long-value", """+ [{"Key":"key","Value":"%s"}]+ """.formatted("v".repeat(257)), "Value must contain at most 256 characters"}+ };++ for (String[] testCase : cases) {+ String stackName = "eventbus-tag-limit-" + testCase[0] + "-" + suffix;+ createStack(stackName,+ eventBusWithTagsTemplate("tag-limit-" + testCase[0] + "-" + suffix,+ testCase[1]));+ assertStackStatus(stackName, "ROLLBACK_COMPLETE");+ String events = describeStackEvents(stackName);+ if (!events.contains(testCase[2])) {+ throw new AssertionError(+ testCase[0] + " tag failure was not preserved: " + events);+ }+ }+ }++ @Test+ void updateDoesNotAdoptBusRecreatedUnderSameName() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "recreated-bus-" + suffix;+ String stackName = "eventbus-recreated-" + suffix;+ String template = eventBusOnlyTemplate(busName, "owned");++ createStack(stackName, template);+ assertStackStatus(stackName, "CREATE_COMPLETE");+ callEventBridge("AWSEvents.DeleteEventBus", "{\"Name\":\"" + busName + "\"}", 200);+ Thread.sleep(2);+ callEventBridge("AWSEvents.CreateEventBus",+ "{\"Name\":\"" + busName + "\",\"Description\":\"external\"}", 200);++ updateStack(stackName, template);+ assertStackStatus(stackName, "UPDATE_ROLLBACK_COMPLETE");+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);++ deleteStack(stackName);+ awaitStackStatus(stackName, "DELETE_FAILED");+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);++ callEventBridge("AWSEvents.DeleteEventBus", "{\"Name\":\"" + busName + "\"}", 200);+ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }++ @Test+ void eventBusDeleteFailurePropagatesAndRetrySucceeds() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "blocked-delete-bus-" + suffix;+ String ruleName = "external-rule-" + suffix;+ String stackName = "eventbus-blocked-delete-" + suffix;++ createStack(stackName, eventBusOnlyTemplate(busName, "blocked"));+ assertStackStatus(stackName, "CREATE_COMPLETE");+ callEventBridge("AWSEvents.PutRule", """+ {"Name":"%s","EventBusName":"%s","EventPattern":"{\\\"source\\\":[\\\"external\\\"]}"}+ """.formatted(ruleName, busName), 200);++ deleteStack(stackName);+ awaitStackStatus(stackName, "DELETE_FAILED");+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200);++ callEventBridge("AWSEvents.DeleteRule",+ "{\"Name\":\"" + ruleName + "\",\"EventBusName\":\"" + busName + "\"}", 200);+ deleteStack(stackName);+ awaitStackDeleted(stackName);+ callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 400);+ }++ @Test+ void deletingStackTreatsAlreadyAbsentBusAsSuccess() throws InterruptedException {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "already-gone-bus-" + suffix;+ String stackName = "eventbus-already-gone-" + suffix;++ createStack(stackName, eventBusOnlyTemplate(busName, "gone"));+ assertStackStatus(stackName, "CREATE_COMPLETE");+ callEventBridge("AWSEvents.DeleteEventBus", "{\"Name\":\"" + busName + "\"}", 200);++ deleteStack(stackName);+ awaitStackDeleted(stackName);+ }++ @Test+ void failedStackCreateRollsBackRuleAndCustomEventBus() {+ String suffix = Long.toString(System.nanoTime(), 36);+ String busName = "rollback-bus-" + suffix;+ String stackName = "eventbus-rollback-" + suffix;+ String template = """+ {+ "Resources": {+ "Bus": {+ "Type": "AWS::Events::EventBus",+ "Properties": { "Name": "%s" }+ },+ "Rule": {+ "Type": "AWS::Events::Rule",+ "DependsOn": "Bus",+ "Properties": {+ "EventBusName": { "Ref": "Bus" },+ "EventPattern": { "source": ["com.example.rollback"] },+ "State": "ENABLED"+ }+ },+ "BadSecret": {+ "Type": "AWS::SecretsManager::Secret",+ "DependsOn": "Rule",+ "Properties": {+ "Name": "rollback-secret-%s",+ "SecretString": "explicit",+ "GenerateSecretString": { "PasswordLength": 32 }+ }+ }+ }+ }+ """.formatted(busName, suffix);++ createStack(stackName, template);+ assertStackStatus(stackName, "ROLLBACK_COMPLETE");++ given()+ .contentType("application/x-amz-json-1.1")+ .header("Authorization", EVENTS_AUTH)+ .header("X-Amz-Target", "AWSEvents.DescribeEventBus")+ .body("{\"Name\":\"" + busName + "\"}")+ .when()+ .post("/")+ .then()+ .statusCode(400)+ .body(containsString("ResourceNotFoundException"));+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.javanew file mode 100644index 0000000000..74692f11b4--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusDeleteOwnershipTest.java@@ -0,0 +1,132 @@+package io.github.hectorvent.floci.services.cloudformation;++import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+import io.github.hectorvent.floci.services.eventbridge.model.EventBus;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Instant;+import java.util.List;++import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertThrows;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.never;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * Deleting an {@code AWS::Events::EventBus} is guarded by the created-time recorded at provision+ * time, so a bus that was destroyed and recreated under the same name out of band is not deleted+ * out from under whoever owns it now.+ */+class EventBusDeleteOwnershipTest {++ private static final String REGION = "us-east-1";+ private static final String BUS = "orders-bus";+ private static final String CREATED_TIME_ATTR = "FlociEventBusCreatedTime";++ private EventBridgeService eventBridgeService;+ private CloudFormationResourceProvisioner provisioner;++ @BeforeEach+ void setUp() {+ eventBridgeService = mock(EventBridgeService.class);+ provisioner = new CloudFormationResourceProvisioner(+ null, null, null, null, null,+ null, null, null, null, eventBridgeService,+ null, null, null, null, null, null,+ new ObjectMapper(),+ null, null, null, null, null, null, null,+ null, null, null, null, null, null, null,+ null,+ new CloudFormationResourceRegistry(List.of()));+ }++ @Test+ void busWhoseCreatedTimeStillMatchesIsDeleted() {+ Instant createdTime = Instant.parse("2026-01-01T00:00:00Z");+ when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(bus(createdTime));++ assertDoesNotThrow(() -> provisioner.delete(resource(createdTime.toString()), REGION));++ verify(eventBridgeService).deleteEventBus(BUS, REGION);+ }++ @Test+ void busRecreatedUnderTheSameNameIsNotDeleted() {+ when(eventBridgeService.describeEventBus(BUS, REGION))+ .thenReturn(bus(Instant.parse("2026-02-02T00:00:00Z")));++ AwsException e = assertThrows(AwsException.class,+ () -> provisioner.delete(resource("2026-01-01T00:00:00Z"), REGION));++ assertTrue(e.getMessage().contains("ownership changed"), e.getMessage());+ verify(eventBridgeService, never()).deleteEventBus(BUS, REGION);+ }++ /**+ * Stacks provisioned before the created-time attribute existed are restored from+ * cloudformation-stacks.json without it. Treating "not tracked" as "ownership changed" would+ * leave every such stack permanently in DELETE_FAILED after a Floci upgrade.+ */+ @Test+ void busProvisionedBeforeOwnershipTrackingIsStillDeleted() {+ when(eventBridgeService.describeEventBus(BUS, REGION))+ .thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));++ assertDoesNotThrow(() -> provisioner.delete(resource(null), REGION));++ verify(eventBridgeService).deleteEventBus(BUS, REGION);+ }++ @Test+ void alreadyDeletedBusIsTreatedAsDeleted() {+ when(eventBridgeService.describeEventBus(BUS, REGION))+ .thenThrow(new AwsException("ResourceNotFoundException", "gone", 400));++ assertDoesNotThrow(() -> provisioner.delete(resource(null), REGION));++ verify(eventBridgeService, never()).deleteEventBus(BUS, REGION);+ }++ @Test+ void unexpectedRuleDeletionFailureIsNotReportedAsSuccess() {+ StackResource rule = new StackResource();+ rule.setLogicalId("OrdersRule");+ rule.setResourceType("AWS::Events::Rule");+ rule.setPhysicalId("orders-rule");+ rule.getAttributes().put("EventBusName", BUS);+ when(eventBridgeService.listTargetsByRule("orders-rule", BUS, REGION))+ .thenThrow(new IllegalStateException("storage unavailable"));++ AwsException error = assertThrows(AwsException.class,+ () -> provisioner.delete(rule, REGION));++ assertEquals("InternalFailure", error.getErrorCode());+ assertTrue(error.getMessage().contains("storage unavailable"), error.getMessage());+ verify(eventBridgeService, never()).deleteRule("orders-rule", BUS, REGION);+ }++ private StackResource resource(String createdTimeAttr) {+ StackResource r = new StackResource();+ r.setLogicalId("OrdersBus");+ r.setResourceType("AWS::Events::EventBus");+ r.setPhysicalId(BUS);+ if (createdTimeAttr != null) {+ r.getAttributes().put(CREATED_TIME_ATTR, createdTimeAttr);+ }+ return r;+ }++ private EventBus bus(Instant createdTime) {+ return new EventBus(BUS, "arn:aws:events:" + REGION + ":000000000000:event-bus/" + BUS,+ null, createdTime);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.javanew file mode 100644index 0000000000..db8d88ccd5--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/EventBusProvisionOwnershipTest.java@@ -0,0 +1,222 @@+package io.github.hectorvent.floci.services.cloudformation;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import com.fasterxml.jackson.databind.node.ObjectNode;+import io.github.hectorvent.floci.core.common.AwsException;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudFormationResourceRegistry;+import io.github.hectorvent.floci.services.eventbridge.EventBridgeService;+import io.github.hectorvent.floci.services.eventbridge.model.EventBus;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;++import java.time.Instant;+import java.util.List;+import java.util.Map;+import java.util.function.Function;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;+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;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/**+ * Provision-side ownership behaviour for {@code AWS::Events::EventBus}. The delete side is covered+ * by {@link EventBusDeleteOwnershipTest}; both have to agree about what a missing created-time+ * attribute means, or an upgrade wedges the stack in one direction or the other.+ *+ * <p>Note {@code provision} reports failure by returning a {@code CREATE_FAILED} resource rather+ * than throwing, so these assert on status.+ */+class EventBusProvisionOwnershipTest {++ private static final String REGION = "us-east-1";+ private static final String BUS = "orders-bus";+ private static final String CREATED_TIME_ATTR = "FlociEventBusCreatedTime";+ private static final String MANAGED_TAG_KEYS_ATTR = "FlociEventBusManagedTagKeys";+ private static final String MANAGED_POLICY_ATTR = "FlociEventBusManagedPolicy";+ private static final String ROLLBACK_OWNED_ATTR = "__FlociRollbackOwned";+ private static final ObjectMapper MAPPER = new ObjectMapper();++ private EventBridgeService eventBridgeService;+ private CloudFormationResourceProvisioner provisioner;++ @BeforeEach+ void setUp() {+ eventBridgeService = mock(EventBridgeService.class);+ provisioner = new CloudFormationResourceProvisioner(+ null, null, null, null, null,+ null, null, null, null, eventBridgeService,+ null, null, null, null, null, null,+ MAPPER,+ null, null, null, null, null, null, null,+ null, null, null, null, null, null, null,+ null,+ new CloudFormationResourceRegistry(List.of()));+ }++ /**+ * A stack provisioned before {@code FlociEventBusCreatedTime} existed is restored without it.+ * Treating that as "ownership changed" made the first UpdateStack after an upgrade fail, leaving+ * the stack stuck for every subsequent update — including no-op ones.+ */+ @Test+ void updateOfBusProvisionedBeforeOwnershipTrackingAdoptsItInsteadOfFailing() {+ when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))+ .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));+ when(eventBridgeService.describeEventBus(BUS, REGION))+ .thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));++ StackResource r = provisionExisting(Map.of());++ assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());+ assertEquals(BUS, r.getPhysicalId());+ // and it starts tracking ownership from here on+ assertEquals("2026-01-01T00:00:00Z", r.getAttributes().get(CREATED_TIME_ATTR));+ }++ @Test+ void updateOfTaggedBusProvisionedBeforeTagTrackingAdoptsItInsteadOfFailing() {+ when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))+ .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));+ EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z"));+ existingBus.setTags(Map.of("environment", "test"));+ when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus);+ JsonNode properties = props(false);+ ((ObjectNode) properties).putArray("Tags")+ .addObject()+ .put("Key", "environment")+ .put("Value", "test");++ StackResource r = provisionExisting(Map.of(), properties);++ assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());+ assertEquals("[\"environment\"]", r.getAttributes().get(MANAGED_TAG_KEYS_ATTR));+ }++ @Test+ void updateOfBusProvisionedBeforePolicyTrackingAdoptsUnchangedPolicyWithoutReapplyingIt()+ throws Exception {+ when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))+ .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));+ EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z"));+ existingBus.setPolicy("{\"Version\":\"2012-10-17\"}");+ when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus);++ StackResource r = provisionExisting(Map.of(), props(true));++ assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());+ assertEquals(+ MAPPER.readTree("{\"Version\":\"2012-10-17\"}"),+ MAPPER.readTree(r.getAttributes().get(MANAGED_POLICY_ATTR)));+ verify(eventBridgeService, never())+ .putPermission(anyString(), any(), any(), any(), any(), anyString(), anyString());+ }++ @Test+ void changedTrackedPolicyFailsWithoutMutatingTheOwnedBus() {+ when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))+ .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));+ EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z"));+ existingBus.setPolicy("{\"Version\":\"2008-10-17\"}");+ when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus);++ StackResource r = provisionExisting(+ Map.of(MANAGED_POLICY_ATTR, "{\"Version\":\"2008-10-17\"}"),+ props(true));++ assertEquals("CREATE_FAILED", r.getStatus());+ assertEquals(+ "Updating AWS::Events::EventBus Description, Tags, or Policy is not supported "+ + "until transactional rollback is available.",+ r.getStatusReason());+ verify(eventBridgeService, never())+ .putPermission(anyString(), any(), any(), any(), any(), anyString(), anyString());+ }++ @Test+ void updateOfBusRecreatedOutOfBandStillFails() {+ when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))+ .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));+ when(eventBridgeService.describeEventBus(BUS, REGION))+ .thenReturn(bus(Instant.parse("2026-02-02T00:00:00Z")));++ StackResource r = provisionExisting(Map.of(CREATED_TIME_ATTR, "2026-01-01T00:00:00Z"));++ assertEquals("CREATE_FAILED", r.getStatus());+ assertNull(r.getAttributes().get(ROLLBACK_OWNED_ATTR),+ "a bus this stack no longer owns must not be deleted by rollback");+ }++ /**+ * rollbackCreatedResources skips any resource whose physicalId is still null, so identity has to+ * be recorded before the policy call — otherwise a malformed Policy leaves a live bus that+ * rollback cannot find, and it leaks permanently.+ */+ @Test+ void busIsRollbackDeletableWhenThePolicyCallFails() {+ when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))+ .thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));+ doThrow(new AwsException("MalformedPolicyDocumentException", "bad policy", 400))+ .when(eventBridgeService)+ .putPermission(anyString(), any(), any(), any(), any(), anyString(), anyString());++ StackResource r = provisioner.provision("OrdersBus", "AWS::Events::EventBus", props(true),+ engine(), REGION, "000000000000", "my-stack", null, Map.of());++ assertEquals("CREATE_FAILED", r.getStatus());+ assertEquals(BUS, r.getPhysicalId(), "physicalId must be recorded before the policy call");+ assertEquals("true", r.getAttributes().get(ROLLBACK_OWNED_ATTR));+ }++ @Test+ void adoptedBusIsNotMarkedRollbackOwned() {+ when(eventBridgeService.createEventBus(eq(BUS), any(), any(), eq(REGION)))+ .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400));+ when(eventBridgeService.describeEventBus(BUS, REGION))+ .thenReturn(bus(Instant.parse("2026-01-01T00:00:00Z")));++ StackResource r = provisionExisting(Map.of());++ assertEquals("CREATE_COMPLETE", r.getStatus(), r.getStatusReason());+ assertNull(r.getAttributes().get(ROLLBACK_OWNED_ATTR),+ "a bus this stack did not create must not be deleted by rollback");+ }++ private StackResource provisionExisting(Map<String, String> existingAttributes) {+ return provisionExisting(existingAttributes, props(false));+ }++ private StackResource provisionExisting(Map<String, String> existingAttributes,+ JsonNode properties) {+ return provisioner.provision("OrdersBus", "AWS::Events::EventBus", properties,+ engine(), REGION, "000000000000", "my-stack", BUS, existingAttributes);+ }++ private JsonNode props(boolean withPolicy) {+ var node = MAPPER.createObjectNode();+ node.put("Name", BUS);+ if (withPolicy) {+ node.set("Policy", MAPPER.createObjectNode().put("Version", "2012-10-17"));+ }+ return node;+ }++ private CloudFormationTemplateEngine engine() {+ return new CloudFormationTemplateEngine("000000000000", REGION, "my-stack",+ "stack/id", Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), MAPPER,+ (Function<String, String>) name -> null);+ }++ private EventBus bus(Instant createdTime) {+ return new EventBus(BUS, "arn:aws:events:" + REGION + ":000000000000:event-bus/" + BUS,+ null, createdTime);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.javaindex 681dd90383..16712cfd80 100644--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeServiceTest.java@@ -12,6 +12,8 @@ import io.github.hectorvent.floci.services.eventbridge.model.Target;import io.github.hectorvent.floci.services.resourcegroupstagging.ResourceGroupsTaggingService;import org.junit.jupiter.api.BeforeEach;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import java.util.List;import java.util.Map;@@ -77,6 +79,49 @@ class EventBridgeServiceTest {service.createEventBus("", null, null, REGION));}+ @ParameterizedTest+ @ValueSource(strings = {"default", "contains/slash", "contains space", "contains*star"})+ void createEventBusRejectsInvalidCustomNames(String name) {+ AwsException error = assertThrows(AwsException.class, () ->+ service.createEventBus(name, null, null, REGION));+ assertEquals("ValidationException", error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ }++ @Test+ void createEventBusRejectsLongNameAndDescription() {+ assertThrows(AwsException.class, () ->+ service.createEventBus("n".repeat(257), null, null, REGION));+ assertThrows(AwsException.class, () ->+ service.createEventBus("valid-name", "d".repeat(513), null, REGION));+ }++ @Test+ void updateEventBusRejectsLongDescription() {+ service.createEventBus("my-bus", null, null, REGION);+ assertThrows(AwsException.class, () ->+ service.updateEventBus(+ "my-bus", "d".repeat(513), null, null, null, REGION));+ }++ @ParameterizedTest+ @ValueSource(strings = {"", "contains space", "contains*star"})+ void updateEventBusRejectsInvalidExplicitNames(String name) {+ AwsException error = assertThrows(AwsException.class, () ->+ service.updateEventBus(name, "description", null, null, null, REGION));+ assertEquals("ValidationException", error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ }++ @Test+ void updateEventBusRejectsLongExplicitName() {+ AwsException error = assertThrows(AwsException.class, () ->+ service.updateEventBus(+ "n".repeat(257), "description", null, null, null, REGION));+ assertEquals("ValidationException", error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ }+@Testvoid deleteEventBus() {service.createEventBus("my-bus", null, null, REGION);@@ -92,6 +137,28 @@ class EventBridgeServiceTest {service.deleteEventBus("default", REGION));}+ @Test+ void deleteMissingEventBusIsIdempotent() {+ assertDoesNotThrow(() -> service.deleteEventBus("missing-bus", REGION));+ }++ @ParameterizedTest+ @ValueSource(strings = {"contains space", "contains*star"})+ void deleteEventBusRejectsInvalidNames(String name) {+ AwsException error = assertThrows(+ AwsException.class, () -> service.deleteEventBus(name, REGION));+ assertEquals("ValidationException", error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ }++ @Test+ void deleteEventBusRejectsLongName() {+ AwsException error = assertThrows(+ AwsException.class, () -> service.deleteEventBus("n".repeat(257), REGION));+ assertEquals("ValidationException", error.getErrorCode());+ assertEquals(400, error.getHttpStatus());+ }+@Testvoid deleteEventBusWithRulesThrows() {service.createEventBus("my-bus", null, null, REGION);diff --git a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeUpdateEventBusIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeUpdateEventBusIntegrationTest.javaindex 4eb0dea22b..c9986287bc 100644--- a/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeUpdateEventBusIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/eventbridge/EventBridgeUpdateEventBusIntegrationTest.java@@ -4,6 +4,8 @@ import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;import io.quarkus.test.junit.QuarkusTest;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;+import org.junit.jupiter.params.ParameterizedTest;+import org.junit.jupiter.params.provider.ValueSource;import static io.restassured.RestAssured.given;import static org.hamcrest.Matchers.containsString;@@ -53,6 +55,24 @@ class EventBridgeUpdateEventBusIntegrationTest {.body("Description", equalTo("hello world"));}+ @Test+ void emptyDescriptionClearsIt() {+ String bus = "update-test-bus-clear-description";+ createBus(bus);++ given().contentType(CT).header("X-Amz-Target", UPDATE)+ .body("{\"Name\":\"" + bus + "\",\"Description\":\"set\"}")+ .when().post("/")+ .then().statusCode(200)+ .body("Description", equalTo("set"));++ given().contentType(CT).header("X-Amz-Target", UPDATE)+ .body("{\"Name\":\"" + bus + "\",\"Description\":\"\"}")+ .when().post("/")+ .then().statusCode(200)+ .body("Description", equalTo(""));+ }+@Testvoid updateDefaultBus_nameOmitted() {given().contentType(CT).header("X-Amz-Target", UPDATE)@@ -91,14 +111,33 @@ class EventBridgeUpdateEventBusIntegrationTest {}@Test- void updateNonExistentCustomBus_returns404() {+ void updateNonExistentCustomBusReturnsAws400() {given().contentType(CT).header("X-Amz-Target", UPDATE).body("{\"Name\":\"this-bus-was-never-created\",\"Description\":\"x\"}").when().post("/")- .then().statusCode(404)+ .then().statusCode(400).body("__type", containsString("ResourceNotFoundException"));}+ @ParameterizedTest+ @ValueSource(strings = {"", "contains space", "contains*star"})+ void updateRejectsInvalidExplicitName(String name) {+ given().contentType(CT).header("X-Amz-Target", UPDATE)+ .body("{\"Name\":\"" + name + "\",\"Description\":\"x\"}")+ .when().post("/")+ .then().statusCode(400)+ .body("__type", containsString("ValidationException"));+ }++ @Test+ void updateRejectsNameLongerThan256Characters() {+ given().contentType(CT).header("X-Amz-Target", UPDATE)+ .body("{\"Name\":\"" + "n".repeat(257) + "\",\"Description\":\"x\"}")+ .when().post("/")+ .then().statusCode(400)+ .body("__type", containsString("ValidationException"));+ }+@Testvoid updateKmsKeyIdentifier() {String bus = "update-test-bus-kms";