Light, fluffy, and always free - The AWS Local Emulator alternative
refactor(cloudformation): move AWS::SNS::* into its own provisioner (#2759)
Hector Ventura9f7b7117f1ff
diff --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 5f94200fc4..efbbc7dd76 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@@ -267,8 +267,6 @@ public class CloudFormationResourceProvisioner {"AWS::RDS::DBSubnetGroup","AWS::Route53::HostedZone","AWS::Route53::RecordSet",- "AWS::SNS::Subscription",- "AWS::SNS::Topic","AWS::SecretsManager::Secret","AWS::SecretsManager::SecretTargetAttachment","AWS::StepFunctions::StateMachine",@@ -285,7 +283,6 @@ public class CloudFormationResourceProvisioner {private static final Duration CR_RESPONSE_TIMEOUT = Duration.ofSeconds(10);private final S3Service s3Service;- private final SnsService snsService;private final DynamoDbService dynamoDbService;private final LambdaService lambdaService;private final IamService iamService;@@ -350,7 +347,6 @@ public class CloudFormationResourceProvisioner {EmulatorConfig config) {this.config = config;this.s3Service = s3Service;- this.snsService = snsService;this.dynamoDbService = dynamoDbService;this.lambdaService = lambdaService;this.iamService = iamService;@@ -413,8 +409,6 @@ public class CloudFormationResourceProvisioner {return resource;}switch (resourceType) {- case "AWS::SNS::Topic" -> provisionSnsTopic(resource, properties, engine, region, accountId, stackName);- case "AWS::SNS::Subscription" -> provisionSnsSubscription(resource, properties, engine, region);case "AWS::DynamoDB::Table", "AWS::DynamoDB::GlobalTable" ->provisionDynamoTable(resource, properties, engine, region, accountId, stackName);case "AWS::Lambda::Function" -> provisionLambda(resource, properties, engine, region, accountId, stackName);@@ -694,8 +688,6 @@ public class CloudFormationResourceProvisioner {return;}switch (resourceType) {- case "AWS::SNS::Topic" -> snsService.deleteTopic(physicalId, region);- case "AWS::SNS::Subscription" -> snsService.unsubscribe(physicalId, region);case "AWS::DynamoDB::Table" -> deleteDynamoTableSafe(physicalId, region);case "AWS::Lambda::Function" -> deleteLambdaFunctionSafe(physicalId, region);// AWS::IAM::Policy is inline: it is removed together with its owning principal (see@@ -1804,50 +1796,6 @@ public class CloudFormationResourceProvisioner {// ── SNS ───────────────────────────────────────────────────────────────────- private void provisionSnsTopic(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,- String region, String accountId, String stackName) {- String topicName = resolveOptional(props, "TopicName", engine);- String contentBasedDedupFlag = resolveOptional(props, "ContentBasedDeduplication", engine);- if (topicName == null || topicName.isBlank()) {- topicName = generatePhysicalName(stackName, r.getLogicalId(), 256, false);- }-- Map<String, String> attributes = new HashMap<>();-- if (contentBasedDedupFlag != null && !contentBasedDedupFlag.isBlank()) {- attributes.put("ContentBasedDeduplication", contentBasedDedupFlag);- }-- var topic = snsService.createTopic(topicName, attributes, Map.of(), region);- r.setPhysicalId(topic.getTopicArn());- r.getAttributes().put("Arn", topic.getTopicArn());- r.getAttributes().put("TopicName", topicName);- }-- private void provisionSnsSubscription(StackResource r, JsonNode props, CloudFormationTemplateEngine engine, String region) {- String topicArn = engine.resolve(props.path("TopicArn"));- String protocol = engine.resolve(props.path("Protocol"));- String endpoint = engine.resolve(props.path("Endpoint"));-- Map<String, String> attributes = new HashMap<>();- if (props.has("FilterPolicy") && !props.path("FilterPolicy").isNull()) {- attributes.put("FilterPolicy", engine.resolveJsonAttribute(props.path("FilterPolicy")));- }- if (props.has("FilterPolicyScope")) {- attributes.put("FilterPolicyScope", engine.resolve(props.path("FilterPolicyScope")));- }- if (props.has("RawMessageDelivery")) {- attributes.put("RawMessageDelivery", engine.resolve(props.path("RawMessageDelivery")));- }- if (props.has("RedrivePolicy") && !props.path("RedrivePolicy").isNull()) {- attributes.put("RedrivePolicy", engine.resolveJsonAttribute(props.path("RedrivePolicy")));- }-- var sub = snsService.subscribe(topicArn, protocol, endpoint, region, attributes);- r.setPhysicalId(sub.getSubscriptionArn());- r.getAttributes().put("Arn", sub.getSubscriptionArn());- }-// ── DynamoDB ──────────────────────────────────────────────────────────────private void provisionDynamoTable(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,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.javanew file mode 100644index 0000000000..56a63cd37c--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisioner.java@@ -0,0 +1,96 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.sns.SnsService;+import jakarta.enterprise.context.ApplicationScoped;++import java.util.HashMap;+import java.util.Map;+import java.util.Set;++/** Provisions {@code AWS::SNS::Topic} and {@code AWS::SNS::Subscription}. */+@ApplicationScoped+public class SnsCfnProvisioner implements CfnResourceProvisioner {++ private static final String TOPIC = "AWS::SNS::Topic";+ private static final String SUBSCRIPTION = "AWS::SNS::Subscription";+ private static final int TOPIC_NAME_MAX_LENGTH = 256;++ private final SnsService snsService;++ public SnsCfnProvisioner(SnsService snsService) {+ this.snsService = snsService;+ }++ @Override+ public Set<String> resourceTypes() {+ return Set.of(TOPIC, SUBSCRIPTION);+ }++ @Override+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {+ switch (r.getResourceType()) {+ case TOPIC -> provisionTopic(r, props, ctx);+ case SUBSCRIPTION -> provisionSubscription(r, props, ctx);+ default -> throw new IllegalStateException(+ "SnsCfnProvisioner cannot provision " + r.getResourceType());+ }+ }++ private void provisionTopic(StackResource r, JsonNode props, ProvisionContext ctx) {+ String topicName = ctx.resolveOptional(props, "TopicName");+ String contentBasedDedupFlag = ctx.resolveOptional(props, "ContentBasedDeduplication");+ if (topicName == null || topicName.isBlank()) {+ topicName = ctx.generatePhysicalName(r.getLogicalId(), TOPIC_NAME_MAX_LENGTH, false);+ }++ Map<String, String> attributes = new HashMap<>();+ if (contentBasedDedupFlag != null && !contentBasedDedupFlag.isBlank()) {+ attributes.put("ContentBasedDeduplication", contentBasedDedupFlag);+ }++ var topic = snsService.createTopic(topicName, attributes, Map.of(), ctx.region());+ // Ref returns the topic ARN, which is why the physical id is the ARN and not the name.+ r.setPhysicalId(topic.getTopicArn());+ r.getAttributes().put("Arn", topic.getTopicArn());+ r.getAttributes().put("TopicName", topicName);+ }++ private void provisionSubscription(StackResource r, JsonNode props, ProvisionContext ctx) {+ String topicArn = ctx.engine().resolve(props.path("TopicArn"));+ String protocol = ctx.engine().resolve(props.path("Protocol"));+ String endpoint = ctx.engine().resolve(props.path("Endpoint"));++ Map<String, String> attributes = new HashMap<>();+ // FilterPolicy and RedrivePolicy are JSON documents, so they go through+ // resolveJsonAttribute, which serializes the resolved node once. Passing them through the+ // scalar resolve() instead would hand SNS a re-encoded string and break filtering.+ if (props.has("FilterPolicy") && !props.path("FilterPolicy").isNull()) {+ attributes.put("FilterPolicy", ctx.engine().resolveJsonAttribute(props.path("FilterPolicy")));+ }+ if (props.has("FilterPolicyScope")) {+ attributes.put("FilterPolicyScope", ctx.engine().resolve(props.path("FilterPolicyScope")));+ }+ if (props.has("RawMessageDelivery")) {+ attributes.put("RawMessageDelivery", ctx.engine().resolve(props.path("RawMessageDelivery")));+ }+ if (props.has("RedrivePolicy") && !props.path("RedrivePolicy").isNull()) {+ attributes.put("RedrivePolicy", ctx.engine().resolveJsonAttribute(props.path("RedrivePolicy")));+ }++ var sub = snsService.subscribe(topicArn, protocol, endpoint, ctx.region(), attributes);+ r.setPhysicalId(sub.getSubscriptionArn());+ r.getAttributes().put("Arn", sub.getSubscriptionArn());+ }++ @Override+ public void delete(String resourceType, String physicalId, String region) {+ switch (resourceType) {+ case TOPIC -> snsService.deleteTopic(physicalId, region);+ case SUBSCRIPTION -> snsService.unsubscribe(physicalId, region);+ default -> throw new IllegalStateException(+ "SnsCfnProvisioner cannot delete " + resourceType);+ }+ }+}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.javanew file mode 100644index 0000000000..60071b0a10--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SnsCfnProvisionerTest.java@@ -0,0 +1,216 @@+package io.github.hectorvent.floci.services.cloudformation.provisioners;++import com.fasterxml.jackson.databind.JsonNode;+import com.fasterxml.jackson.databind.ObjectMapper;+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;+import io.github.hectorvent.floci.services.sns.SnsService;+import io.github.hectorvent.floci.services.sns.model.Subscription;+import io.github.hectorvent.floci.services.sns.model.Topic;+import org.junit.jupiter.api.BeforeEach;+import org.junit.jupiter.api.Test;+import org.mockito.ArgumentCaptor;++import java.util.HashMap;+import java.util.Map;++import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertFalse;+import static org.junit.jupiter.api.Assertions.assertTrue;+import static org.mockito.ArgumentMatchers.any;+import static org.mockito.ArgumentMatchers.anyMap;+import static org.mockito.ArgumentMatchers.anyString;+import static org.mockito.ArgumentMatchers.eq;+import static org.mockito.Mockito.mock;+import static org.mockito.Mockito.verify;+import static org.mockito.Mockito.when;++/** {@code AWS::SNS::Topic} and {@code AWS::SNS::Subscription}. */+class SnsCfnProvisionerTest {++ private static final ObjectMapper MAPPER = new ObjectMapper();+ private static final String REGION = "us-east-1";+ private static final String TOPIC_ARN = "arn:aws:sns:us-east-1:000000000000:events";++ private SnsService sns;+ private SnsCfnProvisioner provisioner;+ private ProvisionContext ctx;++ @BeforeEach+ void setUp() {+ sns = mock(SnsService.class);+ provisioner = new SnsCfnProvisioner(sns);+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);+ // The two resolvers are stubbed with the semantics that distinguish them, so a body that+ // reaches for the wrong one is visible: resolve() is scalar (an object node flattens to+ // ""), resolveJsonAttribute() serializes the document.+ when(engine.resolve(any())).thenAnswer(i -> {+ JsonNode node = i.getArgument(0);+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();+ });+ when(engine.resolveJsonAttribute(any())).thenAnswer(i -> {+ JsonNode node = i.getArgument(0);+ return node == null ? null : MAPPER.writeValueAsString(node);+ });+ ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack");+ }++ private static JsonNode props(String json) {+ try {+ return MAPPER.readTree(json);+ } catch (Exception e) {+ throw new IllegalArgumentException(e);+ }+ }++ private StackResource provision(String type, String json) {+ StackResource r = new StackResource();+ r.setLogicalId(type.endsWith("Topic") ? "Topic" : "Sub");+ r.setResourceType(type);+ r.setAttributes(new HashMap<>());+ provisioner.provision(r, props(json), ctx);+ return r;+ }++ private static Topic topic(String arn) {+ Topic t = new Topic();+ t.setTopicArn(arn);+ return t;+ }++ private static Subscription subscription(String arn) {+ Subscription s = new Subscription();+ s.setSubscriptionArn(arn);+ return s;+ }++ @Test+ void topicRefIsTheArnNotTheName() {+ when(sns.createTopic(eq("events"), anyMap(), anyMap(), eq(REGION))).thenReturn(topic(TOPIC_ARN));++ StackResource r = provision("AWS::SNS::Topic", """+ {"TopicName": "events"}+ """);++ // Ref on an SNS topic returns the ARN, unlike most types where it is the name.+ assertEquals(TOPIC_ARN, r.getPhysicalId());+ assertEquals(Map.of("Arn", TOPIC_ARN, "TopicName", "events"), r.getAttributes());+ }++ @Test+ void anUnnamedTopicGetsAGeneratedStackScopedName() {+ ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);+ when(sns.createTopic(name.capture(), anyMap(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));++ provision("AWS::SNS::Topic", "{}");++ assertTrue(name.getValue().startsWith("my-stack-Topic-"), name.getValue());+ }++ @Test+ void contentBasedDeduplicationIsForwardedOnlyWhenSet() {+ ArgumentCaptor<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);+ when(sns.createTopic(anyString(), attrs.capture(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));++ provision("AWS::SNS::Topic", """+ {"TopicName": "t", "ContentBasedDeduplication": "true"}+ """);+ assertEquals("true", attrs.getValue().get("ContentBasedDeduplication"));++ setUp();+ ArgumentCaptor<Map<String, String>> plain = ArgumentCaptor.forClass(Map.class);+ when(sns.createTopic(anyString(), plain.capture(), anyMap(), anyString())).thenReturn(topic(TOPIC_ARN));+ provision("AWS::SNS::Topic", """+ {"TopicName": "t"}+ """);+ assertFalse(plain.getValue().containsKey("ContentBasedDeduplication"),+ "an absent flag must not be sent as an empty attribute");+ }++ @Test+ void subscriptionRefIsTheSubscriptionArn() {+ when(sns.subscribe(eq(TOPIC_ARN), eq("sqs"), eq("arn:queue"), eq(REGION), anyMap()))+ .thenReturn(subscription("arn:sub"));++ StackResource r = provision("AWS::SNS::Subscription", """+ {"TopicArn": "%s", "Protocol": "sqs", "Endpoint": "arn:queue"}+ """.formatted(TOPIC_ARN));++ assertEquals("arn:sub", r.getPhysicalId());+ assertEquals(Map.of("Arn", "arn:sub"), r.getAttributes());+ }++ /**+ * FilterPolicy is a JSON document, and SNS expects it as a JSON string. It must be serialized+ * once: handing over an already-encoded string would give SNS a quoted blob and silently break+ * message filtering.+ */+ @Test+ void filterPolicyIsSerializedAsJsonNotAsAQuotedString() {+ ArgumentCaptor<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);+ when(sns.subscribe(anyString(), anyString(), anyString(), anyString(), attrs.capture()))+ .thenReturn(subscription("arn:sub"));++ provision("AWS::SNS::Subscription", """+ {"TopicArn": "t", "Protocol": "sqs", "Endpoint": "e",+ "FilterPolicy": {"eventType": ["created", "updated"]}}+ """);++ String filterPolicy = attrs.getValue().get("FilterPolicy");+ assertEquals("{\"eventType\":[\"created\",\"updated\"]}", filterPolicy);+ assertFalse(filterPolicy.startsWith("\"\\{") || filterPolicy.startsWith("\"{"),+ "double-encoded FilterPolicy: " + filterPolicy);+ }++ @Test+ void redrivePolicyIsSerializedTheSameWay() {+ ArgumentCaptor<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);+ when(sns.subscribe(anyString(), anyString(), anyString(), anyString(), attrs.capture()))+ .thenReturn(subscription("arn:sub"));++ provision("AWS::SNS::Subscription", """+ {"TopicArn": "t", "Protocol": "sqs", "Endpoint": "e",+ "RedrivePolicy": {"deadLetterTargetArn": "arn:dlq"}}+ """);++ assertEquals("{\"deadLetterTargetArn\":\"arn:dlq\"}", attrs.getValue().get("RedrivePolicy"));+ }++ @Test+ void scalarSubscriptionAttributesStayScalar() {+ ArgumentCaptor<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);+ when(sns.subscribe(anyString(), anyString(), anyString(), anyString(), attrs.capture()))+ .thenReturn(subscription("arn:sub"));++ provision("AWS::SNS::Subscription", """+ {"TopicArn": "t", "Protocol": "sqs", "Endpoint": "e",+ "RawMessageDelivery": "true", "FilterPolicyScope": "MessageBody"}+ """);++ assertEquals("true", attrs.getValue().get("RawMessageDelivery"));+ assertEquals("MessageBody", attrs.getValue().get("FilterPolicyScope"));+ }++ @Test+ void absentPolicyAttributesAreOmittedEntirely() {+ ArgumentCaptor<Map<String, String>> attrs = ArgumentCaptor.forClass(Map.class);+ when(sns.subscribe(anyString(), anyString(), anyString(), anyString(), attrs.capture()))+ .thenReturn(subscription("arn:sub"));++ provision("AWS::SNS::Subscription", """+ {"TopicArn": "t", "Protocol": "sqs", "Endpoint": "e"}+ """);++ assertEquals(Map.of(), attrs.getValue(),+ "unset optional attributes must not be sent as empty strings");+ }++ @Test+ void deleteRoutesEachTypeToItsOwnCall() {+ provisioner.delete("AWS::SNS::Topic", TOPIC_ARN, REGION);+ verify(sns).deleteTopic(TOPIC_ARN, REGION);++ provisioner.delete("AWS::SNS::Subscription", "arn:sub", REGION);+ verify(sns).unsubscribe("arn:sub", REGION);+ }+}diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsvindex b31fb19afb..5056638d3e 100644--- a/src/test/resources/cloudformation/supported-resource-types.tsv+++ b/src/test/resources/cloudformation/supported-resource-types.tsv@@ -100,8 +100,8 @@ AWS::Route53::HostedZone LEGACY_SWITCHAWS::Route53::RecordSet LEGACY_SWITCHAWS::S3::Bucket S3CfnProvisionerAWS::S3::BucketPolicy S3CfnProvisioner-AWS::SNS::Subscription LEGACY_SWITCH-AWS::SNS::Topic LEGACY_SWITCH+AWS::SNS::Subscription SnsCfnProvisioner+AWS::SNS::Topic SnsCfnProvisionerAWS::SQS::Queue SqsCfnProvisionerAWS::SQS::QueuePolicy SqsCfnProvisionerAWS::SSM::Parameter SsmCfnProvisioner