feat(cloudformation): pass Lambda DurableConfig through (#5218)

* feat(cloudformation): pass Lambda DurableConfig through

AWS::Lambda::Function.DurableConfig reaches CreateFunction and
UpdateFunctionConfiguration. As on AWS, a RetentionPeriodInDays the
template leaves out is 14 on update too, a durable function created
without Timeout gets min(ExecutionTimeout, 900), and adding or removing
DurableConfig replaces the function.

* test(terraform): cover aws_lambda_function durable_config

The provider creates a durable function, reads it back without a diff,
updates execution_timeout in place, and before destroy stops a RUNNING
durable execution through ListDurableExecutionsByFunction,
StopDurableExecution and GetDurableExecution.

* fix(cloudformation): honor AWS::NoValue, cleared keys and large numbers in DurableConfig

A DurableConfig that Fn::If removes with AWS::NoValue leaves the
function plain. A KMSKeyArn the template leaves out or sets to "" clears
the key, as CloudFormation does on AWS, since Lambda keeps a stored key
when the update omits the member. A number beyond an integer reaches
Lambda unchanged, so its range check rejects it.

* fix(cloudformation): reject a DurableConfig that is not an object

Only an intrinsic that resolves to AWS::NoValue removes DurableConfig.
CloudFormation rejects a string, number or list in its schema check
before the function is touched, so an update with one no longer
replaces and deletes a durable function.

* test(cloudformation): cover Lambda DurableConfig with the AWS SDK

The CloudFormation and Lambda SDK clients create a durable function,
update DurableConfig in place, and remove it by replacing the function.

* fix(cloudformation): require ExecutionTimeout and known members in DurableConfig

CloudFormation checks DurableConfig against the schema on update too: an
update without ExecutionTimeout, or with a member the schema does not
list, fails before the function is touched. Floci let such an update
through and kept the old timeout.

* refactor(cloudformation): look up a Lambda function once per deploy

The name choice and the replacement decision now share one lookup and one
durable check, so they cannot disagree.
This commit is contained in:
TATSUNO “Taz” Yasuhiro authored and GitHub committed 2026-10-07 12:39:36 -04:00
1 parent bdb37f0ca3
commit ee2d1a68a6
9 files changed
+667 -8

No files matched your search

@@ -0,0 +1,61 @@
# aws_lambda_function.durable_config. The provider updates execution_timeout in place,
# and before it deletes the function it stops every RUNNING durable execution through
# ListDurableExecutionsByFunction, StopDurableExecution and GetDurableExecution.
variable "execution_timeout" {
type = number
default = 60
}
data "archive_file" "handler" {
type = "zip"
output_path = "${path.module}/handler.zip"
# Starts a long wait, so an execution stays RUNNING until something stops it.
source {
filename = "index.py"
content = <<-PY
import boto3
def handler(event, context):
if len(event["InitialExecutionState"]["Operations"]) == 1:
boto3.client("lambda").checkpoint_durable_execution(
DurableExecutionArn=event["DurableExecutionArn"],
CheckpointToken=event["CheckpointToken"],
Updates=[{"Id": "w", "Type": "WAIT", "SubType": "Wait", "Action": "START",
"WaitOptions": {"WaitSeconds": 600}}])
return {"Status": "PENDING"}
PY
}
}
resource "aws_iam_role" "durable" {
name = "floci-tf-lambda-durable"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Effect = "Allow"
Principal = { Service = "lambda.amazonaws.com" }
Action = "sts:AssumeRole"
}]
})
}
resource "aws_lambda_function" "durable" {
function_name = "floci-tf-lambda-durable"
role = aws_iam_role.durable.arn
runtime = "python3.14"
handler = "index.handler"
filename = data.archive_file.handler.output_path
source_code_hash = data.archive_file.handler.output_base64sha256
timeout = 30
durable_config {
execution_timeout = var.execution_timeout
}
}
output "function_name" {
value = aws_lambda_function.durable.function_name
}
@@ -0,0 +1,33 @@
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 6.25"
}
archive = {
source = "hashicorp/archive"
version = "~> 2.0"
}
}
}
variable "endpoint" {
type = string
default = "http://localhost:4566"
}
provider "aws" {
region = "us-east-1"
access_key = "test"
secret_key = "test"
skip_credentials_validation = true
skip_metadata_api_check = true
skip_requesting_account_id = true
endpoints {
iam = var.endpoint
lambda = var.endpoint
sts = var.endpoint
}
}
@@ -0,0 +1,85 @@
#!/usr/bin/env bats
# Lambda durable_config compatibility test
#
# aws_lambda_function.durable_config creates a durable function, reads it back without a
# diff, updates execution_timeout in place, and on destroy stops a RUNNING durable
# execution before it deletes the function.
TF_DIR_NAME="lambda-durable-config-tf"
setup_file() {
load 'test_helper/common-setup'
DURABLE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/$TF_DIR_NAME" && pwd)"
cd "$DURABLE_TF_DIR"
echo "# === Lambda durable_config Test ===" >&3
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* handler.zip 2>/dev/null || true
run terraform init -input=false -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform init failed: $output" >&3
return 1
fi
run terraform apply -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color
if [ "$status" -ne 0 ]; then
echo "# terraform apply failed: $output" >&3
return 1
fi
}
teardown_file() {
load 'test_helper/common-setup'
DURABLE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/$TF_DIR_NAME" && pwd)"
cd "$DURABLE_TF_DIR"
terraform destroy -var="endpoint=${FLOCI_ENDPOINT}" -input=false -auto-approve -no-color || true
rm -rf .terraform .terraform.lock.hcl terraform.tfstate* handler.zip 2>/dev/null || true
}
setup() {
load 'test_helper/common-setup'
DURABLE_TF_DIR="$(cd "$(dirname "$BATS_TEST_FILENAME")/$TF_DIR_NAME" && pwd)"
}
@test "durable_config: the function is durable with the default retention" {
run aws_cmd lambda get-function-configuration --function-name floci-tf-lambda-durable
assert_success
assert_equal "$(json_get "$output" '.DurableConfig.ExecutionTimeout')" "60"
assert_equal "$(json_get "$output" '.DurableConfig.RetentionPeriodInDays')" "14"
}
@test "durable_config: a second plan has no changes" {
run terraform -chdir="$DURABLE_TF_DIR" plan -var="endpoint=${FLOCI_ENDPOINT}" \
-input=false -no-color -detailed-exitcode
assert_success
}
@test "durable_config: execution_timeout updates the function in place" {
run terraform -chdir="$DURABLE_TF_DIR" apply -var="endpoint=${FLOCI_ENDPOINT}" \
-var="execution_timeout=120" -input=false -auto-approve -no-color
assert_success
assert_output --partial "0 added, 1 changed, 0 destroyed"
run aws_cmd lambda get-function-configuration --function-name floci-tf-lambda-durable
assert_success
assert_equal "$(json_get "$output" '.DurableConfig.ExecutionTimeout')" "120"
}
@test "durable_config: destroy stops a running durable execution" {
run aws_cmd lambda invoke --function-name 'floci-tf-lambda-durable:$LATEST' \
--invocation-type Event --cli-binary-format raw-in-base64-out --payload '{}' /dev/null
assert_success
execution_arn="$(json_get "$output" '.DurableExecutionArn')"
[ -n "$execution_arn" ] && [ "$execution_arn" != "null" ]
run terraform -chdir="$DURABLE_TF_DIR" destroy -var="endpoint=${FLOCI_ENDPOINT}" \
-var="execution_timeout=120" -input=false -auto-approve -no-color
assert_success
run aws_cmd lambda get-durable-execution --durable-execution-arn "$execution_arn"
assert_success
assert_equal "$(json_get "$output" '.Status')" "STOPPED"
}
@@ -0,0 +1,142 @@
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.CreateStackRequest;
import software.amazon.awssdk.services.cloudformation.model.DeleteStackRequest;
import software.amazon.awssdk.services.cloudformation.model.Parameter;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.cloudformation.model.UpdateStackRequest;
import software.amazon.awssdk.services.lambda.LambdaClient;
import software.amazon.awssdk.services.lambda.model.GetFunctionConfigurationResponse;
import software.amazon.awssdk.services.lambda.model.LogFormat;
import software.amazon.awssdk.services.lambda.model.ResourceNotFoundException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* AWS::Lambda::Function.DurableConfig through the CloudFormation and Lambda SDK clients: created,
* updated in place, and removed by replacing the function.
*/
@DisplayName("CloudFormation Lambda DurableConfig")
class CloudFormationLambdaDurableConfigTest {
private static final String STACK_NAME = TestFixtures.uniqueName("compat-cfn-durable");
private static final String ROLE = "arn:aws:iam::000000000000:role/cfn-lambda-role";
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) {
try {
cfn.deleteStack(DeleteStackRequest.builder().stackName(STACK_NAME).build());
} catch (Exception ignored) {
// Cleanup only. A failed delete must not hide the test result.
}
cfn.close();
}
if (lambda != null) {
lambda.close();
}
}
@Test
@DisplayName("DurableConfig is created, updated in place and removed by replacement")
void durableConfigLifecycle() throws InterruptedException {
cfn.createStack(CreateStackRequest.builder()
.stackName(STACK_NAME)
.templateBody(template("""
"DurableConfig": {"ExecutionTimeout": {"Ref": "ExecutionTimeout"}, "RetentionPeriodInDays": 3}
"""))
.parameters(executionTimeout("60"))
.build());
assertThat(waitForTerminal()).isEqualTo("CREATE_COMPLETE");
String created = functionName();
GetFunctionConfigurationResponse durable = lambda.getFunctionConfiguration(r -> r.functionName(created));
assertThat(durable.timeout()).as("a durable function created without Timeout").isEqualTo(60);
assertThat(durable.durableConfig().executionTimeout()).isEqualTo(60);
assertThat(durable.durableConfig().retentionPeriodInDays()).isEqualTo(3);
assertThat(durable.loggingConfig().logFormat()).isEqualTo(LogFormat.JSON);
cfn.updateStack(UpdateStackRequest.builder()
.stackName(STACK_NAME)
.templateBody(template("""
"DurableConfig": {"ExecutionTimeout": {"Ref": "ExecutionTimeout"}}
"""))
.parameters(executionTimeout("120"))
.build());
assertThat(waitForTerminal()).isEqualTo("UPDATE_COMPLETE");
assertThat(functionName()).as("a changed DurableConfig updates in place").isEqualTo(created);
GetFunctionConfigurationResponse updated = lambda.getFunctionConfiguration(r -> r.functionName(created));
assertThat(updated.durableConfig().executionTimeout()).isEqualTo(120);
assertThat(updated.durableConfig().retentionPeriodInDays()).isEqualTo(14);
cfn.updateStack(UpdateStackRequest.builder()
.stackName(STACK_NAME)
.templateBody(template("\"Description\": \"plain\""))
.parameters(executionTimeout("120"))
.build());
assertThat(waitForTerminal()).isEqualTo("UPDATE_COMPLETE");
String replaced = functionName();
assertThat(replaced).as("removing DurableConfig replaces the function").isNotEqualTo(created);
assertThat(lambda.getFunctionConfiguration(r -> r.functionName(replaced)).durableConfig()).isNull();
assertThatThrownBy(() -> lambda.getFunctionConfiguration(r -> r.functionName(created)))
.isInstanceOf(ResourceNotFoundException.class);
}
private static String template(String functionProperty) {
return """
{
"Parameters": {"ExecutionTimeout": {"Type": "Number"}},
"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, functionProperty);
}
private static Parameter executionTimeout(String value) {
return Parameter.builder().parameterKey("ExecutionTimeout").parameterValue(value).build();
}
private static Stack stack() {
return cfn.describeStacks(r -> r.stackName(STACK_NAME)).stacks().get(0);
}
private static String functionName() {
return stack().outputs().get(0).outputValue();
}
private static String waitForTerminal() throws InterruptedException {
for (int i = 0; i < 60; i++) {
String status = stack().stackStatusAsString();
if (!status.endsWith("_IN_PROGRESS")) {
return status;
}
Thread.sleep(500);
}
return stack().stackStatusAsString();
}
}
+1
View File
@@ -289,6 +289,7 @@ accepts, not only by name:
- A no-op redeploy keeps the existing physical function name and does not call Lambda update APIs, so warm containers can be reused.
- 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.
- 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.
+2 -1
View File
@@ -768,7 +768,8 @@ is a permanent diff rather than a cosmetic omission.
`DurableConfig` requires `ExecutionTimeout` on create. A durable function created without
a `Timeout` gets `min(ExecutionTimeout, 900)`. It always logs in JSON format, and
`LogFormat: Text` is rejected. On update the members are merged, and a function created
without `DurableConfig` cannot gain one. See Durable Functions for the execution itself.
without `DurableConfig` cannot gain one. CloudFormation and Terraform (`durable_config`) replace
the function to add or remove it. See Durable Functions for the execution itself.
`LogGroup` is validated against AWS's documented constraint: 1-512 characters matching
`[.\-_/#A-Za-z0-9]+`. `ApplicationLogLevel` and `SystemLogLevel` are accepted with any
@@ -61,6 +61,8 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
private static final String NAME_MODE_GENERATED = "generated";
private static final int LAMBDA_DEFAULT_TIMEOUT_SECONDS = 3;
private static final int LAMBDA_DEFAULT_DURABLE_RETENTION_DAYS = 14;
private static final Set<String> DURABLE_CONFIG_MEMBERS = Set.of("ExecutionTimeout", "RetentionPeriodInDays", "KMSKeyArn");
private static final int LAMBDA_DEFAULT_MEMORY_MB = 128;
private static final int LAMBDA_DEFAULT_EPHEMERAL_STORAGE_MB = 512;
private static final String LAMBDA_DEFAULT_TRACING_MODE = "PassThrough";
@@ -107,8 +109,8 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
private void provisionLambda(StackResource r, JsonNode props, ProvisionContext ctx) {
String region = ctx.region();
LambdaDesiredState desired = buildLambdaDesiredState(r, props, ctx);
LambdaFunction existing = getExistingLambda(region, r.getPhysicalId());
LambdaDesiredState desired = buildLambdaDesiredState(r, props, ctx, existing);
boolean replacement = lambdaRequiresReplacement(r, desired, existing);
LambdaFunction func;
@@ -156,7 +158,8 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
}
}
private LambdaDesiredState buildLambdaDesiredState(StackResource r, JsonNode props, ProvisionContext ctx) {
private LambdaDesiredState buildLambdaDesiredState(StackResource r, JsonNode props, ProvisionContext ctx,
LambdaFunction existing) {
CloudFormationTemplateEngine engine = ctx.engine();
String stackName = ctx.stackName();
String explicitName = ctx.resolveOptional(props, "FunctionName");
@@ -191,6 +194,9 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
boolean packageTypeReplacement = r.getPhysicalId() != null
&& oldPackageType != null
&& !Objects.equals(oldPackageType, packageType);
Map<String, Object> durableConfig = resolveDurableConfig(props, engine);
// Lambda cannot add or remove a DurableConfig, so CloudFormation replaces the function.
boolean durableReplacement = existing != null && existing.isDurable() != (durableConfig != null);
boolean explicitRemoved = r.getPhysicalId() != null
&& !hasExplicitName
&& NAME_MODE_EXPLICIT.equals(previousNameMode);
@@ -198,7 +204,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
String functionName;
if (hasExplicitName) {
functionName = explicitName;
} else if (r.getPhysicalId() != null && !explicitRemoved && !packageTypeReplacement) {
} else if (r.getPhysicalId() != null && !explicitRemoved && !packageTypeReplacement && !durableReplacement) {
functionName = r.getPhysicalId();
} else {
functionName = ctx.generatePhysicalName(r.getLogicalId(), 64, false);
@@ -240,8 +246,8 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
LambdaCodeSpec code = resolveLambdaCode(props, engine, handler, runtime);
createRequest.put("Code", code.request());
configRequest.put("Timeout", intOrDefault(ctx.resolveOptional(props, "Timeout"),
LAMBDA_DEFAULT_TIMEOUT_SECONDS));
String timeout = ctx.resolveOptional(props, "Timeout");
configRequest.put("Timeout", intOrDefault(timeout, LAMBDA_DEFAULT_TIMEOUT_SECONDS));
configRequest.put("MemorySize", intOrDefault(ctx.resolveOptional(props, "MemorySize"),
LAMBDA_DEFAULT_MEMORY_MB));
configRequest.put("Description", ctx.resolveOptional(props, "Description"));
@@ -259,8 +265,15 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
configRequest.put("FileSystemConfigs",
resolveObjectListOrEmpty(props, "FileSystemConfigs", engine));
putResolvedMapIfPresent(configRequest, props, "ImageConfig", "ImageConfig", engine);
if (durableConfig != null) {
configRequest.put("DurableConfig", durableConfig);
}
createRequest.putAll(configRequest);
if (durableConfig != null && timeout == null) {
// Created without one, a durable function gets min(ExecutionTimeout, 900). An update sends 3.
createRequest.remove("Timeout");
}
Map<String, String> tags = ctx.resolveTags(props, "Tags");
LambdaService.validateTagKeys(tags);
if (!tags.isEmpty()) {
@@ -277,7 +290,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
}
}
return new LambdaDesiredState(functionName, hasExplicitName, packageType,
return new LambdaDesiredState(functionName, hasExplicitName, packageType, durableReplacement,
createRequest, code, configRequest, tags, props != null && props.has("ReservedConcurrentExecutions"),
reservedConcurrentExecutions);
}
@@ -381,7 +394,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
return true;
}
String existingPackageType = existing.getPackageType() != null ? existing.getPackageType() : "Zip";
return !Objects.equals(existingPackageType, desired.packageType());
return !Objects.equals(existingPackageType, desired.packageType()) || desired.durableReplacement();
}
private LambdaFunction updateLambdaFunction(String region,
@@ -572,6 +585,15 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
return true;
}
}
case "DurableConfig" -> {
Map<?, ?> config = (Map<?, ?>) desired;
if (!Objects.equals(fn.getDurableExecutionTimeout(), config.get("ExecutionTimeout"))
|| !Objects.equals(fn.getDurableRetentionPeriodInDays(), config.get("RetentionPeriodInDays"))
|| !Objects.equals(Objects.requireNonNullElse(fn.getDurableKmsKeyArn(), ""),
config.get("KMSKeyArn"))) {
return true;
}
}
default -> {
// Properties outside UpdateFunctionConfiguration are ignored here.
}
@@ -685,6 +707,64 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
return value != null ? Integer.parseInt(value) : defaultValue;
}
/**
* Null when the template has no DurableConfig, or one that AWS::NoValue removed. As on AWS,
* RetentionPeriodInDays takes the schema default, 14, when the template leaves it out, on update
* too, and a KMSKeyArn left out clears the key. A number from a parameter arrives as text.
*/
private Map<String, Object> resolveDurableConfig(JsonNode props, CloudFormationTemplateEngine engine) {
if (props == null || !props.has("DurableConfig")) {
return null;
}
JsonNode raw = props.get("DurableConfig");
if (raw.isNull()) {
return null;
}
JsonNode node = engine.resolveNode(raw);
if (node == null || !node.isObject()) {
// The engine yields AWS::NoValue as "". Anything else fails CloudFormation's schema check
// before the function is touched.
if (!raw.isValueNode() && node != null && node.isTextual() && node.asText().isEmpty()) {
return null;
}
throw new AwsException("ValidationError", "AWS::Lambda::Function DurableConfig must be an object", 400);
}
// The schema requires ExecutionTimeout and allows no other members, and checks both on update too.
node.fieldNames().forEachRemaining(member -> {
if (!DURABLE_CONFIG_MEMBERS.contains(member)) {
throw new AwsException("ValidationError",
"AWS::Lambda::Function DurableConfig does not allow the member " + member, 400);
}
});
if (!node.hasNonNull("ExecutionTimeout")) {
throw new AwsException("ValidationError", "AWS::Lambda::Function DurableConfig requires ExecutionTimeout", 400);
}
Map<String, Object> config = new LinkedHashMap<>();
config.put("ExecutionTimeout", integerOrRaw(node.get("ExecutionTimeout")));
config.put("RetentionPeriodInDays", node.hasNonNull("RetentionPeriodInDays")
? integerOrRaw(node.get("RetentionPeriodInDays")) : LAMBDA_DEFAULT_DURABLE_RETENTION_DAYS);
// Lambda keeps a stored key when the update leaves the member out, and clears it on "".
config.put("KMSKeyArn", node.path("KMSKeyArn").asText(""));
return config;
}
/** A long stays a long so Lambda's range check rejects it. Anything else reaches Lambda as is. */
private Object integerOrRaw(JsonNode value) {
if (value.isIntegralNumber()) {
return value.canConvertToInt() ? (Object) value.intValue() : (Object) value.longValue();
}
if (value.isTextual()) {
try {
long number = Long.parseLong(value.asText());
return number == (int) number ? (Object) (int) number : (Object) number;
} catch (NumberFormatException ignored) {
// Not a number. Lambda answers it with the error AWS gives.
return value.asText();
}
}
return jsonNodeToValue(value);
}
private Map<String, String> resolveLambdaEnvironment(JsonNode props, CloudFormationTemplateEngine engine) {
if (props == null || !props.has("Environment") || props.get("Environment").isNull()) {
return Map.of();
@@ -921,6 +1001,7 @@ public class LambdaCfnProvisioner implements CfnResourceProvisioner {
private record LambdaDesiredState(String functionName,
boolean explicitFunctionName,
String packageType,
boolean durableReplacement,
Map<String, Object> createRequest,
LambdaCodeSpec code,
Map<String, Object> configRequest,
@@ -0,0 +1,163 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
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.DurableConfig} through CloudFormation: created, updated in place,
* and removed by replacing the function, with the defaults CloudFormation applies on AWS.
*/
@QuarkusTest
class CloudFormationLambdaDurableConfigIntegrationTest {
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/";
@Test
void durableConfigIsCreatedUpdatedInPlaceAndRemovedByReplacement() {
String stackName = "cfn-lambda-durable-" + Long.toString(System.nanoTime(), 36);
deploy("CreateStack", stackName, template("""
"DurableConfig": {"ExecutionTimeout": {"Ref": "ExecutionTimeout"}, "RetentionPeriodInDays": 3}
"""), "60");
String created = functionName(stackName);
given()
.when()
.get(LAMBDA + created + "/configuration")
.then()
.statusCode(200)
.body("Timeout", equalTo(60))
.body("DurableConfig.ExecutionTimeout", equalTo(60))
.body("DurableConfig.RetentionPeriodInDays", equalTo(3))
.body("LoggingConfig.LogFormat", equalTo("JSON"));
given()
.when()
.get(LAMBDA + created + "/configuration?Qualifier=1")
.then()
.statusCode(200)
.body("DurableConfig.ExecutionTimeout", equalTo(60));
deploy("UpdateStack", stackName, template("""
"DurableConfig": {"ExecutionTimeout": {"Ref": "ExecutionTimeout"}}
"""), "120");
assertEquals(created, functionName(stackName), "a changed DurableConfig updates the function in place");
given()
.when()
.get(LAMBDA + created + "/configuration")
.then()
.statusCode(200)
.body("Timeout", equalTo(3))
.body("DurableConfig.ExecutionTimeout", equalTo(120))
.body("DurableConfig.RetentionPeriodInDays", equalTo(14));
deploy("UpdateStack", stackName, template("\"Description\": \"plain\""), "120");
String replaced = functionName(stackName);
assertNotEquals(created, replaced, "Lambda cannot remove a DurableConfig, so the function is replaced");
given()
.when()
.get(LAMBDA + replaced + "/configuration")
.then()
.statusCode(200)
.body("DurableConfig", nullValue())
.body("LoggingConfig.LogFormat", equalTo("Text"));
given()
.when()
.get(LAMBDA + created)
.then()
.statusCode(404);
}
@Test
void aDurableConfigRemovedWithNoValueLeavesTheFunctionPlain() {
String stackName = "cfn-lambda-novalue-" + Long.toString(System.nanoTime(), 36);
String template = """
{
"Parameters": {"ExecutionTimeout": {"Type": "Number"}},
"Conditions": {"Durable": {"Fn::Equals": ["yes", "no"]}},
"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'"},
"DurableConfig": {"Fn::If": ["Durable", {"ExecutionTimeout": {"Ref": "ExecutionTimeout"}},
{"Ref": "AWS::NoValue"}]}
}
}
},
"Outputs": {"Name": {"Value": {"Ref": "Fn"}}}
}
""";
deploy("CreateStack", stackName, template, "60");
given()
.when()
.get(LAMBDA + functionName(stackName) + "/configuration")
.then()
.statusCode(200)
.body("DurableConfig", nullValue());
}
private static String template(String functionProperty) {
return """
{
"Parameters": {"ExecutionTimeout": {"Type": "Number"}},
"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
}
},
"Ver": {"Type": "AWS::Lambda::Version", "Properties": {"FunctionName": {"Ref": "Fn"}}}
},
"Outputs": {"Name": {"Value": {"Ref": "Fn"}}}
}
""".formatted(functionProperty);
}
private static void deploy(String action, String stackName, String template, String executionTimeout) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.formParam("Parameters.member.1.ParameterKey", "ExecutionTimeout")
.formParam("Parameters.member.1.ParameterValue", executionTimeout)
.when()
.post("/")
.then()
.statusCode(200);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stackName);
assertEquals("CreateStack".equals(action) ? "CREATE_COMPLETE" : "UPDATE_COMPLETE", state.status(),
state.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' }");
}
}
@@ -20,6 +20,7 @@ import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
@@ -27,6 +28,7 @@ import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@@ -183,6 +185,96 @@ class LambdaCfnProvisionerTest {
verify(lambda).tagResource(FUNCTION_ARN + "my-fn", Map.of("team", "b"));
}
@Test
void addingDurableConfigToANamedFunctionCannotReplaceIt() {
stubInPlaceUpdate("my-fn", Map.of());
ObjectNode props = props("my-fn");
props.putObject("DurableConfig").put("ExecutionTimeout", 60);
AwsException rejected = assertThrows(AwsException.class,
() -> provisioner.provision(function("my-fn"), props, updateCtx("my-fn")));
assertEquals("Cannot replace Lambda function my-fn without a new FunctionName", rejected.getMessage());
verify(lambda, never()).updateFunctionConfiguration(anyString(), anyString(), anyMap());
}
@Test
void aDurableConfigThatIsNotAnObjectLeavesTheFunctionAlone() {
// A generated name, so treating the value as removed would replace and delete the function.
String generated = "my-stack-MyFunction-ABCDEFGHIJKL";
LambdaFunction existing = lambdaFunction(generated);
existing.setDurableExecutionTimeout(60);
when(lambda.getFunction(REGION, generated)).thenReturn(existing);
when(lambda.createFunction(eq(REGION), anyMap())).thenReturn(lambdaFunction("replacement"));
for (JsonNode malformed : List.of(mapper.getNodeFactory().textNode("abc"), mapper.getNodeFactory().textNode(""),
mapper.getNodeFactory().numberNode(5), mapper.createArrayNode())) {
StackResource r = function(generated);
r.getAttributes().put("FlociLambdaFunctionNameMode", "generated");
ObjectNode props = mapper.createObjectNode();
props.set("DurableConfig", malformed);
AwsException rejected = assertThrows(AwsException.class,
() -> provisioner.provision(r, props, updateCtx(generated)));
assertEquals("ValidationError", rejected.getErrorCode());
}
verify(lambda, never()).createFunction(anyString(), anyMap());
verify(lambda, never()).updateFunctionConfiguration(anyString(), anyString(), anyMap());
verify(lambda, never()).deleteFunction(anyString(), anyString());
}
@Test
void aDurableConfigWithoutExecutionTimeoutOrWithAnUnknownMemberIsRejectedOnUpdate() {
LambdaFunction existing = lambdaFunction("my-fn");
existing.setDurableExecutionTimeout(60);
when(lambda.getFunction(REGION, "my-fn")).thenReturn(existing);
ObjectNode withoutTimeout = props("my-fn");
withoutTimeout.putObject("DurableConfig").put("RetentionPeriodInDays", 5);
ObjectNode unknownMember = props("my-fn");
unknownMember.putObject("DurableConfig").put("ExecutionTimeout", 90).put("executionTimeout", 1);
AwsException missing = assertThrows(AwsException.class,
() -> provisioner.provision(function("my-fn"), withoutTimeout, updateCtx("my-fn")));
AwsException unknown = assertThrows(AwsException.class,
() -> provisioner.provision(function("my-fn"), unknownMember, updateCtx("my-fn")));
assertEquals("AWS::Lambda::Function DurableConfig requires ExecutionTimeout", missing.getMessage());
assertEquals("AWS::Lambda::Function DurableConfig does not allow the member executionTimeout",
unknown.getMessage());
verify(lambda, never()).updateFunctionConfiguration(anyString(), anyString(), anyMap());
}
@Test
void anExecutionTimeoutBeyondAnIntegerReachesLambdaUnchanged() {
when(lambda.createFunction(eq(REGION), anyMap())).thenReturn(lambdaFunction("my-fn"));
ObjectNode props = props("my-fn");
props.putObject("DurableConfig").put("ExecutionTimeout", 4_294_967_356L);
provisioner.provision(function(null), props, ctx());
assertEquals(4_294_967_356L, ((Map<?, ?>) capturedCreateRequest().get("DurableConfig")).get("ExecutionTimeout"));
}
@Test
void aKmsKeyArnTheTemplateDropsIsClearedOnUpdate() {
LambdaFunction existing = lambdaFunction("my-fn");
existing.setDurableExecutionTimeout(60);
existing.setDurableRetentionPeriodInDays(14);
existing.setDurableKmsKeyArn("arn:aws:kms:us-east-1:000000000000:key/k1");
when(lambda.getFunction(REGION, "my-fn")).thenReturn(existing);
when(lambda.updateFunctionConfiguration(anyString(), anyString(), anyMap())).thenReturn(existing);
when(lambda.updateFunctionCode(anyString(), anyString(), anyMap())).thenReturn(existing);
when(lambda.listTags(FUNCTION_ARN + "my-fn")).thenReturn(new HashMap<>());
ObjectNode props = props("my-fn");
props.putObject("DurableConfig").put("ExecutionTimeout", 60);
provisioner.provision(function("my-fn"), props, updateCtx("my-fn"));
verify(lambda).updateFunctionConfiguration(eq(REGION), eq("my-fn"),
argThat(request -> "".equals(((Map<?, ?>) request.get("DurableConfig")).get("KMSKeyArn"))));
verify(lambda, times(1)).getFunction(REGION, "my-fn");
}
@SuppressWarnings("unchecked")
private Map<String, Object> capturedCreateRequest() {
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.forClass(Map.class);