Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

fix(cloudformation): pass a function's LoggingConfig to Lambda (#5902)

Alessandro Lattao63af5cd299ca
diff --git a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
index 79412b78b6..dc696db6c4 100644
--- a/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
+++ b/compatibility-tests/sdk-test-java/src/main/java/com/floci/test/TestFixtures.java
@@ -930,6 +930,24 @@ public final class TestFixtures {
}
}
+ /** The stack's status once it is no longer {@code *_IN_PROGRESS}, or its last status at the timeout. */
+ public static String awaitStackTerminal(CloudFormationClient cfn, String stackName, Duration timeout)
+ throws InterruptedException {
+ long deadline = System.nanoTime() + timeout.toNanos();
+ while (true) {
+ String status = cfn.describeStacks(request -> request.stackName(stackName))
+ .stacks().get(0).stackStatusAsString();
+ if (!status.endsWith("_IN_PROGRESS")) {
+ return status;
+ }
+ long remainingNanos = deadline - System.nanoTime();
+ if (remainingNanos <= 0) {
+ return status;
+ }
+ Thread.sleep(Math.min(500, Math.max(1, Duration.ofNanos(remainingNanos).toMillis())));
+ }
+ }
+
public static GlueClient glueClient() {
return GlueClient.builder()
.endpointOverride(ENDPOINT)
diff --git a/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaLoggingConfigTest.java b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaLoggingConfigTest.java
new file mode 100644
index 0000000000..61a8b609e5
--- /dev/null
+++ b/compatibility-tests/sdk-test-java/src/test/java/com/floci/test/CloudFormationLambdaLoggingConfigTest.java
@@ -0,0 +1,109 @@
+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.lambda.LambdaClient;
+import software.amazon.awssdk.services.lambda.model.LogFormat;
+import software.amazon.awssdk.services.lambda.model.LoggingConfig;
+
+import java.time.Duration;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+/**
+ * AWS::Lambda::Function.LoggingConfig through the CloudFormation and Lambda SDK clients. Measured on
+ * AWS (eu-west-1, 2026-10-16): the function reads back the LogGroup the template names; a change to
+ * JSON with an ApplicationLogLevel updates it in place, SystemLogLevel reading back INFO; removing
+ * the property puts it back on Text and {@code /aws/lambda/<name>}, again in place.
+ */
+@DisplayName("CloudFormation Lambda LoggingConfig")
+class CloudFormationLambdaLoggingConfigTest {
+
+ private static final String STACK_NAME = TestFixtures.uniqueName("compat-cfn-logging");
+ private static final String ROLE = "arn:aws:iam::000000000000:role/cfn-lambda-role";
+ private static final Duration DEPLOY_TIMEOUT = Duration.ofSeconds(30);
+
+ private static CloudFormationClient cfn;
+ private static LambdaClient lambda;
+
+ @BeforeAll
+ static void setup() {
+ cfn = TestFixtures.cloudFormationClient();
+ lambda = TestFixtures.lambdaClient();
+ }
+
+ @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(STACK_NAME));
+ cfn.close();
+ }
+ if (lambda != null) {
+ lambda.close();
+ }
+ }
+
+ @Test
+ @DisplayName("LoggingConfig is created, updated and removed in place")
+ void loggingConfigLifecycle() throws InterruptedException {
+ cfn.createStack(request -> request.stackName(STACK_NAME)
+ .templateBody(template(",\"LoggingConfig\": {\"LogGroup\": \"/compat/cfn-a\"}")));
+ assertThat(TestFixtures.awaitStackTerminal(cfn, STACK_NAME, DEPLOY_TIMEOUT)).isEqualTo("CREATE_COMPLETE");
+ String created = functionName();
+ LoggingConfig named = loggingConfig(created);
+ assertThat(named.logFormat()).isEqualTo(LogFormat.TEXT);
+ assertThat(named.logGroup()).isEqualTo("/compat/cfn-a");
+ assertThat(named.applicationLogLevel()).isNull();
+
+ cfn.updateStack(request -> request.stackName(STACK_NAME).templateBody(template(
+ ",\"LoggingConfig\": {\"LogGroup\": \"/compat/cfn-b\", \"LogFormat\": \"JSON\","
+ + " \"ApplicationLogLevel\": \"WARN\"}")));
+ assertThat(TestFixtures.awaitStackTerminal(cfn, STACK_NAME, DEPLOY_TIMEOUT)).isEqualTo("UPDATE_COMPLETE");
+ assertThat(functionName()).as("a changed LoggingConfig updates in place").isEqualTo(created);
+ LoggingConfig json = loggingConfig(created);
+ assertThat(json.logFormat()).isEqualTo(LogFormat.JSON);
+ assertThat(json.applicationLogLevelAsString()).isEqualTo("WARN");
+ assertThat(json.systemLogLevelAsString()).isEqualTo("INFO");
+ assertThat(json.logGroup()).isEqualTo("/compat/cfn-b");
+
+ cfn.updateStack(request -> request.stackName(STACK_NAME).templateBody(template("")));
+ assertThat(TestFixtures.awaitStackTerminal(cfn, STACK_NAME, DEPLOY_TIMEOUT)).isEqualTo("UPDATE_COMPLETE");
+ assertThat(functionName()).as("removing LoggingConfig updates in place").isEqualTo(created);
+ LoggingConfig defaults = loggingConfig(created);
+ assertThat(defaults.logFormat()).isEqualTo(LogFormat.TEXT);
+ assertThat(defaults.applicationLogLevel()).isNull();
+ assertThat(defaults.logGroup()).isEqualTo("/aws/lambda/" + created);
+ }
+
+ private static String template(String loggingConfig) {
+ 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
+ }
+ }
+ },
+ "Outputs": {"Name": {"Value": {"Ref": "Fn"}}}
+ }
+ """.formatted(ROLE, loggingConfig);
+ }
+
+ private static String functionName() {
+ return cfn.describeStacks(request -> request.stackName(STACK_NAME)).stacks().get(0).outputs().get(0).outputValue();
+ }
+
+ private static LoggingConfig loggingConfig(String functionName) {
+ return lambda.getFunctionConfiguration(request -> request.functionName(functionName)).loggingConfig();
+ }
+}
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index c74899bcc8..258dd18ea2 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -425,6 +425,7 @@ status, named with its stack or by its ARN alone; a `StackName` that names no st
- Code and mutable configuration changes update the existing function in place.
- Replacement-only changes such as `FunctionName` or `PackageType` changes create a replacement function and remove the old one.
- A changed `DurableConfig` updates the function in place. A `RetentionPeriodInDays` the template leaves out goes back to 14, and a `KMSKeyArn` it leaves out is cleared. Adding or removing `DurableConfig` replaces the function, since Lambda cannot do either in place. A durable function created without `Timeout` gets `min(ExecutionTimeout, 900)`, while an update without it sets 3, as on AWS.
+- `LoggingConfig` reaches the function on create and on update, in place. Removing it from the template puts the function back on its defaults: `Text` (`JSON` for a durable function) and `/aws/lambda/<name>`.
- S3-backed code stays linked through `S3Bucket` / `S3Key`, so Lambda's reactive S3 sync continues to work for functions created by CloudFormation or CDK.
- Hot-reload code (`S3Bucket: hot-reload`) is compared by host path: the same path is a no-op, a different path updates the bind mount in place.
- `Tags` are applied when the function is created, including a replacement function. On `UpdateStack` the template's tags are applied and only the keys the previous template set and the new one drops are removed, so a tag added outside the template is kept, as in AWS.
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.java
index a64641dd62..d7d19d1b9a 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
@@ -261,6 +261,9 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
configRequest.put("DeadLetterConfig", resolveMapOrDefault(props, "DeadLetterConfig", engine,
mapWithNullValue("TargetArn")));
configRequest.put("VpcConfig", resolveMapOrDefault(props, "VpcConfig", engine, Map.of()));
+ // Empty when the template has none, so that removing it puts the function back on its
+ // defaults (Text, or JSON for a durable function, and /aws/lambda/<name>), as on AWS.
+ configRequest.put("LoggingConfig", resolveMapOrDefault(props, "LoggingConfig", engine, Map.of()));
configRequest.put("FileSystemConfigs",
resolveObjectListOrEmpty(props, "FileSystemConfigs", engine));
putResolvedMapIfPresent(configRequest, props, "ImageConfig", "ImageConfig", engine);
@@ -573,6 +576,11 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
return true;
}
}
+ case "LoggingConfig" -> {
+ if (loggingConfigurationChanged(fn, desired)) {
+ return true;
+ }
+ }
case "FileSystemConfigs" -> {
if (!Objects.equals(normalizeForCompare(fileSystemConfigs(fn)),
normalizeForCompare(desired))) {
@@ -601,6 +609,12 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
return false;
}
+ /** Compares what Lambda would store for {@code desired} with what the function has. */
+ private static boolean loggingConfigurationChanged(LambdaFunction fn, Object desired) {
+ Map<?, ?> logging = desired instanceof Map<?, ?> map ? map : Map.of();
+ return !LambdaService.loggingSettings(fn).equals(LambdaService.loggingSettings(logging, fn.isDurable()));
+ }
+
private boolean imageConfigurationChanged(
LambdaFunction fn,
Object desired) {
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
index da1cea2ebe..0b3d3b7678 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaService.java
@@ -2924,17 +2924,45 @@ public class LambdaService implements ResourceProvider {
if (!(value instanceof Map<?, ?> logging)) {
return;
}
- validateLoggingConfig(value, fn.isDurable());
- String defaultFormat = fn.isDurable() ? "JSON" : "Text";
- String format = logging.get("LogFormat") instanceof String f && !f.isBlank() ? f : defaultFormat;
+ LoggingSettings settings = loggingSettings(logging, fn.isDurable());
+ fn.setLogFormat(settings.logFormat());
+ fn.setApplicationLogLevel(settings.applicationLogLevel());
+ fn.setSystemLogLevel(settings.systemLogLevel());
+ fn.setLogGroup(settings.logGroup());
+ }
+
+ /** A function's logging settings as Lambda stores them; see {@link #loggingSettings(Map, boolean)}. */
+ public record LoggingSettings(String logFormat, String applicationLogLevel, String systemLogLevel,
+ String logGroup) {
+ }
+
+ /**
+ * What Lambda stores for a LoggingConfig, once it is valid: an omitted LogFormat is the
+ * function's default, JSON for a durable function and Text otherwise, the two log levels count
+ * only in JSON, and a blank value is an omitted one, an omitted LogGroup meaning
+ * {@code /aws/lambda/<name>}. An invalid value is refused even where it would not be stored,
+ * a log level under Text included, so a comparison of these settings cannot pass it as
+ * unchanged.
+ */
+ public static LoggingSettings loggingSettings(Map<?, ?> logging, boolean durable) {
+ validateLoggingConfig(logging, durable);
+ String format = logging.get("LogFormat") instanceof String f && !f.isBlank() ? f : durable ? "JSON" : "Text";
boolean json = "JSON".equals(format);
- fn.setLogFormat(format);
- fn.setApplicationLogLevel(json && logging.get("ApplicationLogLevel") instanceof String level
- && !level.isBlank() ? level : null);
- fn.setSystemLogLevel(json && logging.get("SystemLogLevel") instanceof String level
- && !level.isBlank() ? level : null);
- fn.setLogGroup(logging.get("LogGroup") instanceof String group && !group.isBlank()
- ? group : null);
+ return new LoggingSettings(format,
+ json ? nonBlank(logging.get("ApplicationLogLevel")) : null,
+ json ? nonBlank(logging.get("SystemLogLevel")) : null,
+ nonBlank(logging.get("LogGroup")));
+ }
+
+ /** The function's stored logging settings, its default LogFormat when it has none stored. */
+ public static LoggingSettings loggingSettings(LambdaFunction fn) {
+ return new LoggingSettings(
+ fn.getLogFormat() != null ? fn.getLogFormat() : loggingSettings(Map.of(), fn.isDurable()).logFormat(),
+ fn.getApplicationLogLevel(), fn.getSystemLogLevel(), fn.getLogGroup());
+ }
+
+ private static String nonBlank(Object value) {
+ return value instanceof String s && !s.isBlank() ? s : null;
}
private static boolean hasValues(Map<String, Object> config, String key) {
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLoggingConfigIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLoggingConfigIntegrationTest.java
new file mode 100644
index 0000000000..94f36e1209
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationLambdaLoggingConfigIntegrationTest.java
@@ -0,0 +1,163 @@
+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.equalTo;
+import static org.hamcrest.Matchers.nullValue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+
+/**
+ * {@code AWS::Lambda::Function.LoggingConfig} through CloudFormation. Measured on AWS (eu-west-1,
+ * 2026-10-16): the function reads back the LogGroup the template names; a change to JSON with an
+ * ApplicationLogLevel updates it in place, SystemLogLevel reading back INFO; and removing the
+ * property puts it back on Text and {@code /aws/lambda/<name>}, again in place.
+ */
+@QuarkusTest
+class CloudFormationLambdaLoggingConfigIntegrationTest {
+
+ 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 loggingConfigIsCreatedUpdatedAndRemovedInPlace() {
+ String stackName = "cfn-lambda-logging-" + Long.toString(System.nanoTime(), 36);
+ registerDeletion(stackName);
+
+ deploy("CreateStack", stackName, template("""
+ ,"LoggingConfig": {"LogGroup": "/floci/cfn-a"}
+ """));
+ String created = functionName(stackName);
+ given()
+ .when()
+ .get(LAMBDA + created + "/configuration")
+ .then()
+ .statusCode(200)
+ .body("LoggingConfig.LogFormat", equalTo("Text"))
+ .body("LoggingConfig.LogGroup", equalTo("/floci/cfn-a"))
+ .body("LoggingConfig.ApplicationLogLevel", nullValue());
+
+ deploy("UpdateStack", stackName, template("""
+ ,"LoggingConfig": {"LogGroup": "/floci/cfn-b", "LogFormat": "JSON", "ApplicationLogLevel": "WARN"}
+ """));
+ assertEquals(created, functionName(stackName), "a changed LoggingConfig updates the function in place");
+ given()
+ .when()
+ .get(LAMBDA + created + "/configuration")
+ .then()
+ .statusCode(200)
+ .body("LoggingConfig.LogFormat", equalTo("JSON"))
+ .body("LoggingConfig.ApplicationLogLevel", equalTo("WARN"))
+ .body("LoggingConfig.SystemLogLevel", equalTo("INFO"))
+ .body("LoggingConfig.LogGroup", equalTo("/floci/cfn-b"));
+
+ deploy("UpdateStack", stackName, template(""));
+ assertEquals(created, functionName(stackName), "removing LoggingConfig updates the function in place");
+ given()
+ .when()
+ .get(LAMBDA + created + "/configuration")
+ .then()
+ .statusCode(200)
+ .body("LoggingConfig.LogFormat", equalTo("Text"))
+ .body("LoggingConfig.ApplicationLogLevel", nullValue())
+ .body("LoggingConfig.LogGroup", equalTo("/aws/lambda/" + created));
+ }
+
+ /**
+ * A log level outside the enum fails the update, as Lambda refuses it, even under Text where
+ * Lambda would not store a level: it must not pass the update check as an unchanged
+ * LoggingConfig, and the function keeps its configuration.
+ */
+ @Test
+ void anInvalidLogLevelFailsTheUpdate() {
+ String stackName = "cfn-lambda-logging-level-" + Long.toString(System.nanoTime(), 36);
+ registerDeletion(stackName);
+ deploy("CreateStack", stackName, template(""));
+ String created = functionName(stackName);
+
+ submit("UpdateStack", stackName, template("""
+ ,"LoggingConfig": {"LogFormat": "Text", "ApplicationLogLevel": "VERBOSE"}
+ """));
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
+ assertNotEquals("UPDATE_COMPLETE", state.status(), state.reason());
+ given()
+ .when()
+ .get(LAMBDA + created + "/configuration")
+ .then()
+ .statusCode(200)
+ .body("LoggingConfig.LogFormat", equalTo("Text"))
+ .body("LoggingConfig.ApplicationLogLevel", nullValue());
+ }
+
+ private void registerDeletion(String stackName) {
+ cleanup.register(() -> {
+ submit("DeleteStack", stackName, null);
+ CfnStackWaits.awaitStackDeleted(stackName);
+ });
+ }
+
+ private static String template(String loggingConfig) {
+ 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(loggingConfig);
+ }
+
+ private static void deploy(String action, String stackName, String template) {
+ submit(action, stackName, template);
+ CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
+ assertEquals("CreateStack".equals(action) ? "CREATE_COMPLETE" : "UPDATE_COMPLETE", state.status(),
+ state.reason());
+ }
+
+ 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 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' }");
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
index 744fbbb824..37803f082d 100644
--- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java
@@ -3006,4 +3006,35 @@ class LambdaServiceTest {
principalOrgId.getMessage());
assertEquals("ValidationException", eventSourceToken.getErrorCode());
}
+
+ @Test
+ void loggingSettingsAreWhatLambdaStoresForALoggingConfig() {
+ assertEquals(new LambdaService.LoggingSettings("Text", null, null, null),
+ LambdaService.loggingSettings(Map.of(), false));
+ assertEquals(new LambdaService.LoggingSettings("JSON", null, null, null),
+ LambdaService.loggingSettings(Map.of(), true));
+ assertEquals(new LambdaService.LoggingSettings("Text", null, null, "/shared/app"),
+ LambdaService.loggingSettings(Map.of("ApplicationLogLevel", "WARN", "LogGroup", "/shared/app"), false));
+ assertEquals(new LambdaService.LoggingSettings("JSON", "WARN", null, null),
+ LambdaService.loggingSettings(Map.of("LogFormat", "JSON", "ApplicationLogLevel", "WARN",
+ "LogGroup", ""), false));
+ }
+
+ @Test
+ void loggingSettingsRefuseAnInvalidLevelEvenUnderText() {
+ AwsException refused = assertThrows(AwsException.class, () -> LambdaService.loggingSettings(
+ Map.of("LogFormat", "Text", "ApplicationLogLevel", "LOUD"), false));
+
+ assertEquals("ValidationException", refused.getErrorCode());
+ }
+
+ @Test
+ void aFunctionsLoggingSettingsFillInItsDefaultFormat() {
+ LambdaFunction fn = new LambdaFunction();
+ fn.setFunctionName("orders");
+ fn.setLogGroup("/shared/app");
+
+ assertEquals(new LambdaService.LoggingSettings("Text", null, null, "/shared/app"),
+ LambdaService.loggingSettings(fn));
+ }
}