Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): resolve FunctionResponseTypes through whole-property intrinsics (#2996)
Olamide Kosile9eb4fc82cd2a
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 19a68b5bf1..7d0cf85cba 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@@ -120,8 +120,17 @@ public class CloudFormationTemplateEngine {return node;}if (node.isObject()) {+ if (node.has("Fn::If")) {+ // Unlike the other intrinsics below, Fn::If's two branches can be any JSON shape+ // (array, object, or scalar) - it just forwards one of them verbatim. Collapsing it+ // through resolve() like the scalar-only intrinsics would stringify a chosen array or+ // object instead of preserving it, so a conditional list (e.g. a Tags property) reads+ // as unresolvable everywhere a caller checks isArray() on the result.+ JsonNode branch = selectIfBranch(node.get("Fn::If"));+ return branch == null ? TextNode.valueOf("") : resolveNode(branch);+ }if (node.has("Ref") || node.has("Fn::Sub") || node.has("Fn::Join") ||- node.has("Fn::Select") || node.has("Fn::If") || node.has("Fn::Base64") ||+ node.has("Fn::Select") || node.has("Fn::Base64") ||node.has("Fn::GetAtt") || node.has("Fn::ImportValue") || node.has("Fn::Split") ||node.has("Fn::GetAZs") || node.has("Fn::Cidr") || node.has("Fn::FindInMap")) {return TextNode.valueOf(resolve(node));@@ -261,8 +270,8 @@ public class CloudFormationTemplateEngine {/*** Resolves a node that represents a list — a literal array, a list-producing intrinsic- * ({@code Fn::GetAZs}, {@code Fn::Cidr}, {@code Fn::Split}), or a comma-delimited scalar- * (e.g. a {@code Ref} to a {@code List<>} parameter).+ * ({@code Fn::GetAZs}, {@code Fn::Cidr}, {@code Fn::Split}), an {@code Fn::If} choosing between+ * two such lists, or a comma-delimited scalar (e.g. a {@code Ref} to a {@code List<>} parameter).*/private List<String> resolveList(JsonNode node) {List<String> out = new ArrayList<>();@@ -273,6 +282,14 @@ public class CloudFormationTemplateEngine {return resolveListElements(node);}if (node.isObject()) {+ if (node.has("Fn::If")) {+ // Fn::If's branch can itself be any of the shapes this method already handles+ // (literal array, Fn::Split, ...), so recurse into it rather than falling through+ // to the scalar branch below, which would stringify a list-shaped branch instead+ // of splitting it.+ JsonNode branch = selectIfBranch(node.get("Fn::If"));+ return branch == null ? out : resolveList(branch);+ }if (node.has("Fn::GetAZs")) {return resolveAvailabilityZones(node.get("Fn::GetAZs"));}@@ -282,14 +299,6 @@ public class CloudFormationTemplateEngine {if (node.has("Fn::Split")) {return resolveSplit(node.get("Fn::Split"));}- if (node.has("Fn::If")) {- JsonNode ifNode = node.get("Fn::If");- if (ifNode.isArray() && ifNode.size() >= 3) {- String conditionName = ifNode.get(0).asText();- boolean condValue = conditions.getOrDefault(conditionName, false);- return resolveList(condValue ? ifNode.get(1) : ifNode.get(2));- }- }}String scalar = resolve(node);if (!scalar.isEmpty()) {@@ -448,12 +457,19 @@ public class CloudFormationTemplateEngine {}private String resolveIf(JsonNode ifNode) {+ JsonNode branch = selectIfBranch(ifNode);+ return branch == null ? "" : resolve(branch);+ }++ /** Picks Fn::If's true/false branch without resolving it further, so the caller decides+ * whether to collapse it to a scalar ({@link #resolve}) or preserve its shape ({@link #resolveNode}). */+ private JsonNode selectIfBranch(JsonNode ifNode) {if (!ifNode.isArray() || ifNode.size() < 3) {- return "";+ return null;}String conditionName = ifNode.get(0).asText();boolean condValue = conditions.getOrDefault(conditionName, false);- return resolve(condValue ? ifNode.get(1) : ifNode.get(2));+ return condValue ? ifNode.get(1) : ifNode.get(2);}private String resolveGetAtt(JsonNode getAtt) {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 16df4daef2..6f1fa38818 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@@ -4769,6 +4769,90 @@ class CloudFormationIntegrationTest {.statusCode(404);}+ @Test+ void createStack_lambdaEventSourceMappingWithConditionalFunctionResponseTypes() throws Exception {+ // github.com/floci-io/floci/issues/2848 follow-up (Greptile review on the fix): a+ // whole-property intrinsic such as Fn::If must still resolve FunctionResponseTypes, not+ // just a plain array. resolveStringList (via the engine's resolveList) now resolves+ // Fn::If, Fn::Split and a CommaDelimitedList Ref, and drops any resulting blank entries.+ String stackName = "cfn-esm-conditional-stack";+ String funcName = "cfn-esm-conditional-func";+ String queueName = "cfn-esm-conditional-queue";++ String template = """+ {+ "Parameters": {+ "ReportBatchFailures": { "Type": "String", "Default": "true" }+ },+ "Conditions": {+ "ShouldReportBatchFailures": { "Fn::Equals": [{ "Ref": "ReportBatchFailures" }, "true"] }+ },+ "Resources": {+ "MyQueue": {+ "Type": "AWS::SQS::Queue",+ "Properties": { "QueueName": "%s" }+ },+ "MyFunction": {+ "Type": "AWS::Lambda::Function",+ "Properties": {+ "FunctionName": "%s",+ "Runtime": "nodejs20.x",+ "Handler": "index.handler",+ "Role": "arn:aws:iam::000000000000:role/lambda-role",+ "Code": {+ "ZipFile": "exports.handler = async (e) => ({ statusCode: 200 });"+ }+ }+ },+ "MyESM": {+ "Type": "AWS::Lambda::EventSourceMapping",+ "Properties": {+ "FunctionName": { "Ref": "MyFunction" },+ "EventSourceArn": { "Fn::GetAtt": ["MyQueue", "Arn"] },+ "BatchSize": 5,+ "FunctionResponseTypes": {+ "Fn::If": ["ShouldReportBatchFailures", ["ReportBatchItemFailures"], []]+ }+ }+ }+ }+ }+ """.formatted(queueName, funcName);++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "CreateStack")+ .formParam("StackName", stackName)+ .formParam("TemplateBody", template)+ .when()+ .post("/")+ .then()+ .statusCode(200);++ given()+ .contentType("application/x-www-form-urlencoded")+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));++ String esmJson = given()+ .when()+ .get("/2015-03-31/event-source-mappings?FunctionName=" + funcName)+ .then()+ .statusCode(200)+ .extract().body().asString();++ JsonNode esmList = OBJECT_MAPPER.readTree(esmJson);+ JsonNode responseTypes = esmList.path("EventSourceMappings").get(0).path("FunctionResponseTypes");+ assertTrue(responseTypes.isArray() && responseTypes.size() == 1+ && "ReportBatchItemFailures".equals(responseTypes.get(0).asText()),+ "expected the Fn::If-selected branch to carry through but was: " + responseTypes);+ }+@Testvoid createStack_lambdaEventSourceMappingKafka() throws Exception {String stackName = "cfn-esm-kafka-stack";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 cf14c2a7f1..eace3c85e0 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@@ -4,11 +4,13 @@ import com.fasterxml.jackson.databind.JsonNode;import com.fasterxml.jackson.databind.ObjectMapper;import org.junit.jupiter.api.Test;+import java.util.List;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;+import static org.junit.jupiter.api.Assertions.assertTrue;class CloudFormationTemplateEngineTest {@@ -102,6 +104,128 @@ class CloudFormationTemplateEngineTest {assertNull(engine().resolveJsonAttribute(mapper.createArrayNode().path("nope")));}+ private CloudFormationTemplateEngine engineWithCondition(String name, boolean value) {+ return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",+ "stack/id", Map.of(), Map.of(), Map.of(), Map.of(name, value), Map.of(), mapper,+ (Function<String, String>) n -> null);+ }++ @Test+ void resolveFnIfPicksTheTrueBranchScalar() {+ assertEquals("prod", engineWithCondition("UseProd", true)+ .resolve(json("{\"Fn::If\": [\"UseProd\", \"prod\", \"dev\"]}")));+ }++ @Test+ void resolveFnIfPicksTheFalseBranchScalar() {+ assertEquals("dev", engineWithCondition("UseProd", false)+ .resolve(json("{\"Fn::If\": [\"UseProd\", \"prod\", \"dev\"]}")));+ }++ @Test+ void resolveNodePreservesArrayShapeThroughFnIf() {+ // github.com/floci-io/floci/issues/2396 (PR #2796 review): resolveNode treated Fn::If the+ // same as every other intrinsic and collapsed it to a stringified scalar, so a conditional+ // array (e.g. a Tags property choosing between two tag lists) resolved to text instead of+ // the chosen branch's actual array - every caller checking isArray() on the result then+ // read a resolvable conditional list as unresolvable.+ JsonNode ifNode = json("""+ {"Fn::If": ["UseProdTags",+ [{"Key": "Env", "Value": "prod"}],+ [{"Key": "Env", "Value": "dev"}]]}+ """);++ JsonNode trueResolved = engineWithCondition("UseProdTags", true).resolveNode(ifNode);+ assertTrue(trueResolved.isArray(), "true branch must resolve to a real array: " + trueResolved);+ assertEquals("prod", trueResolved.get(0).get("Value").asText());++ JsonNode falseResolved = engineWithCondition("UseProdTags", false).resolveNode(ifNode);+ assertTrue(falseResolved.isArray(), "false branch must resolve to a real array: " + falseResolved);+ assertEquals("dev", falseResolved.get(0).get("Value").asText());+ }++ @Test+ void resolveNodeResolvesIntrinsicsInsideTheChosenFnIfBranch() {+ // The chosen branch is passed back through resolveNode, not returned verbatim, so a nested+ // intrinsic inside it (e.g. a Ref-valued tag) still resolves.+ JsonNode ifNode = json("""+ {"Fn::If": ["UseProdTags", [{"Key": "Env", "Value": {"Ref": "AWS::Region"}}], []]}+ """);++ JsonNode resolved = engineWithCondition("UseProdTags", true).resolveNode(ifNode);++ assertEquals("us-east-1", resolved.get(0).get("Value").asText());+ }++ private CloudFormationTemplateEngine engineWithParameter(String name, String value) {+ return new CloudFormationTemplateEngine("000000000000", "us-east-1", "my-stack",+ "stack/id", Map.of(name, value), Map.of(), Map.of(), Map.of(), Map.of(), mapper,+ (Function<String, String>) n -> null);+ }++ // github.com/floci-io/floci/issues/2848 (Greptile review on the follow-up fix): "List+ // intrinsics remain scalar" - resolveNode's Fn::If fix alone does not make Fn::Split or a Ref+ // to a CommaDelimitedList parameter list-shaped, since resolveNode never split anything to+ // begin with. resolveStringList already handled Fn::Split and comma-delimited scalars+ // correctly (and drops blank entries, unlike the private resolveList it delegates to); it+ // only needed Fn::If added, which is what these exercise.++ @Test+ void resolveStringListSplitsFnSplitWithItsActualDelimiter() {+ assertEquals(List.of("a", "b", "c"),+ engine().resolveStringList(json("{\"Fn::Split\": [\"|\", \"a|b|c\"]}")));+ }++ @Test+ void resolveStringListSplitsACommaDelimitedListParameterRef() {+ assertEquals(List.of("a", "b", "c"),+ engineWithParameter("Csv", "a,b,c").resolveStringList(json("{\"Ref\": \"Csv\"}")));+ }++ @Test+ void resolveStringListResolvesFnIfChoosingBetweenTwoFnSplitLists() {+ // The delimiter is deliberately not a comma: falling through to the pre-existing+ // scalar-then-comma-split fallback (rather than actually recursing into the Fn::Split+ // branch) would return the whole unsplit "a|b|c" source as a single element instead of+ // the three pipe-split ones, so this only passes if resolveList's own Fn::If handling+ // is what runs.+ JsonNode node = json("""+ {"Fn::If": ["UseReportBatch",+ {"Fn::Split": ["|", "a|b|c"]},+ {"Fn::Split": ["|", "x|y"]}]}+ """);++ assertEquals(List.of("a", "b", "c"),+ engineWithCondition("UseReportBatch", true).resolveStringList(node));+ assertEquals(List.of("x", "y"),+ engineWithCondition("UseReportBatch", false).resolveStringList(node));+ }++ @Test+ void resolveStringListResolvesFnIfChoosingBetweenACommaDelimitedRefAndALiteralArray() {+ JsonNode node = json("{\"Fn::If\": [\"UseParam\", {\"Ref\": \"Csv\"}, [\"fallback\"]]}");++ CloudFormationTemplateEngine trueEngine = new CloudFormationTemplateEngine(+ "000000000000", "us-east-1", "my-stack", "stack/id",+ Map.of("Csv", "x,y"), Map.of(), Map.of(), Map.of("UseParam", true), Map.of(), mapper,+ (Function<String, String>) n -> null);+ assertEquals(List.of("x", "y"), trueEngine.resolveStringList(node));+ }++ @Test+ void resolveStringListDropsAConditionalElementThatResolvesToNoValue() {+ // github.com/floci-io/floci/pull/2996 (Greptile review): a list element that resolves to+ // AWS::NoValue must be omitted, not forwarded as an invalid empty-string list entry. This+ // is exactly why FunctionResponseTypes must go through resolveStringList (which drops+ // blanks) rather than the private resolveList it delegates to (which keeps them).+ JsonNode node = json("""+ ["ReportBatchItemFailures", {"Fn::If": ["UseExtra", "ExtraType", {"Ref": "AWS::NoValue"}]}]+ """);++ assertEquals(List.of("ReportBatchItemFailures"),+ engineWithCondition("UseExtra", false).resolveStringList(node));+ }+@Testvoid resolveStringListSplitsListValuedIntrinsicNode() {CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000",