mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
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:
1 parent
024bfa0a5c
commit
ba3dd657b6
5 files changed
+282
-5
No files matched your search
@@ -68,7 +68,7 @@ cross-resource references.
|
||||
|---|---|
|
||||
| S3 | `Bucket`, `BucketPolicy` (accepted; policy not enforced) |
|
||||
| SQS | `Queue`, `QueuePolicy` (accepted; policy not enforced) |
|
||||
| SNS | `Topic`, `Subscription` |
|
||||
| SNS | `Topic`, `Subscription`, `TopicPolicy` |
|
||||
| DynamoDB | `Table`, `GlobalTable` |
|
||||
| Lambda | `Function` (Zip via S3/inline `ZipFile`, and Image), `LayerVersion`, `EventSourceMapping` (SQS, Kinesis, DynamoDB Streams), `Version`, `Alias` (also what SAM's `AutoPublishAlias` expands into), `Permission`, `MicrovmImage`, `NetworkConnector`. Inline `ZipFile` packages include the `cfn-response` (Node.js) / `cfnresponse` (Python) module AWS injects for that code path, so Solutions-style custom-resource handlers work. |
|
||||
| IAM | `Role`, `User`, `AccessKey`, `Policy`, `ManagedPolicy`, `InstanceProfile` |
|
||||
|
||||
+38
-2
@@ -1,20 +1,24 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
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.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/** Provisions {@code AWS::SNS::Topic} and {@code AWS::SNS::Subscription}. */
|
||||
/** Provisions {@code AWS::SNS::Topic}, {@code AWS::SNS::Subscription} and {@code AWS::SNS::TopicPolicy}. */
|
||||
@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 String TOPIC_POLICY = "AWS::SNS::TopicPolicy";
|
||||
private static final int TOPIC_NAME_MAX_LENGTH = 256;
|
||||
|
||||
private final SnsService snsService;
|
||||
@@ -25,7 +29,7 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of(TOPIC, SUBSCRIPTION);
|
||||
return Set.of(TOPIC, SUBSCRIPTION, TOPIC_POLICY);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -33,6 +37,7 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
switch (r.getResourceType()) {
|
||||
case TOPIC -> provisionTopic(r, props, ctx);
|
||||
case SUBSCRIPTION -> provisionSubscription(r, props, ctx);
|
||||
case TOPIC_POLICY -> provisionTopicPolicy(r, props, ctx);
|
||||
default -> throw new IllegalStateException(
|
||||
"SnsCfnProvisioner cannot provision " + r.getResourceType());
|
||||
}
|
||||
@@ -93,11 +98,42 @@ public class SnsCfnProvisioner implements CfnResourceProvisioner {
|
||||
r.getAttributes().put("Arn", sub.getSubscriptionArn());
|
||||
}
|
||||
|
||||
/**
|
||||
* 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, and the physical id
|
||||
* only has to stay put across updates, as with {@code AWS::SQS::QueuePolicy}. {@code Ref} and
|
||||
* {@code Fn::GetAtt Id} both return that id.
|
||||
*/
|
||||
private void provisionTopicPolicy(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
List<String> topics = ctx.resolveStringList(props, "Topics");
|
||||
if (topics.isEmpty()) {
|
||||
throw new AwsException("ValidationError",
|
||||
"AWS::SNS::TopicPolicy requires at least one topic ARN in Topics.", 400);
|
||||
}
|
||||
if (props == null || !props.hasNonNull("PolicyDocument")) {
|
||||
throw new AwsException("ValidationError", "AWS::SNS::TopicPolicy requires a PolicyDocument.", 400);
|
||||
}
|
||||
// The document is JSON with intrinsics inside (topic ARNs in Resource, typically), so it
|
||||
// goes through resolveJsonAttribute like FilterPolicy above rather than the scalar resolve.
|
||||
String policy = ctx.engine().resolveJsonAttribute(props.path("PolicyDocument"));
|
||||
for (String topicArn : topics) {
|
||||
snsService.setTopicAttributes(topicArn, "Policy", policy, ctx.region());
|
||||
}
|
||||
String id = ctx.isUpdate()
|
||||
? ctx.priorPhysicalId()
|
||||
: "topic-policy-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
r.setPhysicalId(id);
|
||||
r.getAttributes().put("Id", id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
switch (resourceType) {
|
||||
case TOPIC -> snsService.deleteTopic(physicalId, region);
|
||||
case SUBSCRIPTION -> snsService.unsubscribe(physicalId, region);
|
||||
// No entity to remove. The topics keep the last policy written, the same choice
|
||||
// SqsCfnProvisioner makes for AWS::SQS::QueuePolicy.
|
||||
case TOPIC_POLICY -> { }
|
||||
default -> throw new IllegalStateException(
|
||||
"SnsCfnProvisioner cannot delete " + resourceType);
|
||||
}
|
||||
|
||||
+165
@@ -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();
|
||||
}
|
||||
}
|
||||
+77
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -110,6 +110,7 @@ AWS::S3::Bucket S3CfnProvisioner
|
||||
AWS::S3::BucketPolicy S3CfnProvisioner
|
||||
AWS::SNS::Subscription SnsCfnProvisioner
|
||||
AWS::SNS::Topic SnsCfnProvisioner
|
||||
AWS::SNS::TopicPolicy SnsCfnProvisioner
|
||||
AWS::SQS::Queue SqsCfnProvisioner
|
||||
AWS::SQS::QueuePolicy SqsCfnProvisioner
|
||||
AWS::SSM::Parameter SsmCfnProvisioner
|
||||
|
||||
|
Reference in new issue
Block a user