Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): refuse a Lambda function property that is not an object (#5912)
Alessandro Lattao30d2bf03d957
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.javanew file mode 100644index 0000000000..a79f1b6133--- /dev/null+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaObjectPropertyTest.java@@ -0,0 +1,94 @@+package com.floci.test;++import org.junit.jupiter.api.AfterAll;+import org.junit.jupiter.api.BeforeAll;+import org.junit.jupiter.api.DisplayName;+import org.junit.jupiter.api.Test;+import software.amazon.awssdk.services.cloudformation.CloudFormationClient;+import software.amazon.awssdk.services.cloudformation.model.OperationEvent;+import software.amazon.awssdk.services.cloudformation.model.StackEvent;++import java.time.Duration;+import java.util.List;++import static org.assertj.core.api.Assertions.assertThat;++/**+ * An object property of AWS::Lambda::Function that is not an object, through the CloudFormation SDK+ * client. Measured on AWS (eu-west-1, 2026-10-18): the stack fails before the function is touched,+ * "Property [VpcConfig] expected type: JSONObject, found: String" ("found: JSONArray" for a list).+ * AWS reports it from its pre-deployment validation, read through DescribeEvents; Floci, which+ * does not model that validation, reports the same message on the resource's failed event.+ */+@DisplayName("CloudFormation Lambda object properties")+class CloudFormationLambdaObjectPropertyTest {++ private static final String ROLE = "arn:aws:iam::000000000000:role/cfn-lambda-role";+ private static final Duration DEPLOY_TIMEOUT = Duration.ofSeconds(30);+ private static final String STRING_STACK = TestFixtures.uniqueName("compat-cfn-object-string");+ private static final String LIST_STACK = TestFixtures.uniqueName("compat-cfn-object-list");++ private static CloudFormationClient cfn;++ @BeforeAll+ static void setup() {+ cfn = TestFixtures.cloudFormationClient();+ }++ @AfterAll+ static void cleanup() {+ if (cfn != null) {+ // DeleteStack answers for a stack that is gone too, so a failure here is a real one.+ cfn.deleteStack(request -> request.stackName(STRING_STACK));+ cfn.deleteStack(request -> request.stackName(LIST_STACK));+ cfn.close();+ }+ }++ @Test+ @DisplayName("a VpcConfig that is a string or a DeadLetterConfig that is a list fails the stack")+ void anObjectPropertyThatIsNotAnObjectFailsTheStack() throws InterruptedException {+ cfn.createStack(request -> request.stackName(STRING_STACK).templateBody(template("\"VpcConfig\": \"x\"")));+ assertThat(TestFixtures.awaitStackTerminal(cfn, STRING_STACK, DEPLOY_TIMEOUT)).isEqualTo("ROLLBACK_COMPLETE");+ assertThat(reasons(STRING_STACK)).anyMatch(reason ->+ reason.contains("Property [VpcConfig] expected type: JSONObject, found: String"));++ cfn.createStack(request -> request.stackName(LIST_STACK)+ .templateBody(template("\"DeadLetterConfig\": [\"x\"]")));+ assertThat(TestFixtures.awaitStackTerminal(cfn, LIST_STACK, DEPLOY_TIMEOUT)).isEqualTo("ROLLBACK_COMPLETE");+ assertThat(reasons(LIST_STACK)).anyMatch(reason ->+ reason.contains("Property [DeadLetterConfig] expected type: JSONObject, found: JSONArray"));+ }++ private static List<String> reasons(String stackName) {+ if (TestFixtures.isRealAws()) {+ return cfn.describeEvents(request -> request.stackName(stackName)).operationEvents().stream()+ .map(OperationEvent::validationStatusReason)+ .filter(reason -> reason != null)+ .toList();+ }+ return cfn.describeStackEvents(request -> request.stackName(stackName)).stackEvents().stream()+ .map(StackEvent::resourceStatusReason)+ .filter(reason -> reason != null)+ .toList();+ }++ private static String template(String property) {+ return """+ {+ "Resources": {+ "Fn": {+ "Type": "AWS::Lambda::Function",+ "Properties": {+ "Runtime": "python3.14",+ "Handler": "index.handler",+ "Role": "%s",+ "Code": {"ZipFile": "def handler(e, c): return 'ok'"},+ %s+ }+ }+ }+ }+ """.formatted(ROLE, property);+ }+}diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.javaindex d7d19d1b9a..99aca244c3 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/LambdaCfnProvisioner.java@@ -818,14 +818,27 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {return values;}+ /**+ * The object property {@code source}, or {@code defaultValue} when the template leaves it out,+ * {@code Ref: AWS::NoValue} directly or through {@code Fn::If} included. Any other value is+ * refused before the function is touched, with the message CloudFormation's property validation+ * gives (measured in eu-west-1, 2026-10-18), where a number or a boolean reads as a String too.+ */private Map<String, Object> resolveMapOrDefault(JsonNode props, String source,CloudFormationTemplateEngine engine,Map<String, Object> defaultValue) {if (props == null || !props.has(source) || props.get(source).isNull()) {return defaultValue;}- JsonNode resolved = engine.resolveNode(props.get(source));- return resolved != null && resolved.isObject() ? jsonObjectToMap(resolved) : defaultValue;+ JsonNode resolved = engine.resolveNodeOmittingNoValue(props.get(source));+ if (resolved == null || resolved.isNull() || resolved.isMissingNode()) {+ return defaultValue;+ }+ if (!resolved.isObject()) {+ throw new AwsException("ValidationError", "Property [" + source + "] expected type: JSONObject, found: "+ + (resolved.isArray() ? "JSONArray" : "String"), 400);+ }+ return jsonObjectToMap(resolved);}private static Map<String, Object> mapWithNullValue(String key) {diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaObjectPropertyIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaObjectPropertyIntegrationTest.javanew file mode 100644index 0000000000..9fdd59c0d0--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaObjectPropertyIntegrationTest.java@@ -0,0 +1,166 @@+package io.github.hectorvent.floci.services.cloudformation;++import io.github.hectorvent.floci.testing.PartitionCleanup;+import io.quarkus.test.junit.QuarkusTest;+import io.restassured.specification.RequestSpecification;+import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.extension.RegisterExtension;++import static io.restassured.RestAssured.given;+import static org.hamcrest.Matchers.containsString;+import static org.hamcrest.Matchers.equalTo;+import static org.junit.jupiter.api.Assertions.assertEquals;+import static org.junit.jupiter.api.Assertions.assertNotEquals;++/**+ * An object property of {@code AWS::Lambda::Function} that is not an object. Measured on AWS+ * (eu-west-1, 2026-10-18): a VpcConfig, DeadLetterConfig or LoggingConfig that is a string, a number,+ * a boolean or a list fails the stack before the function is touched, on create and on update,+ * with "Property [VpcConfig] expected type: JSONObject, found: String" ("found: JSONArray" for a+ * list). It is never read as an absent property, which would reset the function's setting.+ */+@QuarkusTest+class CloudFormationLambdaObjectPropertyIntegrationTest {++ private static final String CFN_AUTH =+ "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";+ private static final String LAMBDA = "/2015-03-31/functions/";++ @RegisterExtension+ final PartitionCleanup cleanup = new PartitionCleanup();++ @Test+ void aPropertyThatIsNotAnObjectFailsTheCreate() {+ String vpc = stackName("vpc");+ submit("CreateStack", vpc, template(",\"VpcConfig\": 5"));+ assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(vpc, CFN_AUTH).status());+ assertEventReason(vpc, "Property [VpcConfig] expected type: JSONObject, found: String");++ String deadLetter = stackName("dlq");+ submit("CreateStack", deadLetter, template(",\"DeadLetterConfig\": [\"x\"]"));+ assertEquals("ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(deadLetter, CFN_AUTH).status());+ assertEventReason(deadLetter, "Property [DeadLetterConfig] expected type: JSONObject, found: JSONArray");+ }++ @Test+ void aPropertyThatIsNotAnObjectFailsTheUpdateAndKeepsTheSetting() {+ String stack = stackName("update");+ submit("CreateStack", stack, template(",\"TracingConfig\": {\"Mode\": \"Active\"}"));+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());+ String function = functionName(stack);++ submit("UpdateStack", stack, template(",\"TracingConfig\": \"Active\""));+ assertNotEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stack, CFN_AUTH).status());+ assertEventReason(stack, "Property [TracingConfig] expected type: JSONObject, found: String");+ given()+ .when()+ .get(LAMBDA + function + "/configuration")+ .then()+ .statusCode(200)+ .body("TracingConfig.Mode", equalTo("Active"));+ }++ /**+ * Measured on AWS (eu-west-1, 2026-10-18): {@code Ref: AWS::NoValue}, directly or chosen by+ * {@code Fn::If}, leaves the property out, and the stack is created.+ */+ @Test+ void aPropertyLeftOutWithNoValueIsNotRefused() {+ String direct = stackName("novalue");+ submit("CreateStack", direct, template(+ ",\"VpcConfig\": {\"Ref\": \"AWS::NoValue\"}, \"TracingConfig\": {\"Ref\": \"AWS::NoValue\"}"));+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(direct, CFN_AUTH).status());++ String conditional = stackName("novalue-if");+ submit("CreateStack", conditional, """+ {+ "Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},+ "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'"},+ "DeadLetterConfig": {"Fn::If": ["Never",+ {"TargetArn": "arn:aws:sqs:us-east-1:000000000000:none"}, {"Ref": "AWS::NoValue"}]}+ }+ }+ }+ }+ """);+ assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(conditional, CFN_AUTH).status());+ }++ private String stackName(String purpose) {+ String name = "cfn-lambda-object-" + purpose + "-" + Long.toString(System.nanoTime(), 36);+ cleanup.register(() -> {+ submit("DeleteStack", name, null);+ CfnStackWaits.awaitStackDeleted(name, CFN_AUTH);+ });+ return name;+ }++ private static String template(String property) {+ return """+ {+ "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'"}+ %s+ }+ }+ },+ "Outputs": {"Name": {"Value": {"Ref": "Fn"}}}+ }+ """.formatted(property);+ }++ private static void submit(String action, String stackName, String template) {+ RequestSpecification request = given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", action)+ .formParam("StackName", stackName);+ if (template != null) {+ request.formParam("TemplateBody", template);+ }+ request+ .when()+ .post("/")+ .then()+ .statusCode(200);+ }++ private static void assertEventReason(String stackName, String reason) {+ given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStackEvents")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .body(containsString(reason));+ }++ private static String functionName(String stackName) {+ return given()+ .contentType("application/x-www-form-urlencoded")+ .header("Authorization", CFN_AUTH)+ .formParam("Action", "DescribeStacks")+ .formParam("StackName", stackName)+ .when()+ .post("/")+ .then()+ .statusCode(200)+ .extract().xmlPath().getString("**.find { it.name() == 'OutputValue' }");+ }+}