fix(cloudformation): don't double-encode string-form SNS RedrivePolicy and FilterPolicy (#2325)

CDK emits AWS::SNS::Subscription RedrivePolicy/FilterPolicy and Step Functions
definitions as an already-serialized JSON string via Fn::Join. resolveNode
collapses the Fn::Join to a TextNode, and toString() on that node re-quotes and
re-escapes the JSON a second time, so the stored policy is double-encoded and
SNS can no longer parse it (dead-lettering silently fails).

Add CloudFormationTemplateEngine#resolveJsonAttribute, which unwraps textual
results while keeping normal serialization for plain object/array nodes, and
use it at every site that stores a resolved node as a JSON document:
SNS FilterPolicy/RedrivePolicy, Step Functions Definition, IAM inline policy
documents, and the SQS RedrivePolicy already fixed in #1939.

Verified: GetSubscriptionAttributes returns the literal policy JSON and
regression tests mirror the SQS pattern from #1939.
This commit is contained in:
MAN$I VERMA authored and GitHub committed 2026-08-15 12:17:06 -04:00
1 parent 3cfa983479
commit c12f3fae7d
8 files changed
+182 -6

No files matched your search

@@ -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);
@@ -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-parameters
return switch (name) {
@@ -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);
}
}
@@ -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());
@@ -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 &quot;) inside the value; the stored attribute must be the literal
// policy JSON with no backslash-escape sequences.
.body(not(containsString("\\&quot;")));
}
@Test
void createStack_withCognitoUserPoolAndClient() {
String template = """
@@ -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")));
}
}
@@ -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());
}
@Test
void inlinePolicyWithoutANameFailsTheResource() {
// PolicyName is required on AWS::IAM::Role Policies. Generating one gave the same policy a
@@ -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");
}