fix(cloudformation): replace an SNS topic when the engine says its create-only properties changed (#8374)

This commit is contained in:
Oleksandr Nikolaichuk authored and GitHub committed 2026-11-16 16:23:34 -04:00
1 parent 2ca478b7ba
commit d2bca16023
6 files changed
+295 -25

No files matched your search

@@ -217,6 +217,11 @@ class CfnReplacementIntegrationTest {
+ " \"LogGroupName\": {\"Fn::If\": [\"Named\", \"repl-if-output\","
+ " {\"Ref\": \"AWS::NoValue\"}]}}}}}",
"Subject", "False", false, stack -> createOutputSource()),
createOnlyRow("SNS topic TopicName removed", "", "", "AWS::SNS::Topic",
"\"TopicName\": \"repl-sns-named\"", "\"DisplayName\": \"unnamed\"",
"True", false, null),
createOnlyRow("SNS topic FifoTopic switched on", "", "", "AWS::SNS::Topic",
"\"FifoTopic\": false", "\"FifoTopic\": true", "True", false, null),
new Row("deployed parameter renamed, same value",
locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"),
locationStack(stringParameter("NameB", HOSTED), "", REF_B, "e"),
@@ -0,0 +1,66 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.CfnTestStack;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.sns.SnsClient;
import software.amazon.awssdk.services.sns.model.Subscription;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
class CloudFormationSnsAdoptedTopicRollbackIntegrationTest {
private static final String ACCOUNT_ARN = "arn:aws:sns:us-east-1:000000000000:";
private static final String OUTSIDE_QUEUE = "arn:aws:sqs:us-east-1:000000000000:outside-queue";
private static final String INLINE_QUEUE = "arn:aws:sqs:us-east-1:000000000000:inline-queue";
@RegisterExtension
final CfnTestStack stack = new CfnTestStack("cfn-sns-adopt");
@Test
void aRolledBackReplacementLeavesTheTopicItAdoptedAsItWas() {
String suffix = Long.toString(System.nanoTime(), 36);
String own = "own-" + suffix;
String outside = "outside-" + suffix;
SnsClient sns = stack.client(SnsClient.builder());
String outsideArn = sns.createTopic(r -> r.name(outside).attributes(Map.of("DisplayName", "outside"))).topicArn();
try {
sns.subscribe(r -> r.topicArn(outsideArn).protocol("sqs").endpoint(OUTSIDE_QUEUE));
Map<String, String> before = sns.getTopicAttributes(r -> r.topicArn(outsideArn)).attributes();
stack.create(template(own, "", false));
String inline = ", \"MaximumMessageSize\": 4096, \"Subscription\": "
+ "[{\"Protocol\": \"sqs\", \"Endpoint\": \"" + INLINE_QUEUE + "\"}]";
Stack rolledBack = stack.update(template(outside, inline, true), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(before, sns.getTopicAttributes(r -> r.topicArn(outsideArn)).attributes());
assertEquals(List.of(OUTSIDE_QUEUE), sns.listSubscriptionsByTopic(r -> r.topicArn(outsideArn))
.subscriptions().stream().map(Subscription::endpoint).toList());
assertEquals(ACCOUNT_ARN + own, CfnStackWaits.output(rolledBack, "TopicRef"));
sns.getTopicAttributes(r -> r.topicArn(ACCOUNT_ARN + own));
} finally {
sns.deleteTopic(r -> r.topicArn(outsideArn));
}
}
/** A named topic; with {@code failing}, a later resource that fails, so the update rolls back. */
private static String template(String topicName, String extraTopicProperties, boolean failing) {
return """
{
"Resources": {
"Topic": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": "%s"%s}}%s
},
"Outputs": {"TopicRef": {"Value": {"Ref": "Topic"}}}
}
""".formatted(topicName, extraTopicProperties,
failing ? CfnStackWaits.failingResourceAfter("Topic") : "");
}
}
@@ -10,6 +10,8 @@ import io.floci.aws.services.sns.model.Subscription;
import io.floci.aws.services.sns.model.Topic;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
@@ -26,9 +28,11 @@ import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
@@ -412,27 +416,27 @@ class SnsCfnProvisionerTest {
"a standard topic must not be renamed into a FIFO one");
}
/**
* Replacing would displace a topic nothing cleans up, subscriptions included, so it is refused.
*/
/** A custom-named topic cannot be replaced under the same name, so turning it FIFO is refused. */
@Test
void aTopicTurningFifoIsRejectedRatherThanReplaced() {
void aNamedTopicTurningFifoIsRefusedAsACustomNamedReplacement() {
StackResource r = new StackResource();
r.setLogicalId("Topic");
r.setResourceType("AWS::SNS::Topic");
r.setAttributes(new HashMap<>(Map.of("TopicName", "my-stack-Topic-abc123def456")));
r.setAttributes(new HashMap<>(Map.of("TopicName", "events")));
r.setPhysicalId(TOPIC_ARN);
ProvisionContext update =
new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack", TOPIC_ARN);
ProvisionContext update = new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack",
TOPIC_ARN, e -> { }, props("""
{"TopicName": "events"}
"""));
JsonNode turningFifo = props("""
{"FifoTopic": true}
{"TopicName": "events", "FifoTopic": true}
""");
AwsException e = assertThrows(AwsException.class,
() -> provisioner.provision(r, turningFifo, update));
assertEquals("ValidationError", e.getErrorCode());
assertTrue(e.getMessage().contains("requires resource replacement"), e.getMessage());
assertTrue(e.getMessage().contains("custom-named"), e.getMessage());
verify(sns, never()).createTopic(anyString(), anyMap(), anyMap(), anyString());
}
@@ -847,4 +851,43 @@ class SnsCfnProvisionerTest {
provisioner.delete("AWS::SNS::TopicPolicy", "topic-policy-abc12345", REGION);
verifyNoMoreInteractions(sns);
}
/**
* A replacing update that a later resource fails points the topic back to the old ARN with the old
* inline-subscription marker, and deletes the new topic only when this update created it.
*/
@ParameterizedTest(name = "{0}")
@CsvSource(delimiter = '|', textBlock = """
unnamed topic turning FIFO | my-stack-Topic-abc123 | {"FifoTopic": false, "Subscription": [SUB]} | {"FifoTopic": true, "Subscription": [SUB]} | true | 1
rename onto a topic outside the stack | old | {"TopicName": "old", "Subscription": [SUB]} | {"TopicName": "taken", "Subscription": [SUB]} | false | 0
""")
void aRolledBackTopicReplacementRestoresTheOldTopicAndDeletesOnlyWhatItCreated(
String label, String priorName, String priorJson, String newJson, boolean created, int deletes) {
String oldArn = "arn:aws:sns:us-east-1:000000000000:" + priorName;
String newArn = "arn:aws:sns:us-east-1:000000000000:replacement";
String marker = "__FlociInlineSubscription:arn:old-sub";
String sub = "{\"Protocol\": \"lambda\", \"Endpoint\": \"arn:lambda\"}";
StackResource r = new StackResource();
r.setLogicalId("Topic");
r.setResourceType("AWS::SNS::Topic");
r.setPhysicalId(oldArn);
r.setAttributes(new HashMap<>(Map.of("TopicName", priorName, "TopicArn", oldArn, "Arn", oldArn,
marker, "true")));
doReturn(new SnsService.TopicCreation(topic(newArn), created))
.when(sns).createTopicWithStatus(anyString(), anyMap(), anyMap(), eq(REGION));
doReturn(subscription("arn:new-sub")).when(sns).subscribe(eq(newArn), anyString(), anyString(),
eq(REGION), anyMap());
ProvisionContext update = new ProvisionContext(ctx.engine(), REGION, "000000000000", "my-stack",
oldArn, e -> { }, props(priorJson.replace("SUB", sub)));
provisioner.provision(r, props(newJson.replace("SUB", sub)), update);
assertEquals(newArn, r.getPhysicalId(), label);
assertTrue(provisioner.rollbackUpdate(r), label);
assertEquals(oldArn, r.getPhysicalId(), label);
assertEquals(priorName, r.getAttributes().get("TopicName"), label);
assertEquals("true", r.getAttributes().get(marker), label);
verify(sns, times(deletes)).deleteTopic(newArn, REGION);
verify(sns, times(deletes)).deleteTopic(anyString(), eq(REGION));
}
}