Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): create inline SNS subscriptions (#6443)

Jimmy Liu Jia7d4caf229150
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java
index c3a6ed0d57..d1ba0a15d8 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java
@@ -8,9 +8,12 @@ import io.github.hectorvent.floci.services.sns.model.Subscription;
import io.github.hectorvent.floci.services.sns.model.Topic;
import jakarta.enterprise.context.ApplicationScoped;
+import java.util.ArrayList;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Set;
import java.util.UUID;
@@ -23,6 +26,7 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
private static final String TOPIC_POLICY = "AWS::SNS::TopicPolicy";
private static final int TOPIC_NAME_MAX_LENGTH = 256;
private static final String FIFO_SUFFIX = ".fifo";
+ private static final String INLINE_SUBSCRIPTION_PREFIX = "__FlociInlineSubscription:";
private final SnsService snsService;
@@ -90,7 +94,24 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
attributes.put("MaximumMessageSize", maximumMessageSize);
}
- Topic topic = snsService.createTopic(topicName, attributes, Map.of(), ctx.region());
+ JsonNode subscriptions = props == null ? null
+ : ctx.engine().resolveNodeOmittingNoValue(props.path("Subscription"));
+ if (subscriptions != null && !subscriptions.isMissingNode() && !subscriptions.isNull()
+ && !subscriptions.isArray()) {
+ throw new AwsException("ValidationError", "Subscription must be a list.", 400);
+ }
+ List<SubscriptionTarget> desiredSubscriptions = new ArrayList<>();
+ if (subscriptions != null && subscriptions.isArray()) {
+ for (JsonNode subscription : subscriptions) {
+ desiredSubscriptions.add(new SubscriptionTarget(ctx.resolveOptional(subscription, "Protocol"),
+ ctx.resolveOptional(subscription, "Endpoint")));
+ }
+ }
+
+ SnsService.TopicCreation creation = snsService.createTopicWithStatus(
+ topicName, attributes, Map.of(), ctx.region());
+ Topic topic = creation.topic();
+ boolean created = creation.created();
// createTopic leaves an existing topic untouched, so an update writes the mutable
// attributes itself. A property the template dropped is reset, not left standing.
if (ctx.isUpdate()) {
@@ -117,6 +138,46 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
r.getAttributes().put("TopicArn", topic.getTopicArn());
r.getAttributes().put("Arn", topic.getTopicArn());
r.getAttributes().put("TopicName", topicName);
+
+ List<Subscription> existing = snsService.listSubscriptionsByTopic(topic.getTopicArn(), ctx.region());
+ Set<String> added = new HashSet<>();
+ CfnRollback.guarded(r, ctx, created,
+ () -> snsService.deleteTopic(topic.getTopicArn(), ctx.region()),
+ () -> added.forEach(arn -> snsService.unsubscribe(arn, ctx.region())),
+ () -> reconcileInlineSubscriptions(r, topic.getTopicArn(), ctx.region(),
+ desiredSubscriptions, existing, added));
+ }
+
+ private void reconcileInlineSubscriptions(StackResource r, String topicArn, String region,
+ List<SubscriptionTarget> desired, List<Subscription> existing,
+ Set<String> added) {
+ for (SubscriptionTarget target : desired) {
+ SnsService.SubscriptionCreation creation = snsService.subscribeWithStatus(
+ topicArn, target.protocol(), target.endpoint(), region, Map.of());
+ Subscription sub = creation.subscription();
+ if (creation.created()) {
+ added.add(sub.getSubscriptionArn());
+ r.getAttributes().put(INLINE_SUBSCRIPTION_PREFIX + sub.getSubscriptionArn(), "true");
+ }
+ }
+ for (Subscription sub : existing) {
+ String key = INLINE_SUBSCRIPTION_PREFIX + sub.getSubscriptionArn();
+ if (r.getAttributes().containsKey(key)
+ && desired.stream().noneMatch(target -> target.matches(sub))) {
+ snsService.unsubscribe(sub.getSubscriptionArn(), region);
+ r.getAttributes().remove(key);
+ }
+ }
+ r.getAttributes().keySet().removeIf(key -> key.startsWith(INLINE_SUBSCRIPTION_PREFIX)
+ && existing.stream().noneMatch(sub -> key.equals(INLINE_SUBSCRIPTION_PREFIX
+ + sub.getSubscriptionArn())) && !added.contains(key.substring(INLINE_SUBSCRIPTION_PREFIX.length())));
+ }
+
+ private record SubscriptionTarget(String protocol, String endpoint) {
+ private boolean matches(Subscription subscription) {
+ return Objects.equals(protocol, subscription.getProtocol())
+ && Objects.equals(endpoint, subscription.getEndpoint());
+ }
}
private void provisionSubscription(StackResource r, JsonNode props, ProvisionContext ctx) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
index 1fffbbbfac..369900fa8a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/sns/SnsService.java
@@ -556,6 +556,14 @@ public class SnsService implements Resettable, ResourceProvider {
public Topic createTopic(String name, Map<String, String> attributes,
Map<String, String> tags, String region) {
+ return createTopicWithStatus(name, attributes, tags, region).topic();
+ }
+
+ public record TopicCreation(Topic topic, boolean created) {
+ }
+
+ public synchronized TopicCreation createTopicWithStatus(String name, Map<String, String> attributes,
+ Map<String, String> tags, String region) {
if (name == null || name.isBlank()) {
throw new AwsException("InvalidParameter", "Topic name is required.", 400);
}
@@ -566,7 +574,7 @@ public class SnsService implements Resettable, ResourceProvider {
String key = topicKey(region, topicArn);
Topic existing = topicStore.get(key).orElse(null);
- if (existing != null) return existing;
+ if (existing != null) return new TopicCreation(existing, false);
Topic topic = new Topic(name, topicArn);
if (attributes != null) topic.getAttributes().putAll(attributes);
@@ -583,7 +591,7 @@ public class SnsService implements Resettable, ResourceProvider {
topicStore.put(key, topic);
LOG.infov("Created SNS topic: {0} in region {1}", name, region);
- return topic;
+ return new TopicCreation(topic, true);
}
public void deleteTopic(String topicArn, String region) {
@@ -911,7 +919,17 @@ public class SnsService implements Resettable, ResourceProvider {
}
}
- public Subscription subscribe(String topicArn, String protocol, String endpoint, String region, Map<String, String> attributes) {
+ public Subscription subscribe(String topicArn, String protocol, String endpoint, String region,
+ Map<String, String> attributes) {
+ return subscribeWithStatus(topicArn, protocol, endpoint, region, attributes).subscription();
+ }
+
+ public record SubscriptionCreation(Subscription subscription, boolean created) {
+ }
+
+ public SubscriptionCreation subscribeWithStatus(String topicArn, String protocol,
+ String endpoint, String region,
+ Map<String, String> attributes) {
String topicKey = topicKey(region, topicArn);
if (topicStore.get(topicKey).isEmpty() && !ensureControlTowerManagedTopic(topicArn, region)) {
throw new AwsException("NotFound", "Topic does not exist.", 404);
@@ -934,29 +952,32 @@ public class SnsService implements Resettable, ResourceProvider {
requireLargePayloadProtocol(protocol);
}
- for (Subscription existing : subscriptionsByTopic(topicArn, region)) {
- if (protocol.equals(existing.getProtocol())
- && Objects.equals(endpoint, existing.getEndpoint())) {
- return existing;
+ Subscription subscription;
+ synchronized (this) {
+ for (Subscription existing : subscriptionsByTopic(topicArn, region)) {
+ if (protocol.equals(existing.getProtocol())
+ && Objects.equals(endpoint, existing.getEndpoint())) {
+ return new SubscriptionCreation(existing, false);
+ }
}
- }
- String subscriptionArn = topicArn + ":" + UUID.randomUUID().toString();
- Subscription subscription = new Subscription(subscriptionArn, topicArn, protocol, endpoint,
- regionResolver.getAccountId());
- subscription.setAccountId(regionResolver.getAccountId());
- if (attributes != null) subscription.getAttributes().putAll(attributes);
+ String subscriptionArn = topicArn + ":" + UUID.randomUUID().toString();
+ subscription = new Subscription(subscriptionArn, topicArn, protocol, endpoint,
+ regionResolver.getAccountId());
+ subscription.setAccountId(regionResolver.getAccountId());
+ if (attributes != null) subscription.getAttributes().putAll(attributes);
- if (PENDING_CONFIRMATION_PROTOCOLS.contains(protocol)) {
- String token = UUID.randomUUID().toString().replace("-", "")
- + UUID.randomUUID().toString().replace("-", "");
- subscription.getAttributes().put("PendingConfirmation", "true");
- subscription.getAttributes().put("ConfirmationToken", token);
- LOG.infov("Subscription pending confirmation for {0} ({1}) to topic {2} in {3}",
- endpoint, protocol, topicArn, region);
- }
+ if (PENDING_CONFIRMATION_PROTOCOLS.contains(protocol)) {
+ String token = UUID.randomUUID().toString().replace("-", "")
+ + UUID.randomUUID().toString().replace("-", "");
+ subscription.getAttributes().put("PendingConfirmation", "true");
+ subscription.getAttributes().put("ConfirmationToken", token);
+ LOG.infov("Subscription pending confirmation for {0} ({1}) to topic {2} in {3}",
+ endpoint, protocol, topicArn, region);
+ }
- subscriptionStore.put(subKey(region, subscriptionArn), subscription);
+ subscriptionStore.put(subKey(region, subscriptionArn), subscription);
+ }
if (attributes == null || attributes.isEmpty()) {
LOG.infov("Subscribed {0} ({1}) to topic {2} in {3}", endpoint, protocol, topicArn, region);
} else {
@@ -967,7 +988,7 @@ public class SnsService implements Resettable, ResourceProvider {
sendSubscriptionConfirmation(subscription, topicArn, region);
}
- return subscription;
+ return new SubscriptionCreation(subscription, true);
}
private boolean ensureControlTowerManagedTopic(String topicArn, String region) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
index 9603606d50..7e4385a1e5 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationIntegrationTest.java
@@ -6,6 +6,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.testing.MutableClock;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.path.xml.XmlPath;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import jakarta.inject.Inject;
@@ -6689,6 +6690,204 @@ class CloudFormationIntegrationTest {
.body("authorizerId", equalTo(secondAuth));
}
+ @Test
+ void createStack_snsTopicWithInlineSubscriptions() {
+ String topicArn = "arn:aws:sns:us-east-1:000000000000:cfn-inline-subs-topic";
+ String template = """
+ {
+ "Resources": {
+ "MyQueue": {
+ "Type": "AWS::SQS::Queue",
+ "Properties": {"QueueName": "cfn-inline-subs-queue"}
+ },
+ "MyTopic": {
+ "Type": "AWS::SNS::Topic",
+ "Properties": {
+ "TopicName": "cfn-inline-subs-topic",
+ "Subscription": [
+ {"Protocol": "sqs", "Endpoint": {"Fn::GetAtt": ["MyQueue", "Arn"]}},
+ {"Protocol": "email", "Endpoint": "[email protected]"}
+ ]
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-inline-subs-stack")
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ String subscriptions = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListSubscriptionsByTopic")
+ .formParam("TopicArn", topicArn)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("arn:aws:sqs:us-east-1:000000000000:cfn-inline-subs-queue"))
+ .body(containsString("[email protected]"))
+ .extract().asString();
+ String sqsArn = new XmlPath(subscriptions)
+ .getString("**.find { it.Protocol == 'sqs' }.SubscriptionArn");
+ String emailArn = new XmlPath(subscriptions)
+ .getString("**.find { it.Protocol == 'email' }.SubscriptionArn");
+ assertTrue(sqsArn.startsWith(topicArn + ":"), sqsArn);
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "GetSubscriptionAttributes")
+ .formParam("SubscriptionArn", emailArn)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body("**.find { it.key == 'PendingConfirmation' }.value", equalTo("true"));
+ }
+
+ @Test
+ void createStack_snsTopicResolvesConditionalInlineSubscriptions() {
+ String topicArn = "arn:aws:sns:us-east-1:000000000000:cfn-conditional-subs-topic";
+ String template = """
+ {
+ "Conditions": {"Include": {"Fn::Equals": ["yes", "yes"]}},
+ "Resources": {
+ "MyTopic": {
+ "Type": "AWS::SNS::Topic",
+ "Properties": {
+ "TopicName": "cfn-conditional-subs-topic",
+ "Subscription": {"Fn::If": ["Include", [
+ {"Protocol": "email", "Endpoint": "[email protected]"},
+ {"Fn::If": ["Include", {"Ref": "AWS::NoValue"},
+ {"Protocol": "email", "Endpoint": "[email protected]"}]}
+ ], {"Ref": "AWS::NoValue"}]}
+ }
+ }
+ }
+ }
+ """;
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-conditional-subs-stack")
+ .formParam("TemplateBody", template)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListSubscriptionsByTopic")
+ .formParam("TopicArn", topicArn)
+ .when()
+ .post("/")
+ .then()
+ .statusCode(200)
+ .body(containsString("[email protected]"))
+ .body(not(containsString("[email protected]")));
+ }
+
+ @Test
+ void updateStack_snsTopicRemovesOnlyDroppedInlineSubscriptions() {
+ String topicArn = "arn:aws:sns:us-east-1:000000000000:cfn-update-inline-subs-topic";
+ String initialTemplate = """
+ {"Resources":{"MyTopic":{"Type":"AWS::SNS::Topic","Properties":{
+ "TopicName":"cfn-update-inline-subs-topic",
+ "Subscription":[{"Protocol":"email","Endpoint":"[email protected]"}]}}}}
+ """;
+ String updatedTemplate = """
+ {"Resources":{"MyTopic":{"Type":"AWS::SNS::Topic","Properties":{
+ "TopicName":"cfn-update-inline-subs-topic"}}}}
+ """;
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-update-inline-subs-stack")
+ .formParam("TemplateBody", initialTemplate)
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "Subscribe")
+ .formParam("TopicArn", topicArn)
+ .formParam("Protocol", "email")
+ .formParam("Endpoint", "[email protected]")
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "UpdateStack")
+ .formParam("StackName", "cfn-update-inline-subs-stack")
+ .formParam("TemplateBody", updatedTemplate)
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListSubscriptionsByTopic")
+ .formParam("TopicArn", topicArn)
+ .when().post("/").then().statusCode(200)
+ .body(containsString("[email protected]"))
+ .body(not(containsString("[email protected]")));
+ }
+
+ @Test
+ void createStack_snsTopicSubscribesSameStackLambda() {
+ String functionName = "cfn-inline-subs-lambda";
+ String functionArn = "arn:aws:lambda:us-east-1:000000000000:function:" + functionName;
+ String topicArn = "arn:aws:sns:us-east-1:000000000000:cfn-lambda-inline-subs-topic";
+ String template = """
+ {
+ "Resources": {
+ "Fn": {"Type":"AWS::Lambda::Function","Properties":{
+ "FunctionName":"%s","Runtime":"python3.12","Handler":"index.handler",
+ "Role":"arn:aws:iam::000000000000:role/cfn-test-lambda-role",
+ "Code":{"ZipFile":"def handler(e, c): return 'ok'"}}},
+ "Topic": {"Type":"AWS::SNS::Topic","Properties":{
+ "TopicName":"cfn-lambda-inline-subs-topic",
+ "Subscription":[{"Protocol":"lambda","Endpoint":{"Fn::GetAtt":["Fn","Arn"]}}]}},
+ "Perm": {"Type":"AWS::Lambda::Permission","Properties":{
+ "FunctionName":{"Ref":"Fn"},"Action":"lambda:InvokeFunction",
+ "Principal":"sns.amazonaws.com","SourceArn":{"Ref":"Topic"}}}
+ }
+ }
+ """.formatted(functionName);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "CreateStack")
+ .formParam("StackName", "cfn-lambda-inline-subs-stack")
+ .formParam("TemplateBody", template)
+ .when().post("/").then().statusCode(200);
+
+ given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "DescribeStacks")
+ .formParam("StackName", "cfn-lambda-inline-subs-stack")
+ .when().post("/").then().statusCode(200)
+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
+ String lambdaSubscriptionArn = given()
+ .contentType("application/x-www-form-urlencoded")
+ .formParam("Action", "ListSubscriptionsByTopic")
+ .formParam("TopicArn", topicArn)
+ .when().post("/").then().statusCode(200)
+ .body(containsString(functionArn))
+ .extract().xmlPath().getString("**.find { it.Protocol == 'lambda' }.SubscriptionArn");
+ assertTrue(lambdaSubscriptionArn.startsWith(topicArn + ":"), lambdaSubscriptionArn);
+ given()
+ .when().get("/2015-03-31/functions/" + functionName + "/policy")
+ .then().statusCode(200)
+ .body(containsString("sns.amazonaws.com"))
+ .body(containsString(topicArn));
+ }
+
@Test
void createStack_snsSqsFifoWithContentBasedDeduplicationAndSubscription() {
String stackName = "cfn-sns-sqs-fifo-stack";
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java
index 3d0e49cc00..cd48acd83f 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java
@@ -68,6 +68,17 @@ class SnsCfnProvisionerTest {
}
return values;
});
+ when(engine.resolveNodeOmittingNoValue(any())).thenAnswer(i -> i.getArgument(0));
+ when(sns.listTopics(REGION)).thenReturn(List.of());
+ when(sns.createTopicWithStatus(anyString(), anyMap(), anyMap(), eq(REGION)))
+ .thenAnswer(i -> new SnsService.TopicCreation(
+ sns.createTopic(i.getArgument(0), i.getArgument(1), i.getArgument(2), i.getArgument(3)),
+ false));
+ when(sns.listSubscriptionsByTopic(TOPIC_ARN, REGION)).thenReturn(List.of());
+ when(sns.subscribeWithStatus(anyString(), anyString(), anyString(), eq(REGION), anyMap()))
+ .thenAnswer(i -> new SnsService.SubscriptionCreation(
+ sns.subscribe(i.getArgument(0), i.getArgument(1), i.getArgument(2), i.getArgument(3),
+ i.getArgument(4)), true));
ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack");
}
@@ -116,6 +127,195 @@ class SnsCfnProvisionerTest {
r.getAttributes());
}
+ @Test
+ void topicCreatesInlineSubscriptions() {
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION))).thenReturn(topic(TOPIC_ARN));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("lambda"), eq("arn:lambda"), eq(REGION), anyMap()))
+ .thenReturn(subscription("arn:sub"));
+
+ provision("AWS::SNS::Topic", """
+ {"TopicName": "events", "Subscription": [
+ {"Protocol": "lambda", "Endpoint": "arn:lambda"}
+ ]}
+ """);
+
+ verify(sns).subscribe(TOPIC_ARN, "lambda", "arn:lambda", REGION, Map.of());
+ }
+
+ @Test
+ void topicWithoutPropertiesStillCreates() {
+ when(sns.createTopic(anyString(), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(topic(TOPIC_ARN));
+ StackResource r = new StackResource();
+ r.setLogicalId("Topic");
+ r.setResourceType("AWS::SNS::Topic");
+ r.setAttributes(new HashMap<>());
+
+ provisioner.provision(r, null, ctx);
+
+ assertEquals(TOPIC_ARN, r.getPhysicalId());
+ verify(sns, never()).subscribe(anyString(), anyString(), anyString(), anyString(), anyMap());
+ }
+
+ @Test
+ void topicUpdateRemovesOnlyItsDroppedInlineSubscription() {
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(topic(TOPIC_ARN));
+ Subscription old = subscription("arn:old");
+ old.setProtocol("sqs");
+ old.setEndpoint("arn:old-queue");
+ Subscription manual = subscription("arn:manual");
+ manual.setProtocol("sqs");
+ manual.setEndpoint("arn:manual-queue");
+ when(sns.listSubscriptionsByTopic(TOPIC_ARN, REGION))
+ .thenReturn(List.of(), List.of(old, manual));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:old-queue"), eq(REGION), anyMap()))
+ .thenReturn(old);
+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:new-queue"), eq(REGION), anyMap()))
+ .thenReturn(subscription("arn:new"));
+
+ StackResource r = provision("AWS::SNS::Topic", """
+ {"TopicName":"events","Subscription":[{"Protocol":"sqs","Endpoint":"arn:old-queue"}]}
+ """);
+ provisioner.provision(r, props("""
+ {"TopicName":"events","Subscription":[{"Protocol":"sqs","Endpoint":"arn:new-queue"}]}
+ """), new ProvisionContext(engine, REGION, "000000000000", "my-stack", TOPIC_ARN));
+
+ verify(sns).unsubscribe("arn:old", REGION);
+ verify(sns, never()).unsubscribe("arn:manual", REGION);
+ verify(sns).subscribe(TOPIC_ARN, "sqs", "arn:new-queue", REGION, Map.of());
+ }
+
+ @Test
+ void topicUpdateRemovesInlineSubscriptionWhenPropertyIsDropped() {
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(topic(TOPIC_ARN));
+ Subscription old = subscription("arn:old");
+ old.setProtocol("sqs");
+ old.setEndpoint("arn:old-queue");
+ when(sns.listSubscriptionsByTopic(TOPIC_ARN, REGION))
+ .thenReturn(List.of(), List.of(old));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:old-queue"), eq(REGION), anyMap()))
+ .thenReturn(old);
+
+ StackResource r = provision("AWS::SNS::Topic", """
+ {"TopicName":"events","Subscription":[{"Protocol":"sqs","Endpoint":"arn:old-queue"}]}
+ """);
+ provisioner.provision(r, props("""
+ {"TopicName":"events"}
+ """),
+ new ProvisionContext(engine, REGION, "000000000000", "my-stack", TOPIC_ARN));
+
+ verify(sns).unsubscribe("arn:old", REGION);
+ }
+
+ @Test
+ void failedInlineSubscriptionRemovesNewTopic() {
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(topic(TOPIC_ARN));
+ when(sns.createTopicWithStatus(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(new SnsService.TopicCreation(topic(TOPIC_ARN), true));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:queue"), eq(REGION), anyMap()))
+ .thenReturn(subscription("arn:first"));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("https"), eq("http://wrong"), eq(REGION), anyMap()))
+ .thenThrow(new AwsException("InvalidParameter", "Endpoint scheme mismatch", 400));
+
+ assertThrows(AwsException.class, () -> provision("AWS::SNS::Topic", """
+ {"TopicName":"events","Subscription":[
+ {"Protocol":"sqs","Endpoint":"arn:queue"},
+ {"Protocol":"https","Endpoint":"http://wrong"}]}
+ """));
+
+ verify(sns).deleteTopic(TOPIC_ARN, REGION);
+ }
+
+ @Test
+ void failedInlineSubscriptionKeepsPreexistingTopic() {
+ Topic preexisting = topic(TOPIC_ARN);
+ preexisting.setName("events");
+ when(sns.listTopics(REGION)).thenReturn(List.of(preexisting));
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(preexisting);
+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:queue"), eq(REGION), anyMap()))
+ .thenReturn(subscription("arn:first"));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("https"), eq("http://wrong"), eq(REGION), anyMap()))
+ .thenThrow(new AwsException("InvalidParameter", "Endpoint scheme mismatch", 400));
+
+ assertThrows(AwsException.class, () -> provision("AWS::SNS::Topic", """
+ {"TopicName":"events","Subscription":[
+ {"Protocol":"sqs","Endpoint":"arn:queue"},
+ {"Protocol":"https","Endpoint":"http://wrong"}]}
+ """));
+
+ verify(sns).unsubscribe("arn:first", REGION);
+ verify(sns, never()).deleteTopic(TOPIC_ARN, REGION);
+ }
+
+ @Test
+ void topicCreationStatusAvoidsListThenCreateRace() {
+ Topic createdByAnotherCaller = topic(TOPIC_ARN);
+ createdByAnotherCaller.setName("events");
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(createdByAnotherCaller);
+ when(sns.createTopicWithStatus(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(new SnsService.TopicCreation(createdByAnotherCaller, false));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("https"), eq("http://wrong"), eq(REGION), anyMap()))
+ .thenThrow(new AwsException("InvalidParameter", "Endpoint scheme mismatch", 400));
+ when(sns.subscribeWithStatus(eq(TOPIC_ARN), eq("https"), eq("http://wrong"), eq(REGION), anyMap()))
+ .thenThrow(new AwsException("InvalidParameter", "Endpoint scheme mismatch", 400));
+
+ assertThrows(AwsException.class, () -> provision("AWS::SNS::Topic", """
+ {"TopicName":"events","Subscription":[
+ {"Protocol":"https","Endpoint":"http://wrong"}]}
+ """));
+
+ verify(sns, never()).deleteTopic(TOPIC_ARN, REGION);
+ verify(sns, never()).listTopics(REGION);
+ }
+
+ @Test
+ void inlineSubscriptionCreationStatusProtectsAnotherCaller() {
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(topic(TOPIC_ARN));
+ when(sns.createTopicWithStatus(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(new SnsService.TopicCreation(topic(TOPIC_ARN), false));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:queue"), eq(REGION), anyMap()))
+ .thenReturn(subscription("arn:other"));
+ when(sns.subscribeWithStatus(eq(TOPIC_ARN), eq("sqs"), eq("arn:queue"), eq(REGION), anyMap()))
+ .thenReturn(new SnsService.SubscriptionCreation(subscription("arn:other"), false));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("https"), eq("http://wrong"), eq(REGION), anyMap()))
+ .thenThrow(new AwsException("InvalidParameter", "Endpoint scheme mismatch", 400));
+ when(sns.subscribeWithStatus(eq(TOPIC_ARN), eq("https"), eq("http://wrong"), eq(REGION), anyMap()))
+ .thenThrow(new AwsException("InvalidParameter", "Endpoint scheme mismatch", 400));
+
+ assertThrows(AwsException.class, () -> provision("AWS::SNS::Topic", """
+ {"TopicName":"events","Subscription":[
+ {"Protocol":"sqs","Endpoint":"arn:queue"},
+ {"Protocol":"https","Endpoint":"http://wrong"}]}
+ """));
+
+ verify(sns, never()).unsubscribe("arn:other", REGION);
+ verify(sns, never()).deleteTopic(TOPIC_ARN, REGION);
+ }
+
+ @Test
+ void topicResolvesConditionalSubscriptionList() {
+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION)))
+ .thenReturn(topic(TOPIC_ARN));
+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:selected"), eq(REGION), anyMap()))
+ .thenReturn(subscription("arn:selected-sub"));
+ when(engine.resolveNodeOmittingNoValue(any())).thenReturn(props("""
+ [{"Protocol":"sqs","Endpoint":"arn:selected"}]
+ """));
+
+ provision("AWS::SNS::Topic", """
+ {"TopicName":"events","Subscription":{"Fn::If":["Include",
+ [{"Protocol":"sqs","Endpoint":"arn:selected"}],{"Ref":"AWS::NoValue"}]}}
+ """);
+
+ verify(sns).subscribe(TOPIC_ARN, "sqs", "arn:selected", REGION, Map.of());
+ }
+
@Test
void anUnnamedTopicGetsAGeneratedStackScopedName() {
ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
diff --git a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
index 6b51018dd7..bb01fc2e92 100644
--- a/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/sns/SnsServiceTest.java
@@ -69,6 +69,18 @@ class SnsServiceTest {
assertEquals("arn:aws:sns:us-east-1:000000000000:my-topic", topic.getTopicArn());
}
+ @Test
+ void createTopicWithStatusReportsWhetherTheTopicWasCreated() {
+ SnsService.TopicCreation first = snsService.createTopicWithStatus(
+ "status-topic", null, null, REGION);
+ SnsService.TopicCreation second = snsService.createTopicWithStatus(
+ "status-topic", null, null, REGION);
+
+ assertTrue(first.created());
+ assertFalse(second.created());
+ assertSame(first.topic(), second.topic());
+ }
+
@Test
void smsAttributesAreScopedToAccountAndRegion() {
RegionResolver regionResolver = mock(RegionResolver.class);
@@ -250,6 +262,19 @@ class SnsServiceTest {
assertEquals(Map.of("attr1", "value1", "attr2", "value2"), sub.getAttributes());
}
+ @Test
+ void subscribeWithStatusReportsWhetherTheSubscriptionWasCreated() {
+ Topic topic = snsService.createTopic("status-topic", null, null, REGION);
+ SnsService.SubscriptionCreation first = snsService.subscribeWithStatus(
+ topic.getTopicArn(), "sqs", "http://localhost:4566/queue", REGION, Map.of());
+ SnsService.SubscriptionCreation second = snsService.subscribeWithStatus(
+ topic.getTopicArn(), "sqs", "http://localhost:4566/queue", REGION, Map.of());
+
+ assertTrue(first.created());
+ assertFalse(second.created());
+ assertSame(first.subscription(), second.subscription());
+ }
+
@Test
void subscribe_firehoseRequiresValidRoleArn() {
Topic topic = snsService.createTopic("firehose-topic", null, null, REGION);