feat(cloudformation): provision AWS::SNS::TopicPolicy (#3126)

Adds the type to SnsCfnProvisioner beside Topic and Subscription. A topic
policy is not an entity of its own: it writes the Policy attribute of every
topic the template lists, so re-applying on UpdateStack is what an update
means. The document goes through resolveJsonAttribute like FilterPolicy, so a
Ref to a topic inside Resource resolves to the ARN. The physical id is
synthetic and stays put across updates, as AWS::SQS::QueuePolicy does, and Ref
and Fn::GetAtt Id both return it. An empty Topics list or a missing
PolicyDocument is refused. Delete touches nothing, as with QueuePolicy.

Ported from lex00/floci#118. Tracked in lex00/floci#192.
This commit is contained in:
lex00 authored and GitHub committed 2026-09-06 15:11:42 -05:00
1 parent 024bfa0a5c
commit ba3dd657b6
5 files changed
+282 -5

No files matched your search

@@ -0,0 +1,165 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* Provisions an {@code AWS::SNS::TopicPolicy} over two topics the same stack creates, with the
* topic ARNs referenced inside the document the way CDK emits them. Asserts that both topics carry
* the resolved policy after create, that {@code Ref} and {@code Fn::GetAtt Id} agree and survive an
* update that rewrites the document, and that deleting the stack takes the topics with it.
*/
@QuarkusTest
class SnsTopicPolicyCfnIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
private static final String SNS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/sns/aws4_request";
private static final String STACK = "sns-topic-policy-cfn-it";
private static final String TEMPLATE = """
{
"Parameters": {"Sid": {"Type": "String"}},
"Resources": {
"TopicA": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": "sns-topic-policy-cfn-it-a"}},
"TopicB": {"Type": "AWS::SNS::Topic", "Properties": {"TopicName": "sns-topic-policy-cfn-it-b"}},
"Policy": {
"Type": "AWS::SNS::TopicPolicy",
"Properties": {
"Topics": [{"Ref": "TopicA"}, {"Ref": "TopicB"}],
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [{
"Sid": {"Ref": "Sid"},
"Effect": "Allow",
"Principal": {"AWS": "*"},
"Action": "sns:Publish",
"Resource": [{"Ref": "TopicA"}, {"Ref": "TopicB"}]
}]
}
}
}
},
"Outputs": {
"PolicyRef": {"Value": {"Ref": "Policy"}},
"PolicyId": {"Value": {"Fn::GetAtt": ["Policy", "Id"]}},
"TopicA": {"Value": {"Ref": "TopicA"}},
"TopicB": {"Value": {"Ref": "TopicB"}}
}
}
""";
@Test
void createUpdateAndDeleteATopicPolicy() throws InterruptedException {
cloudFormation("CreateStack", Map.of("Sid", "AllowPublishV1"));
String created = describeStacks("CREATE_COMPLETE");
String policyId = outputValue(created, "PolicyRef");
String topicA = outputValue(created, "TopicA");
String topicB = outputValue(created, "TopicB");
// Ref and Fn::GetAtt Id agree, and the id is the synthetic one a policy without an entity gets.
assertEquals(policyId, outputValue(created, "PolicyId"));
assertTrue(policyId.startsWith("topic-policy-"), policyId);
// Both topics carry the document, with the Ref inside Resource resolved to the ARN.
for (String topicArn : new String[] {topicA, topicB}) {
topicAttributes(topicArn)
.body(containsString("<key>Policy</key>"))
.body(containsString("AllowPublishV1"))
.body(containsString(topicA))
.body(containsString(topicB));
}
cloudFormation("UpdateStack", Map.of("Sid", "AllowPublishV2"));
String updated = describeStacks("UPDATE_COMPLETE");
// The document is rewritten on the same topics under the same id.
assertEquals(policyId, outputValue(updated, "PolicyRef"));
assertEquals(topicA, outputValue(updated, "TopicA"));
topicAttributes(topicA)
.body(containsString("AllowPublishV2"))
.body(not(containsString("AllowPublishV1")));
topicAttributes(topicB).body(containsString("AllowPublishV2"));
cloudFormation("DeleteStack", Map.of());
awaitStackDeleted();
topicAttributes(topicA).statusCode(404);
topicAttributes(topicB).statusCode(404);
}
private static void cloudFormation(String action, Map<String, String> parameters) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", STACK);
if (!"DeleteStack".equals(action)) {
request.formParam("TemplateBody", TEMPLATE);
}
int index = 1;
for (Map.Entry<String, String> parameter : parameters.entrySet()) {
request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
index++;
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
/** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
private static void awaitStackDeleted() throws InterruptedException {
for (int i = 0; i < 100; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", STACK)
.when().post("/").then().extract().asString();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("stack delete failed: " + body);
}
Thread.sleep(50);
}
fail("stack " + STACK + " was not deleted within the timeout");
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
private static ValidatableResponse topicAttributes(String topicArn) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", SNS_AUTH)
.formParam("Action", "GetTopicAttributes")
.formParam("TopicArn", topicArn)
.when().post("/").then();
}
}
@@ -2,6 +2,7 @@ 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.core.common.AwsException;
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;
@@ -11,21 +12,27 @@ import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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.assertThrows;
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.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
/** {@code AWS::SNS::Topic} and {@code AWS::SNS::Subscription}. */
/** {@code AWS::SNS::Topic}, {@code AWS::SNS::Subscription} and {@code AWS::SNS::TopicPolicy}. */
class SnsCfnProvisionerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
@@ -34,13 +41,14 @@ class SnsCfnProvisionerTest {
private SnsService sns;
private SnsCfnProvisioner provisioner;
private CloudFormationTemplateEngine engine;
private ProvisionContext ctx;
@BeforeEach
void setUp() {
sns = mock(SnsService.class);
provisioner = new SnsCfnProvisioner(sns);
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
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.
@@ -52,6 +60,14 @@ class SnsCfnProvisionerTest {
JsonNode node = i.getArgument(0);
return node == null ? null : MAPPER.writeValueAsString(node);
});
when(engine.resolveStringList(any())).thenAnswer(i -> {
JsonNode node = i.getArgument(0);
List<String> values = new ArrayList<>();
if (node != null && node.isArray()) {
node.forEach(element -> values.add(element.asText()));
}
return values;
});
ctx = new ProvisionContext(engine, REGION, "000000000000", "my-stack");
}
@@ -230,6 +246,61 @@ class SnsCfnProvisionerTest {
"unset optional attributes must not be sent as empty strings");
}
@Test
void topicPolicyWritesTheDocumentToEveryListedTopic() {
StackResource r = provision("AWS::SNS::TopicPolicy", """
{"Topics": ["arn:aws:sns:us-east-1:000000000000:a", "arn:aws:sns:us-east-1:000000000000:b"],
"PolicyDocument": {"Version": "2012-10-17", "Statement": [
{"Sid": "AllowPublish", "Effect": "Allow", "Principal": "*", "Action": "sns:Publish", "Resource": "*"}]}}
""");
// The document reaches SNS as serialized JSON, one SetTopicAttributes per topic.
verify(sns).setTopicAttributes(eq("arn:aws:sns:us-east-1:000000000000:a"), eq("Policy"),
contains("\"Sid\":\"AllowPublish\""), eq(REGION));
verify(sns).setTopicAttributes(eq("arn:aws:sns:us-east-1:000000000000:b"), eq("Policy"),
contains("\"Sid\":\"AllowPublish\""), eq(REGION));
assertTrue(r.getPhysicalId().startsWith("topic-policy-"), r.getPhysicalId());
assertEquals(Map.of("Id", r.getPhysicalId()), r.getAttributes());
}
@Test
void topicPolicyKeepsItsPhysicalIdAcrossUpdates() {
StackResource r = new StackResource();
r.setLogicalId("Policy");
r.setResourceType("AWS::SNS::TopicPolicy");
r.setPhysicalId("topic-policy-abc12345");
r.setAttributes(new HashMap<>(Map.of("Id", "topic-policy-abc12345")));
ProvisionContext update = new ProvisionContext(engine, REGION, "000000000000", "my-stack", "topic-policy-abc12345");
provisioner.provision(r, props("""
{"Topics": ["arn:aws:sns:us-east-1:000000000000:a"], "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
"""), update);
verify(sns).setTopicAttributes(eq("arn:aws:sns:us-east-1:000000000000:a"), eq("Policy"), anyString(), eq(REGION));
assertEquals("topic-policy-abc12345", r.getPhysicalId());
assertEquals("topic-policy-abc12345", r.getAttributes().get("Id"));
}
@Test
void topicPolicyWithoutTopicsIsRejected() {
AwsException e = assertThrows(AwsException.class, () -> provision("AWS::SNS::TopicPolicy", """
{"Topics": [], "PolicyDocument": {"Version": "2012-10-17", "Statement": []}}
"""));
assertEquals("ValidationError", e.getErrorCode());
verify(sns, never()).setTopicAttributes(any(), any(), any(), any());
}
@Test
void topicPolicyWithoutADocumentIsRejected() {
AwsException e = assertThrows(AwsException.class, () -> provision("AWS::SNS::TopicPolicy", """
{"Topics": ["arn:aws:sns:us-east-1:000000000000:a"]}
"""));
assertEquals("ValidationError", e.getErrorCode());
verify(sns, never()).setTopicAttributes(any(), any(), any(), any());
}
@Test
void deleteRoutesEachTypeToItsOwnCall() {
provisioner.delete("AWS::SNS::Topic", TOPIC_ARN, REGION);
@@ -237,5 +308,9 @@ class SnsCfnProvisionerTest {
provisioner.delete("AWS::SNS::Subscription", "arn:sub", REGION);
verify(sns).unsubscribe("arn:sub", REGION);
// A topic policy has no entity of its own, so its delete touches nothing.
provisioner.delete("AWS::SNS::TopicPolicy", "topic-policy-abc12345", REGION);
verifyNoMoreInteractions(sns);
}
}