From 1f4a46804c0e98a201f7bb2960908a3041c4ac52 Mon Sep 17 00:00:00 2001 From: Alessandro Lattao Date: Sun, 18 Oct 2026 20:32:04 +0200 Subject: [PATCH] fix(cloudformation): refuse a list property that a parameter or an intrinsic makes a string (#5949) * fix(cloudformation): refuse a list property that a parameter or an intrinsic makes a string The follow-up asked on #5923. The engine kept parameter values but not their types, so the Lambda provisioner's list readers could not tell a Ref to a CommaDelimitedList parameter, which the engine resolves to the comma-joined text, from a Ref to a String parameter: both read as lists, where CloudFormation refuses the second. Measured on CloudFormation (eu-west-1, 2026-10-18), Layers and Architectures of AWS::Lambda::Function: - a Ref to a CommaDelimitedList, AWS::SSM::Parameter::Value> or AWS::SSM::Parameter::Value parameter, Fn::Split, an Fn::If choosing a Ref to a list, and Ref AWS::NotificationARNs are lists; - a Ref to a String or Number parameter, Ref AWS::Region, Fn::Select, Fn::Join, Fn::Sub and an Fn::If choosing a literal string fail the template's validation with "Property [Architectures] expected type: JSONArray, found: String"; - a resource's Ref and Fn::GetAtt fail only when the resource is provisioned, with "Properties validation failed for resource Fn with message: #/Architectures: expected type: JSONArray, found: String". CloudFormationTemplateEngine now takes the declared parameter types, which executeTemplate reads from the template (stacks, change sets, stack sets and nested stacks all deploy through it), and yieldsString tells the forms of the second group. The list readers refuse such an intrinsic with the validation message, as they refuse a literal of the wrong type. The third group is left as it was: the engine cannot tell a list-valued attribute from a string one before provisioning, and a resource's own message format is not modelled. parameterType gives a declaration's Type, String when it is left out, for the new reader and for GetTemplateSummary, which had its own copy. Tests: CloudFormationTemplateEngineTest for yieldsString over every measured form; CloudFormationLambdaObjectPropertyIntegrationTest for each refused form, an Fn::If choosing a list, and a nested stack whose own parameter types decide; CloudFormationLambdaObjectPropertyTest in sdk-test-java for a String parameter through the SDK. The integration and SDK tests fail on main. * fix(cloudformation): take Fn::Base64 as a string where a list is expected Review of #5949 (Qodo). Measured on CloudFormation (eu-west-1, 2026-10-18): Architectures: {"Fn::Base64": "x86_64"} fails validation with "Property [Architectures] expected type: JSONArray, found: String", like Fn::Sub. yieldsString left it out, so the Lambda reader split the encoded text into a list and the function got an invalid architecture instead. Tests: CloudFormationTemplateEngineTest and CloudFormationLambdaObjectPropertyIntegrationTest gain the case; both fail on the previous head. --- ...loudFormationLambdaObjectPropertyTest.java | 33 +++++++ docs/services/cloudformation.md | 7 +- .../cloudformation/CloudFormationService.java | 22 ++++- .../CloudFormationTemplateEngine.java | 62 +++++++++++++ .../provisioners/LambdaCfnProvisioner.java | 5 +- ...onLambdaObjectPropertyIntegrationTest.java | 92 ++++++++++++++++++- .../CloudFormationTemplateEngineTest.java | 31 +++++++ 7 files changed, 245 insertions(+), 7 deletions(-) diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaObjectPropertyTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaObjectPropertyTest.java index 2ceaf54f2a..d6c30c5f5b 100644 --- a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaObjectPropertyTest.java +++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaObjectPropertyTest.java @@ -32,6 +32,7 @@ class CloudFormationLambdaObjectPropertyTest { private static final String LIST_STACK = TestFixtures.uniqueName("compat-cfn-object-list"); private static final String LAYERS_STACK = TestFixtures.uniqueName("compat-cfn-layers-object"); private static final String DELIMITED_STACK = TestFixtures.uniqueName("compat-cfn-comma-delimited"); + private static final String STRING_PARAMETER_STACK = TestFixtures.uniqueName("compat-cfn-string-parameter"); private static CloudFormationClient cfn; @@ -48,6 +49,7 @@ class CloudFormationLambdaObjectPropertyTest { cfn.deleteStack(request -> request.stackName(LIST_STACK)); cfn.deleteStack(request -> request.stackName(LAYERS_STACK)); cfn.deleteStack(request -> request.stackName(DELIMITED_STACK)); + cfn.deleteStack(request -> request.stackName(STRING_PARAMETER_STACK)); cfn.close(); } } @@ -111,6 +113,37 @@ class CloudFormationLambdaObjectPropertyTest { } } + /** + * Measured on AWS (eu-west-1, 2026-10-18): a {@code Ref} to a {@code String} parameter is a + * string, so a list property refuses it, though the same value from a {@code CommaDelimitedList} + * parameter is a list. + */ + @Test + @DisplayName("a list property from a String parameter fails the stack") + void aListPropertyFromAStringParameterFailsTheStack() throws InterruptedException { + cfn.createStack(request -> request.stackName(STRING_PARAMETER_STACK).templateBody(""" + { + "Parameters": {"Archs": {"Type": "String", "Default": "x86_64"}}, + "Resources": { + "Fn": { + "Type": "AWS::Lambda::Function", + "Properties": { + "Runtime": "python3.14", + "Handler": "index.handler", + "Role": "%s", + "Code": {"ZipFile": "def handler(e, c): return 'ok'"}, + "Architectures": {"Ref": "Archs"} + } + } + } + } + """.formatted(ROLE))); + assertThat(TestFixtures.awaitStackTerminal(cfn, STRING_PARAMETER_STACK, DEPLOY_TIMEOUT)) + .isEqualTo("ROLLBACK_COMPLETE"); + assertThat(reasons(STRING_PARAMETER_STACK)).anyMatch(reason -> + reason.contains("Property [Architectures] expected type: JSONArray, found: String")); + } + private static List reasons(String stackName) { if (TestFixtures.isRealAws()) { return cfn.describeEvents(request -> request.stackName(stackName)).operationEvents().stream() diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md index 258dd18ea2..8fad335608 100644 --- a/docs/services/cloudformation.md +++ b/docs/services/cloudformation.md @@ -572,7 +572,12 @@ Parameters passed to `CreateStack` / `UpdateStack` (and echoed back by `Describe before provisioning: - **`String`, `Number`, `CommaDelimitedList`, and `List<...>`** parameter types are accepted and - substituted into resource properties via `Ref`. + substituted into resource properties via `Ref`. Where a property takes a list (a Lambda function's + `Layers` or `Architectures`, a layer's `CompatibleRuntimes` or `CompatibleArchitectures`), a `Ref` to + a `CommaDelimitedList`, `List<...>` or SSM list parameter is a list, and a `Ref` to a `String` or + `Number` parameter is refused as a string, as are `Fn::Select`, `Fn::Join`, `Fn::Sub`, `Fn::Base64`, a + pseudo-parameter but `AWS::NotificationARNs`, and an `Fn::If` choosing one of these: + `Property [Architectures] expected type: JSONArray, found: String`. - **`AWS::SSM::Parameter::Value`-typed parameters** are resolved at deploy time: the value the caller supplies is treated as an SSM parameter *name*, and floci substitutes the current value of that SSM parameter into the template. This is the pattern CDK uses to pull bootstrap values (image diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java index d185e05306..fbaac39423 100644 --- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java +++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationService.java @@ -1572,6 +1572,19 @@ public class CloudFormationService implements ResourceProvider { return buildTemplateSummary(template); } + /** Each parameter the template declares, with its {@link #parameterType}. */ + private static Map parameterTypes(JsonNode template) { + Map types = new HashMap<>(); + template.path("Parameters").properties() + .forEach(entry -> types.put(entry.getKey(), parameterType(entry.getValue()))); + return types; + } + + /** A parameter declaration's {@code Type}, {@code String} when the template leaves it out. */ + private static String parameterType(JsonNode declaration) { + return declaration.hasNonNull("Type") ? declaration.get("Type").asText() : "String"; + } + private TemplateSummary buildTemplateSummary(JsonNode template) { String description = template.hasNonNull("Description") ? template.get("Description").asText() : null; String version = template.hasNonNull("AWSTemplateFormatVersion") @@ -1588,7 +1601,7 @@ public class CloudFormationService implements ResourceProvider { p.hasNonNull("Default") ? p.get("Default").asText() : null, p.path("NoEcho").asBoolean(false), p.hasNonNull("Description") ? p.get("Description").asText() : null, - p.hasNonNull("Type") ? p.get("Type").asText() : "String")); + parameterType(p))); }); } @@ -1956,6 +1969,7 @@ public class CloudFormationService implements ResourceProvider { Map givenParams = resolveDefaultParameters(template, params); stack.replaceParameters(givenParams); Map resolvedParams = resolveSsmParameters(template, givenParams, region); + Map parameterTypes = parameterTypes(template); stack.setResolvedParameters(new LinkedHashMap<>(resolvedParams)); // Resolve conditions first @@ -2006,7 +2020,8 @@ public class CloudFormationService implements ResourceProvider { name -> exports.get(accountExportKey(accountId, exportKey(region, name))), value -> dynamicReferences.resolveDynamicReferences(value, region, false), (name, output, outputRegion, roleArn) -> - resolveStackOutput(accountId, name, output, outputRegion, roleArn)); + resolveStackOutput(accountId, name, output, outputRegion, roleArn), + parameterTypes); StackResource resource = stack.getResources().get(logicalId); StackResource previousResource = resource; @@ -2174,7 +2189,8 @@ public class CloudFormationService implements ResourceProvider { name -> exports.get(accountExportKey(accountId, exportKey(region, name))), value -> dynamicReferences.resolveDynamicReferences(value, region, false), (name, output, outputRegion, roleArn) -> - resolveStackOutput(accountId, name, output, outputRegion, roleArn)); + resolveStackOutput(accountId, name, output, outputRegion, roleArn), + parameterTypes); // Resolve outputs before mutating stack/global export state, so failed updates do not // leave stale or partially registered exports behind. 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.java index b511f22283..6a1c6f9a5f 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 @@ -64,6 +64,7 @@ public class CloudFormationTemplateEngine { private final Function importValueResolver; private final UnaryOperator dynamicReferenceResolver; private final StackOutputResolver stackOutputResolver; + private final Map parameterTypes; private final List unresolvedIntrinsics = new ArrayList<>(); /** * Above zero while {@code Fn::GetStackOutput}'s arguments resolve: CloudFormation hands them on @@ -134,6 +135,27 @@ public class CloudFormationTemplateEngine { Function importValueResolver, UnaryOperator dynamicReferenceResolver, StackOutputResolver stackOutputResolver) { + this(accountId, region, stackName, stackId, parameters, physicalIds, resourceAttributes, + conditions, mappings, objectMapper, importValueResolver, dynamicReferenceResolver, + stackOutputResolver, Map.of()); + } + + /** + * @param parameterTypes each declared parameter's {@code Type}, which tells a {@code Ref} to a + * list parameter, resolved to the comma-joined text, from one to a string + * (see {@link #yieldsString}) + */ + CloudFormationTemplateEngine(String accountId, String region, String stackName, String stackId, + Map parameters, + Map physicalIds, + Map> resourceAttributes, + Map conditions, + Map mappings, + ObjectMapper objectMapper, + Function importValueResolver, + UnaryOperator dynamicReferenceResolver, + StackOutputResolver stackOutputResolver, + Map parameterTypes) { this.accountId = accountId; this.region = region; this.stackName = stackName; @@ -147,6 +169,7 @@ public class CloudFormationTemplateEngine { this.importValueResolver = importValueResolver; this.dynamicReferenceResolver = dynamicReferenceResolver; this.stackOutputResolver = stackOutputResolver; + this.parameterTypes = parameterTypes; } /** The id of the stack this engine resolves for, as {@code AWS::StackId} returns it. */ @@ -578,6 +601,45 @@ public class CloudFormationTemplateEngine { return out; } + /** + * Whether {@code node} yields a string, which CloudFormation's template validation refuses where + * a list is expected, "expected type: JSONArray, found: String" (measured, eu-west-1, + * 2026-10-18): a literal scalar, a {@code Ref} to a parameter whose type is not a list + * ({@code String}, {@code Number}, ...) or to a pseudo-parameter but + * {@code AWS::NotificationARNs}, {@code Fn::Select}, {@code Fn::Join}, {@code Fn::Sub}, + * {@code Fn::Base64}, or an {@code Fn::If} choosing one of these. A {@code Ref} to a {@code CommaDelimitedList}, + * {@code List<...>} or SSM list parameter is a list, though it resolves to the comma-joined + * text. What only provisioning can tell (a resource's {@code Ref}, {@code Fn::GetAtt}, + * {@code Fn::ImportValue}, {@code Fn::FindInMap}) is not reported here. + */ + public boolean yieldsString(JsonNode node) { + if (node == null || node.isNull() || node.isMissingNode() || node.isArray()) { + return false; + } + if (node.isValueNode()) { + return true; + } + if (node.has("Ref")) { + String name = node.get("Ref").asText(); + if (name.startsWith("AWS::")) { + return !"AWS::NotificationARNs".equals(name) && !"AWS::NoValue".equals(name); + } + String type = parameterTypes.get(name); + return type != null && !isListParameterType(type); + } + if (node.has("Fn::If")) { + return yieldsString(selectIfBranch(node.get("Fn::If"))); + } + return node.has("Fn::Select") || node.has("Fn::Join") || node.has("Fn::Sub") || node.has("Fn::Base64"); + } + + /** The parameter types whose value is a list: CommaDelimitedList, List<...> and their SSM forms. */ + private static boolean isListParameterType(String type) { + return "CommaDelimitedList".equals(type) || type.startsWith("List<") + || "AWS::SSM::Parameter::Value".equals(type) + || type.startsWith("AWS::SSM::Parameter::Value { + given().when().delete("/" + bucket + "/string.json"); + given().when().delete("/" + bucket + "/list.json"); + given().when().delete("/" + bucket); + }); + for (String type : List.of("String", "CommaDelimitedList")) { + String child = """ + {"Parameters": {"Archs": {"Type": "%s"}}, + "Resources": {"Fn": {"Type": "AWS::Lambda::Function", "Properties": { + "Runtime": "python3.14", "Handler": "index.handler", + "Role": "arn:aws:iam::000000000000:role/lambda-role", + "Code": {"ZipFile": "def handler(e, c): return 'ok'"}, + "Architectures": {"Ref": "Archs"}}}}, + "Outputs": {"Name": {"Value": {"Ref": "Fn"}}}} + """.formatted(type); + String key = "String".equals(type) ? "string.json" : "list.json"; + given().contentType("application/json").body(child) + .when().put("/" + bucket + "/" + key).then().statusCode(200); + String parent = stackName("nested-" + key.replace(".json", "")); + submit("CreateStack", parent, """ + {"Resources": {"Child": {"Type": "AWS::CloudFormation::Stack", "Properties": { + "TemplateURL": "http://localhost/%s/%s", "Parameters": {"Archs": "x86_64"}}}}} + """.formatted(bucket, key)); + assertEquals("String".equals(type) ? "ROLLBACK_COMPLETE" : "CREATE_COMPLETE", + CfnStackWaits.awaitTerminal(parent, CFN_AUTH).status(), type); + String childStack = given() + .contentType("application/x-www-form-urlencoded") + .header("Authorization", CFN_AUTH) + .formParam("Action", "DescribeStackResource") + .formParam("StackName", parent) + .formParam("LogicalResourceId", "Child") + .when() + .post("/") + .then() + .statusCode(200) + .extract().xmlPath().getString("**.find { it.name() == 'PhysicalResourceId' }"); + if ("String".equals(type)) { + assertEventReason(childStack, "Property [Architectures] expected type: JSONArray, found: String"); + } else { + given().when().get(LAMBDA + functionName(childStack) + "/configuration") + .then().statusCode(200) + .body("Architectures", contains("x86_64")); + } + } + } + private String publishLayer() throws IOException { String layerName = "cfn-lambda-list-" + Long.toString(System.nanoTime(), 36); ByteArrayOutputStream zip = new ByteArrayOutputStream(); @@ -269,8 +353,14 @@ class CloudFormationLambdaObjectPropertyIntegrationTest { } private static String template(String property) { + return template("", property); + } + + /** {@link #template(String)} after the template sections {@code sections}, each followed by a comma. */ + private static String template(String sections, String property) { return """ { + %s "Resources": { "Fn": { "Type": "AWS::Lambda::Function", @@ -285,7 +375,7 @@ class CloudFormationLambdaObjectPropertyIntegrationTest { }, "Outputs": {"Name": {"Value": {"Ref": "Fn"}}} } - """.formatted(property); + """.formatted(sections, property); } private static void submit(String action, String stackName, 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.java index ab6a56d457..7dd0ca6fa1 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 @@ -14,6 +14,7 @@ import java.util.function.Function; import java.util.function.UnaryOperator; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -242,6 +243,36 @@ class CloudFormationTemplateEngineTest { assertNull(engine().resolveJsonAttribute(mapper.createArrayNode().path("nope"))); } + /** + * Measured on CloudFormation (eu-west-1, 2026-10-18), for a Lambda function's Architectures and + * Layers: the first forms are refused as a string where a list is expected, the others are + * lists. Fn::GetAtt and Fn::ImportValue are only known when the resource is provisioned. + */ + @Test + void yieldsStringTellsTheFormsCloudFormationRefusesWhereAListIsExpected() { + Map types = Map.of("Str", "String", "Num", "Number", "Csv", "CommaDelimitedList", + "Subnets", "List", "SsmList", "AWS::SSM::Parameter::Value>", + "SsmCsv", "AWS::SSM::Parameter::Value"); + Map values = Map.of("Str", "x86_64", "Num", "1", "Csv", "x86_64", "Subnets", "subnet-a", + "SsmList", "/p", "SsmCsv", "/p"); + CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000", "us-east-1", + "my-stack", "stack/id", values, Map.of(), Map.of(), Map.of("Yes", true), Map.of(), mapper, + (Function) name -> null, null, null, types); + + for (String string : List.of("\"x86_64\"", "5", "true", "{\"Ref\": \"Str\"}", "{\"Ref\": \"Num\"}", + "{\"Ref\": \"AWS::Region\"}", "{\"Fn::Select\": [0, {\"Ref\": \"Csv\"}]}", + "{\"Fn::Join\": [\",\", {\"Ref\": \"Csv\"}]}", "{\"Fn::Sub\": \"x86_64\"}", "{\"Fn::Base64\": \"x86_64\"}", + "{\"Fn::If\": [\"Yes\", \"x86_64\", {\"Ref\": \"AWS::NoValue\"}]}")) { + assertTrue(e.yieldsString(json(string)), string); + } + for (String list : List.of("[\"x86_64\"]", "{\"Ref\": \"Csv\"}", "{\"Ref\": \"Subnets\"}", + "{\"Ref\": \"SsmList\"}", "{\"Ref\": \"SsmCsv\"}", "{\"Ref\": \"AWS::NotificationARNs\"}", + "{\"Fn::Split\": [\",\", {\"Ref\": \"Str\"}]}", "{\"Fn::If\": [\"Yes\", {\"Ref\": \"Csv\"}, [\"arm64\"]]}", + "{\"Fn::GetAtt\": [\"Queue\", \"Arn\"]}", "{\"Fn::ImportValue\": \"Archs\"}")) { + assertFalse(e.yieldsString(json(list)), list); + } + } + 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,