Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): don't double-encode string-form SNS RedrivePolicy and FilterPolicy (#2325)
MAN$I VERMAc12f3fae7d19
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 b308d54c7d..d7d5cbaea3 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@@ -1768,7 +1768,7 @@ public class CloudFormationResourceProvisioner {Map<String, String> attributes = new HashMap<>();if (props.has("FilterPolicy") && !props.path("FilterPolicy").isNull()) {- attributes.put("FilterPolicy", engine.resolveNode(props.path("FilterPolicy")).toString());+ attributes.put("FilterPolicy", engine.resolveJsonAttribute(props.path("FilterPolicy")));}if (props.has("FilterPolicyScope")) {attributes.put("FilterPolicyScope", engine.resolve(props.path("FilterPolicyScope")));@@ -1777,7 +1777,7 @@ public class CloudFormationResourceProvisioner {attributes.put("RawMessageDelivery", engine.resolve(props.path("RawMessageDelivery")));}if (props.has("RedrivePolicy") && !props.path("RedrivePolicy").isNull()) {- attributes.put("RedrivePolicy", engine.resolveNode(props.path("RedrivePolicy")).toString());+ attributes.put("RedrivePolicy", engine.resolveJsonAttribute(props.path("RedrivePolicy")));}var sub = snsService.subscribe(topicArn, protocol, endpoint, region, attributes);@@ -4508,7 +4508,7 @@ public class CloudFormationResourceProvisioner {if (hasDefinitionString) {definition = resolveOptional(props, "DefinitionString", engine);} else if (hasDefinition) {- definition = engine.resolveNode(props.get("Definition")).toString();+ definition = engine.resolveJsonAttribute(props.get("Definition"));} else {JsonNode location = engine.resolveNode(props.get("DefinitionS3Location"));String bucket = location.path("Bucket").asText(null);diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.javaindex 17446a5143..22e0fa0c9b 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngine.java@@ -145,6 +145,26 @@ public class CloudFormationTemplateEngine {return node;}+ /**+ * Resolves a node that must be stored as a JSON document (SNS/SQS RedrivePolicy and+ * FilterPolicy, Step Functions definitions, IAM policy documents) to its string form.+ * <p>+ * resolveNode collapses intrinsics such as Fn::Join into a {@link TextNode}. Calling+ * {@code toString()} on that node re-quotes and re-escapes the already-serialized JSON+ * (e.g. CDK's Fn::Join-spliced RedrivePolicy), so the value is double-encoded and the+ * downstream service can no longer parse it. Unwrapping textual results preserves the+ * literal JSON while non-textual nodes (plain objects) keep the normal serialization.+ *+ * @see <a href="https://github.com/floci-io/floci/issues/2317">#2317</a>+ */+ public String resolveJsonAttribute(JsonNode node) {+ JsonNode resolved = resolveNode(node);+ if (resolved == null || resolved.isNull() || resolved.isMissingNode()) {+ return null;+ }+ return resolved.isTextual() ? resolved.asText() : resolved.toString();+ }+private String resolveRef(String name) {// Pseudo-parametersreturn switch (name) {diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.javaindex 26a34d26ef..a3aa5f61d1 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisioner.java@@ -166,7 +166,7 @@ public class IamRoleCfnProvisioner implements CfnResourceProvisioner {+ " has no PolicyDocument.", 400);}iamService.putRolePolicy(resolvedRoleName, policyName,- ctx.engine().resolveNode(document).toString());+ ctx.engine().resolveJsonAttribute(document));inlineWrittenByThisAttempt.add(policyName);}}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisioner.javaindex 1967457c12..0a79f4cbbe 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisioner.java@@ -85,8 +85,7 @@ public class SqsCfnProvisioner implements CfnResourceProvisioner {// CDK commonly emits RedrivePolicy as an already-serialized string via Fn::Join,// which resolveNode collapses to a TextNode — unwrap it instead of calling// toString(), which would JSON-re-encode (quote/escape) the string a second time.- JsonNode redrivePolicy = ctx.engine().resolveNode(props.path("RedrivePolicy"));- attrs.put("RedrivePolicy", redrivePolicy.isTextual() ? redrivePolicy.asText() : redrivePolicy.toString());+ attrs.put("RedrivePolicy", ctx.engine().resolveJsonAttribute(props.path("RedrivePolicy")));}}Queue queue = sqsService.createQueue(queueName, attrs, ctx.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.javaindex 74d1da0649..240a7ea64a 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@@ -5249,6 +5249,99 @@ class CloudFormationIntegrationTest {.body(containsString("cfn-sub-policies-dlq"));}+ @Test+ void createStack_snsSubscriptionKeepsSerializedStringRedrivePolicyAndFilterPolicy() {+ // Reproduces #2317: CDK emits RedrivePolicy / FilterPolicy via Fn::Join as an+ // already-serialized JSON string. resolveNode collapses the Fn::Join to a TextNode, and a+ // naive toString() re-quotes/escapes the JSON a second time — the value SNS stores (and+ // GetSubscriptionAttributes returns) must be the literal policy JSON instead.+ String stackName = "cfn-sns-sub-string-policies-stack";+ String template = """+ {+ "Resources": {+ "MyTopic": {+ "Type": "AWS::SNS::Topic",+ "Properties": {+ "TopicName": "cfn-sub-string-policies-topic"+ }+ },+ "MyQueue": {+ "Type": "AWS::SQS::Queue",+ "Properties": {+ "QueueName": "cfn-sub-string-policies-queue"+ }+ },+ "MyDLQ": {+ "Type": "AWS::SQS::Queue",+ "Properties": {+ "QueueName": "cfn-sub-string-policies-dlq"+ }+ },+ "MySubscription": {+ "Type": "AWS::SNS::Subscription",+ "Properties": {+ "TopicArn": {"Ref": "MyTopic"},+ "Protocol": "sqs",+ "Endpoint": {"Fn::GetAtt": ["MyQueue", "Arn"]},+ "FilterPolicy": {+ "Fn::Join": ["", [+ "{\\"store\\":[\\"shoes\\"]}"+ ]]+ },+ "RedrivePolicy": {+ "Fn::Join": ["", [+ "{\\"deadLetterTargetArn\\":\\"",+ {"Fn::GetAtt": ["MyDLQ", "Arn"]},+ "\\"}"+ ]]+ }+ }+ }+ }+ }+ """;++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ String resourcesXml = given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStackResources")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().asString();++ String subArn = physicalIdByLogicalId(resourcesXml, "MySubscription");++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "GetSubscriptionAttributes")+ .formParam("SubscriptionArn", subArn)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("FilterPolicy"))+ .body(containsString("store"))+ .body(containsString("RedrivePolicy"))+ .body(containsString("deadLetterTargetArn"))+ .body(containsString("arn:aws:sqs:us-east-1:000000000000:cfn-sub-string-policies-dlq"))+ // A double-encoded value would come back with the JSON-escaped quote (backslash before+ // the XML-escaped ") inside the value; the stored attribute must be the literal+ // policy JSON with no backslash-escape sequences.+ .body(not(containsString("\\"")));+ }+@Testvoid createStack_withCognitoUserPoolAndClient() {String template = """diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.javaindex 666682b142..9e7b5a077a 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationTemplateEngineTest.java@@ -8,6 +8,7 @@ import java.util.Map;import java.util.function.Function;import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNull;class CloudFormationTemplateEngineTest {@@ -58,4 +59,33 @@ class CloudFormationTemplateEngineTest {assertEquals("10.0.2.0/24",engine().resolve(json("{\"Fn::Select\": [2, {\"Fn::Cidr\": [\"10.0.0.0/16\", 4, 8]}]}")));}++ @Test+ void resolveJsonAttributeUnwrapsAlreadySerializedStringFromFnJoin() {+ // Reproduces #2317: CDK emits RedrivePolicy / FilterPolicy / Definition as an Fn::Join+ // that resolveNode collapses to a TextNode. toString() on that node re-quotes and+ // re-escapes the JSON a second time; resolveJsonAttribute must pass the literal string+ // through instead.+ String serialized = "{\"deadLetterTargetArn\":\"arn:aws:sqs:us-east-1:000000000000:dlq\"}";+ String escaped = serialized.replace("\"", "\\\"");+ String joined = "{\"Fn::Join\":[\"\",[\"" + escaped + "\"]]}";++ assertEquals(serialized, engine().resolveJsonAttribute(json(joined)));+ }++ @Test+ void resolveJsonAttributeSerializesPlainObjectNode() {+ // The object form keeps working: a template object with a resolved intrinsic must still+ // reach the service as the JSON string it parses.+ assertEquals(+ "{\"deadLetterTargetArn\":\"Dlq.Arn\"}",+ engine().resolveJsonAttribute(json(+ "{\"deadLetterTargetArn\":{\"Fn::GetAtt\":[\"Dlq\",\"Arn\"]}}")));+ }++ @Test+ void resolveJsonAttributeReturnsNullForMissingOrNullNode() {+ assertNull(engine().resolveJsonAttribute(json("null")));+ assertNull(engine().resolveJsonAttribute(mapper.createArrayNode().path("nope")));+ }}diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.javaindex 54f4558eab..08ad580f28 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/IamRoleCfnProvisionerTest.java@@ -49,6 +49,10 @@ class IamRoleCfnProvisionerTest {return node == null ? null : node.asText();});when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));+ when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> {+ JsonNode node = inv.getArgument(0);+ return node != null && node.isTextual() ? node.asText() : node.toString();+ });return new ProvisionContext(engine, "us-east-1", ACCOUNT_ID, "test-stack");}@@ -99,6 +103,32 @@ class IamRoleCfnProvisionerTest {order.verify(iam).putRolePolicy("app-role", "log-write", EMPTY_TRUST);}+ @Test+ void inlinePolicyPassesThroughAlreadySerializedPolicyDocumentString() {+ // Same failure mode as #2317: CDK can emit an inline PolicyDocument as an+ // already-serialized JSON string (e.g. via Fn::Join). resolveNode collapses that to a+ // TextNode whose toString() re-quotes/escapes the JSON; the policy must be stored verbatim.+ stubCreate("app-role");+ StackResource r = resource();+ String serialized = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\","+ + "\"Action\":\"s3:GetObject\",\"Resource\":\"*\"}]}";+ JsonNode props = props(String.format("""+ {+ "RoleName": "app-role",+ "Policies": [+ {"PolicyName": "serialized-doc",+ "PolicyDocument": "%s"}+ ]+ }+ """, serialized.replace("\"", "\\\"")));++ provisioner.provision(r, props, ctx());+ @SuppressWarnings("unchecked")+ ArgumentCaptor<String> docCaptor = ArgumentCaptor.forClass(String.class);+ verify(iam).putRolePolicy(eq("app-role"), eq("serialized-doc"), docCaptor.capture());+ assertEquals(serialized, docCaptor.getValue());+ }+@Testvoid inlinePolicyWithoutANameFailsTheResource() {// PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same policy adiff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisionerTest.javaindex bc64f91943..d6cb5173f1 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/SqsCfnProvisionerTest.java@@ -59,6 +59,10 @@ class SqsCfnProvisionerTest {});return resolved;});+ when(engine.resolveJsonAttribute(any())).thenAnswer(inv -> {+ JsonNode resolved = engine.resolveNode(inv.getArgument(0));+ return resolved != null && resolved.isTextual() ? resolved.asText() : resolved.toString();+ });return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");}