fix(cloudformation): update the tags of an AWS::Events::EventBus in place (#7799)

* fix(cloudformation): update the tags of an AWS::Events::EventBus in place

A tag-only UpdateStack of an event bus was refused with "Updating
AWS::Events::EventBus Description, Tags, or Policy is not supported until
transactional rollback is available." and rolled back, so a template that
bumps a version tag could not be deployed.

The bus the stack already owns now takes the template's tags: a key the
stack set and the template dropped is untagged, a tag added outside the
stack stays, as measured on AWS. The tags of the keys the update touches
are snapshotted first, and rollbackUpdate puts them and the tracked keys
back when a later resource fails the update. Description and Policy
changes are still refused.

Closes #7796

* fix(cloudformation): keep a failed event bus tag update for its rollback

A tag call that fails after the bus's tags started changing left the
engine restoring the previous resource and marking it rolled back, so
the half-applied tags stayed. retainsFailedUpdateState now keeps an
attempt that carries the tag snapshot, and the rollback walker restores
it through rollbackUpdate, as the SSM parameter provisioner does.

* test(cloudformation): read EventBridge answers through callEventBridge

* refactor(cloudformation): share the tag snapshot of an update with SSM

The event bus recorded and read back the tags of an update the same way
the SSM parameter does. CfnRollback now holds that pair, putTagSnapshot,
snapshotTagKeys and snapshotTags, in the same tagKeys and tags fields, so
a snapshot an SSM update already stored still reads. The bus reconciles
its tags from the managed keys and the desired tags, as SSM's
reconcileTags does, so its update and rollback no longer each work out
the keys to remove.

* fix(cloudformation): read a null tag value back as null from a tag snapshot

* refactor(cloudformation): read the event bus update snapshot through CfnRollback

rollbackEventBusUpdate parsed its snapshot by hand, which is what
CfnRollback.updateSnapshot does; it now uses that and still reports
false when the bus carries no snapshot. The CloudFormation docs say
event bus tags now update in place on UpdateStack, keeping tags added
outside the stack, and go back when a later resource fails the update.
This commit is contained in:
Mario Toffia authored and GitHub committed 2026-11-10 08:17:17 -04:00
1 parent aff365d1e5
commit 8b48aafd44
7 files changed
+324 -65

No files matched your search

@@ -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<String, Object> 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("<PhysicalResourceId>" + busName + "</PhysicalResourceId>")) {
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<String, String> busTags(String busArn) {
List<Map<String, String>> tags = callEventBridge("AWSEvents.ListTagsForResource",
"{\"ResourceARN\":\"" + busArn + "\"}", 200).getList("Tags");
Map<String, String> byKey = new HashMap<>();
for (Map<String, String> tag : tags) {
byKey.put(tag.get("Key"), tag.get("Value"));
}
return byKey;
}
private Map<String, Object> describeBus(String busName) {
return callEventBridge("AWSEvents.DescribeEventBus", "{\"Name\":\"" + busName + "\"}", 200).getMap("");
}
@Test
void mutableEventBusPolicyUpdateRollsBackWithoutChangingPolicy() {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -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
@@ -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<String, String> 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));
}
}