diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 7e63aa3be5..43adf84822 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -312,9 +312,13 @@ The current implementation is limited to custom buses with the `Name`, `Descript `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. +available. `Policy` is applied when the bus is created. On `UpdateStack` the template's `Tags` are +applied to the same bus in place: a key the stack recorded setting and the new template drops is +removed, and a tag added outside the stack is kept, as on AWS. A bus created before Floci recorded +its tag keys keeps a key an older template dropped. When a later resource fails the update, the +tags the bus had before it are put back. Changing `Description` 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. ## EventBridge archives diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java index 3dc300de61..269b796914 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/CfnRollback.java @@ -3,10 +3,17 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.services.cloudformation.model.StackResource; import org.jboss.logging.Logger; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeSet; import java.util.function.BiConsumer; /** @@ -151,6 +158,13 @@ public final class CfnRollback { */ public static final String API_DESTINATION_UPDATE_SNAPSHOT_ATTR = "__FlociApiDestinationUpdateSnapshot"; + /** + * Holds the tags an EventBridge event bus carried, for the keys an in-place update manages, + * and the managed tag keys it was tracking, so a failed stack update can put them back. Written + * by {@code EventsCfnProvisioner} before its tag calls and spent by its {@code rollbackUpdate}. + */ + public static final String EVENT_BUS_UPDATE_SNAPSHOT_ATTR = "__FlociEventBusUpdateSnapshot"; + /** * Holds the name, description and endpoint configuration a REST API had before an in-place * update patched them, so a failed stack update can put them back, and a {@code body} flag set @@ -478,6 +492,38 @@ public final class CfnRollback { return value == null || value.isNull() ? null : value.asText(); } + /** + * Records the tags an in-place update is about to reconcile under {@code tagKeys} and + * {@code tags} of {@code snapshot}: every key it manages, and the value {@code current} holds + * for it. A managed key the resource did not carry is listed without a value, so the rollback + * removes it. {@link #snapshotTagKeys} and {@link #snapshotTags} read them back. + */ + public static void putTagSnapshot(ObjectNode snapshot, Collection managedKeys, + Map current) { + ArrayNode tagKeys = snapshot.putArray("tagKeys"); + ObjectNode tags = snapshot.putObject("tags"); + for (String key : new TreeSet<>(managedKeys)) { + tagKeys.add(key); + if (current.containsKey(key)) { + tags.put(key, current.get(key)); + } + } + } + + /** The tag keys {@link #putTagSnapshot} recorded as managed by the update. */ + public static List snapshotTagKeys(JsonNode snapshot) { + List keys = new ArrayList<>(); + snapshot.path("tagKeys").forEach(key -> keys.add(key.asText())); + return keys; + } + + /** The tags {@link #putTagSnapshot} recorded, which are what the rollback puts back. */ + public static Map snapshotTags(JsonNode snapshot) { + Map tags = new LinkedHashMap<>(); + snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().textValue())); + return tags; + } + /** * Undoes an update {@link #recordCreatedByUpdate} recorded: deletes the created entity with * {@code deleteInRegion}, which takes its id and region, names the prior id again as the physical diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java index 9561719554..dcd8dc3a5a 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/EventsCfnProvisioner.java @@ -25,6 +25,7 @@ import jakarta.inject.Inject; import org.jboss.logging.Logger; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; @@ -306,6 +307,17 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { } } + /** + * An event bus update that failed after its tag snapshot may already have changed tags, so the + * engine keeps that attempt for {@link #rollbackUpdate} instead of putting the previous resource + * back over it. A failure before the snapshot changed nothing and is left to the engine. + */ + @Override + public boolean retainsFailedUpdateState(StackResource resource) { + return "AWS::Events::EventBus".equals(resource.getResourceType()) + && resource.getAttributes().containsKey(CfnRollback.EVENT_BUS_UPDATE_SNAPSHOT_ATTR); + } + /** * Puts the rule's targets back to what the snapshot holds and spends it. Exact rather than * additive: a target the failed update added is removed, and every snapshotted target is put @@ -323,6 +335,9 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { if ("AWS::Events::ApiDestination".equals(resource.getResourceType())) { return rollbackApiDestinationUpdate(resource); } + if ("AWS::Events::EventBus".equals(resource.getResourceType())) { + return rollbackEventBusUpdate(resource); + } String rawSnapshot = resource.getAttributes().get(CfnRollback.RULE_TARGETS_SNAPSHOT_ATTR); if (rawSnapshot == null) { return false; @@ -386,6 +401,8 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { * (not the ARN), so the physical id is the name; {@code Fn::GetAtt "Arn"} exposes the ARN. */ private void provisionEventBus(StackResource r, JsonNode props, ProvisionContext ctx) { + // A snapshot describes the update in flight; one an earlier update left behind is stale + r.getAttributes().remove(CfnRollback.EVENT_BUS_UPDATE_SNAPSHOT_ATTR); validateEventBusProperties(props); String existingBusName = ctx.isUpdate() ? ctx.priorPhysicalId() : null; String busName = ctx.resolveOptional(props, "Name"); @@ -424,7 +441,8 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { r.getAttributes().remove(CfnRollback.ROLLBACK_OWNED_ATTR); throw e; } - validateEventBusMutablePropertiesUnchanged(r, bus, description, tags, policy); + validateEventBusMutablePropertiesUnchanged(r, bus, description, policy); + updateEventBusTags(r, bus, tags, ctx.region()); } // Record identity before applying the policy: rollbackCreatedResources skips any resource @@ -530,27 +548,11 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { } private void validateEventBusMutablePropertiesUnchanged( - StackResource resource, EventBus bus, String requestedDescription, - Map requestedTags, JsonNode requestedPolicy) { + StackResource resource, EventBus bus, String requestedDescription, 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 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") @@ -594,10 +596,68 @@ public class EventsCfnProvisioner implements CfnResourceProvisioner { private AwsException unsupportedEventBusMutableUpdate() { return new AwsException("ValidationError", - "Updating AWS::Events::EventBus Description, Tags, or Policy is not supported " + "Updating AWS::Events::EventBus Description or Policy is not supported " + "until transactional rollback is available.", 400); } + /** + * Drives the tags of the bus the stack already owns to the template's, as AWS's update handler + * does: a key the stack set and the template dropped is untagged, and a tag added outside the + * stack stays. A bus provisioned before its keys were tracked has none to drop. The tags of the + * keys this touches are recorded first, so {@link #rollbackUpdate} can put them back. + */ + private void updateEventBusTags(StackResource r, EventBus bus, Map tags, String region) { + Set managedKeys = eventBusManagedTagKeys(r); + Set touchedKeys = new HashSet<>(managedKeys); + touchedKeys.addAll(tags.keySet()); + ObjectNode snapshot = MAPPER.createObjectNode(); + snapshot.put("region", region); + snapshot.put("arn", bus.getArn()); + snapshot.put("managedTagKeys", r.getAttributes().get(EVENT_BUS_MANAGED_TAG_KEYS_ATTR)); + CfnRollback.putTagSnapshot(snapshot, touchedKeys, bus.getTags()); + r.getAttributes().put(CfnRollback.EVENT_BUS_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); + reconcileEventBusTags(bus.getArn(), managedKeys, tags, region); + } + + /** + * Puts the managed tags and tracked keys the bus had before the failed update back, and spends + * the snapshot. A bus this update did not reach carries no snapshot, which is the false that + * keeps the stack reporting that rollback is not implemented. + */ + private boolean rollbackEventBusUpdate(StackResource resource) { + JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.EVENT_BUS_UPDATE_SNAPSHOT_ATTR); + if (snapshot == null) { + return false; + } + reconcileEventBusTags(snapshot.path("arn").asText(), CfnRollback.snapshotTagKeys(snapshot), + CfnRollback.snapshotTags(snapshot), snapshot.path("region").asText()); + String managedTagKeys = snapshotText(snapshot, "managedTagKeys"); + if (managedTagKeys == null) { + resource.getAttributes().remove(EVENT_BUS_MANAGED_TAG_KEYS_ATTR); + } else { + resource.getAttributes().put(EVENT_BUS_MANAGED_TAG_KEYS_ATTR, managedTagKeys); + } + resource.getAttributes().remove(CfnRollback.EVENT_BUS_UPDATE_SNAPSHOT_ATTR); + return true; + } + + /** + * Applies {@code desired} and removes the {@code managedKeys} it does not hold, so a tag added + * outside the stack stays. + */ + private void reconcileEventBusTags(String arn, Collection managedKeys, Map desired, + String region) { + List dropped = managedKeys.stream() + .filter(key -> !desired.containsKey(key)) + .toList(); + if (!dropped.isEmpty()) { + eventBridgeService.untagResource(arn, dropped, region); + } + if (!desired.isEmpty()) { + eventBridgeService.tagResource(arn, desired, region); + } + } + private Set eventBusManagedTagKeys(StackResource resource) { String value = resource.getAttributes().get(EVENT_BUS_MANAGED_TAG_KEYS_ATTR); if (value == null || value.isBlank()) { diff --git a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SsmCfnProvisioner.java b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SsmCfnProvisioner.java index 525fb0bb2c..50642764e3 100644 --- a/src/main/java/io/floci/aws/services/cloudformation/provisioners/SsmCfnProvisioner.java +++ b/src/main/java/io/floci/aws/services/cloudformation/provisioners/SsmCfnProvisioner.java @@ -3,7 +3,6 @@ package io.floci.aws.services.cloudformation.provisioners; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.floci.aws.core.common.AwsArnUtils; import io.floci.aws.services.cloudformation.model.StackResource; @@ -123,18 +122,9 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner { if (current.getPolicies() != null) { snapshot.putArray("policies").addAll(current.getPolicies()); } - // A managed key the parameter did not carry is listed without a value, so the rollback removes it. Set managedKeys = new TreeSet<>(templateTagKeys(attributesBefore)); managedKeys.addAll(desiredTagKeys); - Map currentTags = current.getTags() == null ? Map.of() : current.getTags(); - ArrayNode tagKeys = snapshot.putArray("tagKeys"); - ObjectNode tags = snapshot.putObject("tags"); - for (String key : managedKeys) { - tagKeys.add(key); - if (currentTags.containsKey(key)) { - tags.put(key, currentTags.get(key)); - } - } + CfnRollback.putTagSnapshot(snapshot, managedKeys, current.getTags() == null ? Map.of() : current.getTags()); r.getAttributes().put(CfnRollback.SSM_PARAMETER_UPDATE_SNAPSHOT_ATTR, snapshot.toString()); } @@ -265,10 +255,6 @@ public class SsmCfnProvisioner implements CfnResourceProvisioner { ssmService.putParameter(name, value, type, description, true, null, keyId, allowedPattern, tier, policies, region); } - List managedKeys = new ArrayList<>(); - snapshot.path("tagKeys").forEach(key -> managedKeys.add(key.asText())); - Map tags = new HashMap<>(); - snapshot.path("tags").properties().forEach(tag -> tags.put(tag.getKey(), tag.getValue().asText())); - reconcileTags(name, managedKeys, tags, region); + reconcileTags(name, CfnRollback.snapshotTagKeys(snapshot), CfnRollback.snapshotTags(snapshot), region); } } diff --git a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java index ace16e588b..37f0b71e23 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/CloudFormationEventBusIntegrationTest.java @@ -4,11 +4,14 @@ import io.floci.aws.core.common.XmlParser; import io.floci.aws.testing.CfnStackWaits; import io.floci.aws.testing.RestAssuredJsonUtils; import io.quarkus.test.junit.QuarkusTest; +import io.restassured.path.json.JsonPath; 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 java.util.HashMap; +import java.util.List; import java.util.Map; import static io.restassured.RestAssured.given; @@ -148,6 +151,10 @@ class CloudFormationEventBusIntegrationTest { } private static String eventBusWithTagsTemplate(String busName, String tags) { + return eventBusWithTagsTemplate(busName, tags, ""); + } + + private static String eventBusWithTagsTemplate(String busName, String tags, String moreResources) { return """ { "Resources": { @@ -159,9 +166,10 @@ class CloudFormationEventBusIntegrationTest { "Tags": %s } } + %s } } - """.formatted(busName, tags); + """.formatted(busName, tags, moreResources); } private static String eventBusWithPolicyTemplate(String busName, String statementId) { @@ -189,8 +197,8 @@ class CloudFormationEventBusIntegrationTest { """.formatted(busName, statementId); } - private void callEventBridge(String target, String body, int expectedStatus) { - given() + private JsonPath callEventBridge(String target, String body, int expectedStatus) { + return given() .contentType("application/x-amz-json-1.1") .header("Authorization", EVENTS_AUTH) .header("X-Amz-Target", target) @@ -198,7 +206,8 @@ class CloudFormationEventBusIntegrationTest { .when() .post("/") .then() - .statusCode(expectedStatus); + .statusCode(expectedStatus) + .extract().jsonPath(); } private static String eventBusAndRuleTemplate(String busName) { @@ -570,49 +579,95 @@ class CloudFormationEventBusIntegrationTest { } } + /** + * A tag-only update changes the tags of the bus the stack already has, as measured on AWS + * (eu-west-1, 2026-11-09): same ARN and creation time, UPDATE_COMPLETE, a tag the template + * dropped removed and a tag added outside the stack kept. + */ @Test - void mutableEventBusTagUpdateRollsBackWithoutChangingTags() { + void tagOnlyEventBusUpdateRetagsTheSameBus() { 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"},{"Key":"version","Value":"0.1.5"}] + """)); + 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); + Map busBefore = describeBus(busName); + + updateStack(stackName, eventBusWithTagsTemplate(busName, """ + [{"Key":"keep","Value":"after"},{"Key":"add","Value":"new"},{"Key":"version","Value":"0.1.6"}] + """)); + assertStackStatus(stackName, "UPDATE_COMPLETE"); + + assertEquals(busBefore, describeBus(busName)); + assertEquals(Map.of("keep", "after", "add", "new", "version", "0.1.6", "external", "preserve"), + busTags(busArn)); + if (!describeStackResources(stackName).contains("" + busName + "")) { + throw new AssertionError("tag update changed the bus physical id"); + } + + deleteStack(stackName); + CfnStackWaits.awaitStackDeleted(stackName); + } + + /** + * When a later resource fails the update, the tags the bus took go back, and the stack manages + * the tag keys of the template it kept: the next update still removes a key that template set. + */ + @Test + void eventBusTagUpdateRollsBackWhenALaterResourceFails() { + String suffix = Long.toString(System.nanoTime(), 36); + String busName = "rollback-tags-bus-" + suffix; + String stackName = "eventbus-tag-rollback-" + 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, """ + String newTags = """ [{"Key":"keep","Value":"after"},{"Key":"add","Value":"new"}] + """; + updateStack(stackName, eventBusWithTagsTemplate(busName, newTags, """ + ,"Bad": {"Type": "AWS::Events::EventBus", "DependsOn": "Bus", + "Properties": {"Description": "no name"}} """)); 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); - } + assertEquals(Map.of("keep", "before", "remove", "old", "external", "preserve"), busTags(busArn)); + + updateStack(stackName, eventBusWithTagsTemplate(busName, newTags)); + assertStackStatus(stackName, "UPDATE_COMPLETE"); + assertEquals(Map.of("keep", "after", "add", "new", "external", "preserve"), busTags(busArn)); deleteStack(stackName); CfnStackWaits.awaitStackDeleted(stackName); } + private Map busTags(String busArn) { + List> tags = callEventBridge("AWSEvents.ListTagsForResource", + "{\"ResourceARN\":\"" + busArn + "\"}", 200).getList("Tags"); + Map byKey = new HashMap<>(); + for (Map tag : tags) { + byKey.put(tag.get("Key"), tag.get("Value")); + } + return byKey; + } + + private Map describeBus(String busName) { + return callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200).getMap(""); + } + @Test void mutableEventBusPolicyUpdateRollsBackWithoutChangingPolicy() { String suffix = Long.toString(System.nanoTime(), 36); diff --git a/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java b/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java index 49144ed71e..469ca3ba3e 100644 --- a/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java +++ b/src/test/java/io/floci/aws/services/cloudformation/EventBusProvisionOwnershipTest.java @@ -12,11 +12,14 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.time.Instant; +import java.util.HashMap; import java.util.Map; import java.util.function.Function; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNull; +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; @@ -120,19 +123,90 @@ class EventBusProvisionOwnershipTest { .thenThrow(new AwsException("ResourceAlreadyExistsException", "exists", 400)); EventBus existingBus = bus(Instant.parse("2026-01-01T00:00:00Z")); existingBus.setPolicy("{\"Version\":\"2008-10-17\"}"); + existingBus.setTags(Map.of("version", "0.1.5")); when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus); + JsonNode properties = props(true); + ((ObjectNode) properties).putArray("Tags") + .addObject() + .put("Key", "version") + .put("Value", "0.1.6"); StackResource r = provisionExisting( - Map.of(MANAGED_POLICY_ATTR, "{\"Version\":\"2008-10-17\"}"), - props(true)); + Map.of(MANAGED_POLICY_ATTR, "{\"Version\":\"2008-10-17\"}", + MANAGED_TAG_KEYS_ATTR, "[\"version\"]"), + properties); assertEquals("CREATE_FAILED", r.getStatus()); assertEquals( - "Updating AWS::Events::EventBus Description, Tags, or Policy is not supported " + "Updating AWS::Events::EventBus Description or Policy is not supported " + "until transactional rollback is available.", r.getStatusReason()); verify(eventBridgeService, never()) .putPermission(anyString(), any(), any(), any(), any(), anyString(), anyString()); + verify(eventBridgeService, never()).tagResource(anyString(), any(), anyString()); + verify(eventBridgeService, never()).untagResource(anyString(), any(), anyString()); + } + + /** + * A tag call that fails after the bus's tags started changing must leave the attempt, snapshot + * and all, for the rollback walker: restoring the previous resource instead marks the bus as + * already rolled back and leaves the half-applied tags on it. + */ + @Test + void failedTagUpdateKeepsItsSnapshotForTheRollbackWalker() { + 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("version", "0.1.5")); + when(eventBridgeService.describeEventBus(BUS, REGION)).thenReturn(existingBus); + doThrow(new AwsException("InternalFailure", "store unavailable", 500)) + .doNothing() + .when(eventBridgeService).tagResource(anyString(), any(), anyString()); + JsonNode properties = props(false); + ((ObjectNode) properties).putArray("Tags") + .addObject() + .put("Key", "version") + .put("Value", "0.1.6"); + + StackResource r = provisionExisting(Map.of(MANAGED_TAG_KEYS_ATTR, "[\"version\"]"), properties); + + assertEquals("CREATE_FAILED", r.getStatus()); + assertTrue(provisioner.retainsFailedUpdateState(r)); + assertTrue(provisioner.rollbackUpdate(r)); + verify(eventBridgeService).tagResource(existingBus.getArn(), Map.of("version", "0.1.5"), REGION); + assertEquals("[\"version\"]", r.getAttributes().get(MANAGED_TAG_KEYS_ATTR)); + } + + /** + * A logical id whose type changed starts from the bus's attributes, stale tag snapshot included, + * so only an event bus attempt is kept for that snapshot. + */ + @Test + void anotherEventsTypeIsNotKeptForAnInheritedBusTagSnapshot() { + StackResource policy = new StackResource(); + policy.setLogicalId("OrdersBus"); + policy.setResourceType("AWS::Events::EventBusPolicy"); + policy.setAttributes(new HashMap<>(Map.of("__FlociEventBusUpdateSnapshot", "{}"))); + + assertFalse(provisioner.retainsFailedUpdateState(policy)); + } + + /** + * A bus the failed update never reached carries no snapshot, so its rollback reports false + * and the stack keeps saying rollback is not implemented, rather than touching its tags. + */ + @Test + void aBusWithoutAnUpdateSnapshotIsNotRolledBack() { + StackResource bus = new StackResource(); + bus.setLogicalId("OrdersBus"); + bus.setResourceType("AWS::Events::EventBus"); + bus.setPhysicalId(BUS); + bus.setAttributes(new HashMap<>(Map.of(MANAGED_TAG_KEYS_ATTR, "[\"version\"]"))); + + assertFalse(provisioner.rollbackUpdate(bus)); + verify(eventBridgeService, never()).tagResource(anyString(), any(), anyString()); + verify(eventBridgeService, never()).untagResource(anyString(), any(), anyString()); + assertEquals("[\"version\"]", bus.getAttributes().get(MANAGED_TAG_KEYS_ATTR)); } @Test diff --git a/src/test/java/io/floci/aws/services/cloudformation/provisioners/CfnRollbackTest.java b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CfnRollbackTest.java new file mode 100644 index 0000000000..7e0768c26d --- /dev/null +++ b/src/test/java/io/floci/aws/services/cloudformation/provisioners/CfnRollbackTest.java @@ -0,0 +1,34 @@ +package io.floci.aws.services.cloudformation.provisioners; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class CfnRollbackTest { + + private static final ObjectMapper MAPPER = new ObjectMapper(); + + /** + * A stored tag snapshot reads back the keys sorted and the values as the resource held them: + * a key it did not carry has no value, and a null value stays null rather than the text "null". + */ + @Test + void aStoredTagSnapshotReadsBackTheTagsAsTheyWere() throws Exception { + Map current = new HashMap<>(); + current.put("kept", "value"); + current.put("unset", null); + ObjectNode snapshot = MAPPER.createObjectNode(); + + CfnRollback.putTagSnapshot(snapshot, List.of("unset", "kept", "absent"), current); + + ObjectNode stored = (ObjectNode) MAPPER.readTree(snapshot.toString()); + assertEquals(List.of("absent", "kept", "unset"), CfnRollback.snapshotTagKeys(stored)); + assertEquals(current, CfnRollback.snapshotTags(stored)); + } +}