fix(cloudformation): pass Lambda hot-reload code through to the Lambda service (#4093)

* fix(cloudformation): pass Lambda hot-reload code through to the Lambda service

AWS::Lambda::Function code of {S3Bucket: hot-reload, S3Key: /host/path} is
Lambda's bind-mount hot-reload convention: the bucket is a marker and the key
is a directory on the Docker host. The provisioner probed S3 for the pair
before calling CreateFunction, so no such object existed and the stack failed
with a ValidationError (or, with allow-stub-lambda-code on, quietly deployed
the stub handler).

Skip the S3 probe for the hot-reload bucket and hand the Code map to
LambdaService unchanged, which keeps enforcing hot-reload enablement, the
absolute-path rule and the allow-list, and reports its own error as the
resource status reason. Record a hot-reload code identity so a redeploy with
the same path is a no-op, and compare adopted functions by host path since a
hot-reload function carries no S3 bucket or key.

* fix(cloudformation): canonicalise the hot-reload code identity

LambdaService stores a hot-reload host path normalised (#4053), while the
provisioner recorded the raw template key as the code identity and compared
adopted functions against it. A template that spelled the same directory with
a trailing slash or a ".." segment, or a function adopted from a direct
CreateFunction, therefore looked like a code change and triggered an
UpdateFunctionCode that mounted the same directory again.

Build the identity from, and compare against, the normalised path. The raw key
still goes to Lambda so its validation and error messages are unchanged. Also
cover the documented SAM CodeUri form, s3://hot-reload//abs/path, through the
transform.
This commit is contained in:
stodan authored and GitHub committed 2026-09-23 18:03:35 -05:00
1 parent 67f06c3ac9
commit 34f4f72e82
7 files changed
+372 -2

No files matched your search

@@ -0,0 +1,184 @@
package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.lambda.model.LambdaFunction;
import io.github.hectorvent.floci.services.s3.S3Service;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.Map;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* A template whose Lambda code is {@code {S3Bucket: hot-reload, S3Key: /host/path}} uses the
* Lambda service's bind-mount hot-reload convention. There is no S3 object behind that pair, so
* the provisioner must hand it to LambdaService unchanged instead of probing S3 and failing the
* resource (or, with allow-stub-lambda-code, quietly deploying the stub handler).
*/
class CloudFormationLambdaHotReloadCodeTest {
private static final String ACCOUNT_ID = "000000000000";
private static final String REGION = "us-east-1";
private static final String STACK_NAME = "test-stack";
private static final String FUNCTION_NAME = "hot-fn";
private static final String HOST_PATH = "/home/dev/project/dist";
private final ObjectMapper mapper = new ObjectMapper();
private S3Service s3Service;
private LambdaService lambdaService;
private CloudFormationResourceProvisioner provisioner;
@BeforeEach
void setUp() {
s3Service = mock(S3Service.class);
lambdaService = mock(LambdaService.class);
when(lambdaService.createFunction(anyString(), anyMap()))
.thenAnswer(inv -> hotReloadFunction(HOST_PATH));
when(lambdaService.updateFunctionConfiguration(anyString(), anyString(), anyMap()))
.thenAnswer(inv -> hotReloadFunction(HOST_PATH));
when(lambdaService.updateFunctionCode(anyString(), anyString(), anyMap()))
.thenAnswer(inv -> hotReloadFunction((String) ((Map<?, ?>) inv.getArgument(2)).get("S3Key")));
provisioner = CfnProvisionerFixture.builder()
.s3(s3Service)
.lambda(lambdaService)
.objectMapper(mapper)
.build();
}
@Test
void hotReloadCodeIsPassedThroughWithoutProbingS3() {
StackResource result = provision(HOST_PATH, null, Map.of());
assertEquals("CREATE_COMPLETE", result.getStatus());
verify(s3Service, never()).headObject(anyString(), anyString());
verify(s3Service, never()).getObject(anyString(), anyString());
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.captor();
verify(lambdaService).createFunction(eq(REGION), request.capture());
assertEquals(Map.of("S3Bucket", "hot-reload", "S3Key", HOST_PATH), request.getValue().get("Code"));
assertEquals("hot-reload:" + HOST_PATH, result.getAttributes().get("FlociLambdaCodeIdentity"));
}
@Test
void redeployingTheSameHostPathDoesNotTouchTheCode() {
when(lambdaService.getFunction(REGION, FUNCTION_NAME)).thenReturn(hotReloadFunction(HOST_PATH));
StackResource result = provision(HOST_PATH, FUNCTION_NAME,
Map.of("FlociLambdaCodeIdentity", "hot-reload:" + HOST_PATH));
assertEquals(FUNCTION_NAME, result.getPhysicalId());
verify(lambdaService, never()).createFunction(anyString(), anyMap());
verify(lambdaService, never()).updateFunctionCode(anyString(), anyString(), anyMap());
verify(s3Service, never()).headObject(anyString(), anyString());
}
@Test
void anAdoptedHotReloadFunctionWithoutARecordedIdentityIsComparedByHostPath() {
when(lambdaService.getFunction(REGION, FUNCTION_NAME)).thenReturn(hotReloadFunction(HOST_PATH));
provision(HOST_PATH, FUNCTION_NAME, Map.of());
verify(lambdaService, never()).updateFunctionCode(anyString(), anyString(), anyMap());
}
@Test
void aRespelledHostPathIsNotACodeChange() {
// LambdaService stores the normalized path (#4053); the template may spell the same
// directory with a trailing slash or a ".." segment. Neither is a new mount.
when(lambdaService.getFunction(REGION, FUNCTION_NAME)).thenReturn(hotReloadFunction(HOST_PATH));
StackResource result = provision("/home/dev/project/build/../dist/", FUNCTION_NAME,
Map.of("FlociLambdaCodeIdentity", "hot-reload:" + HOST_PATH));
verify(lambdaService, never()).updateFunctionCode(anyString(), anyString(), anyMap());
assertEquals("hot-reload:" + HOST_PATH, result.getAttributes().get("FlociLambdaCodeIdentity"));
}
@Test
void anAdoptedFunctionIsComparedAgainstTheCanonicalTemplatePath() {
when(lambdaService.getFunction(REGION, FUNCTION_NAME)).thenReturn(hotReloadFunction(HOST_PATH));
provision(HOST_PATH + "/", FUNCTION_NAME, Map.of());
verify(lambdaService, never()).updateFunctionCode(anyString(), anyString(), anyMap());
}
@Test
void theRawKeyStillReachesLambdaForValidation() {
StackResource result = provision("relative/dist", null, Map.of());
ArgumentCaptor<Map<String, Object>> request = ArgumentCaptor.captor();
verify(lambdaService).createFunction(eq(REGION), request.capture());
assertEquals("relative/dist", ((Map<?, ?>) request.getValue().get("Code")).get("S3Key"));
assertEquals("CREATE_COMPLETE", result.getStatus());
}
@Test
void aChangedHostPathUpdatesTheFunctionCode() {
when(lambdaService.getFunction(REGION, FUNCTION_NAME)).thenReturn(hotReloadFunction(HOST_PATH));
StackResource result = provision("/home/dev/other/dist", FUNCTION_NAME,
Map.of("FlociLambdaCodeIdentity", "hot-reload:" + HOST_PATH));
verify(lambdaService, never()).createFunction(anyString(), anyMap());
verify(lambdaService).updateFunctionCode(eq(REGION), eq(FUNCTION_NAME),
eq(Map.of("S3Bucket", "hot-reload", "S3Key", "/home/dev/other/dist")));
assertEquals("hot-reload:/home/dev/other/dist", result.getAttributes().get("FlociLambdaCodeIdentity"));
}
private StackResource provision(String hostPath, String existingPhysicalId,
Map<String, String> existingAttributes) {
String props = """
{
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Handler": "index.handler",
"Role": "arn:aws:iam::000000000000:role/r",
"Code": {"S3Bucket": "hot-reload", "S3Key": "%s"}
}
""".formatted(FUNCTION_NAME, hostPath);
return provisioner.provision("Function", "AWS::Lambda::Function", props(props), engine(),
REGION, ACCOUNT_ID, STACK_NAME, existingPhysicalId, existingAttributes);
}
private CloudFormationTemplateEngine engine() {
return new CloudFormationTemplateEngine(
ACCOUNT_ID, REGION, STACK_NAME, "stack/id",
Map.of(), Map.of(), Map.of(), Map.of(), Map.of(), mapper,
(Function<String, String>) name -> null);
}
private JsonNode props(String json) {
try {
return mapper.readTree(json);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static LambdaFunction hotReloadFunction(String hostPath) {
LambdaFunction fn = new LambdaFunction();
fn.setFunctionName(FUNCTION_NAME);
fn.setFunctionArn("arn:aws:lambda:" + REGION + ":" + ACCOUNT_ID + ":function:" + FUNCTION_NAME);
fn.setPackageType("Zip");
fn.setRuntime("nodejs20.x");
fn.setHandler("index.handler");
fn.setRole("arn:aws:iam::" + ACCOUNT_ID + ":role/r");
fn.setRevisionId("1");
fn.setHotReloadHostPath(hostPath);
return fn;
}
}
@@ -0,0 +1,116 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.ValidatableResponse;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
/**
* A stack whose Lambda code is {@code {S3Bucket: hot-reload, S3Key: /host/path}} must reach
* CREATE_COMPLETE with the function bound to that host path, exactly as CreateFunction with the
* same Code does. The provisioner used to probe S3 for the pair and fail the stack because no
* such object exists. Control plane only: the bind mount is only consulted at invoke time, so
* the test is Docker-free. The test profile enables hot-reload.
*/
@QuarkusTest
class CloudFormationLambdaHotReloadIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
@Test
void hotReloadCodeReachesLambdaAndCompletesTheStack() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-hot-reload-" + suffix;
String fnName = "hot-reload-fn-" + suffix;
String hostPath = "/tmp/floci-cfn-hot-reload-" + suffix;
createStack(stackName, template(fnName, hostPath));
describeStacks(stackName)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"));
given()
.when().get("/2015-03-31/functions/" + fnName)
.then()
.statusCode(200)
.body("Configuration.FunctionName", equalTo(fnName))
.body("Configuration.Handler", equalTo("index.handler"));
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
}
@Test
void aRelativeHostPathFailsTheStackWithLambdasOwnMessage() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-hot-reload-rel-" + suffix;
String fnName = "hot-reload-rel-fn-" + suffix;
createStack(stackName, template(fnName, "relative/dist"));
describeStacks(stackName)
.body(not(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>")))
.body(containsString("Hot-reload S3Key must be an absolute path"));
given()
.when().get("/2015-03-31/functions/" + fnName)
.then()
.statusCode(404);
}
private static String template(String fnName, String hostPath) {
return """
{
"Resources": {
"Fn": {
"Type": "AWS::Lambda::Function",
"Properties": {
"FunctionName": "%s",
"Runtime": "nodejs20.x",
"Handler": "index.handler",
"Role": "arn:aws:iam::000000000000:role/r",
"Code": {"S3Bucket": "hot-reload", "S3Key": "%s"}
}
}
}
}
""".formatted(fnName, hostPath);
}
private static void createStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
}
private static ValidatableResponse describeStacks(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);
}
}
@@ -411,6 +411,33 @@ class SamTransformProcessorTest {
assertEquals("code.zip", code.path("S3Key").asText());
}
@Test
void expandSamTemplate_functionWithHotReloadCodeUri() throws Exception {
// Everything after the first slash is the key, so the documented double slash is what
// keeps a hot-reload host path absolute; the pair must reach AWS::Lambda::Function intact.
JsonNode template = objectMapper.readTree("""
{
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"HotFunc": {
"Type": "AWS::Serverless::Function",
"Properties": {
"Handler": "index.handler",
"Runtime": "nodejs20.x",
"CodeUri": "s3://hot-reload//home/dev/project/dist"
}
}
}
}
""");
JsonNode code = processor.expandSamTemplate(template)
.path("Resources").path("HotFunc").path("Properties").path("Code");
assertEquals("hot-reload", code.path("S3Bucket").asText());
assertEquals("/home/dev/project/dist", code.path("S3Key").asText());
}
@Test
void expandSamTemplate_functionPreservesMetadata() throws Exception {
JsonNode template = objectMapper.readTree("""