Skip to content

armgit / floci

Public Imported from GitHub
0

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

fix(lambda): honour Publish on CreateFunction and UpdateFunctionCode (#2825)

Brian Taylora7b2b794929f
diff --git a/compatibility-tests/sdk-test-node/tests/lambda.test.ts b/compatibility-tests/sdk-test-node/tests/lambda.test.ts
index 57efb7685a..02124dc00c 100644
--- a/compatibility-tests/sdk-test-node/tests/lambda.test.ts
+++ b/compatibility-tests/sdk-test-node/tests/lambda.test.ts
@@ -17,6 +17,8 @@ import {
UpdateAliasCommand,
DeleteAliasCommand,
PublishVersionCommand,
+ ListVersionsByFunctionCommand,
+ UpdateFunctionCodeCommand,
} from '@aws-sdk/client-lambda';
import { makeClient, uniqueName, ACCOUNT, buildMinimalZip } from './setup';
@@ -185,3 +187,57 @@ describe('Lambda ImageConfig.WorkingDirectory', () => {
}
});
});
+
+describe('Lambda Publish flag', () => {
+ let lambda: LambdaClient;
+ let fnName: string;
+
+ beforeAll(() => {
+ lambda = makeClient(LambdaClient);
+ fnName = `test-publish-${uniqueName()}`;
+ });
+
+ afterAll(async () => {
+ await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName })).catch(() => {});
+ });
+
+ it('should publish version 1 on create and keep the ARN unqualified', async () => {
+ const response = await lambda.send(new CreateFunctionCommand({
+ FunctionName: fnName,
+ Runtime: 'nodejs20.x',
+ Role: `arn:aws:iam::${ACCOUNT}:role/lambda-role`,
+ Handler: 'index.handler',
+ Code: { ZipFile: buildMinimalZip('index.js', Buffer.from('exports.handler = async () => 1;')) },
+ Publish: true,
+ }));
+
+ expect(response.Version).toBe('1');
+ expect(response.FunctionArn).toMatch(new RegExp(`:function:${fnName}$`));
+
+ const listed = await lambda.send(new ListVersionsByFunctionCommand({ FunctionName: fnName }));
+ expect((listed.Versions ?? []).map((v) => v.Version).sort()).toEqual(['$LATEST', '1']);
+ });
+
+ it('should publish the next version on code update and return a qualified ARN', async () => {
+ const response = await lambda.send(new UpdateFunctionCodeCommand({
+ FunctionName: fnName,
+ ZipFile: buildMinimalZip('index.js', Buffer.from('exports.handler = async () => 2;')),
+ Publish: true,
+ }));
+
+ expect(response.Version).toBe('2');
+ expect(response.FunctionArn).toMatch(new RegExp(`:function:${fnName}:2$`));
+ });
+
+ it('should create no version when Publish is not set', async () => {
+ const response = await lambda.send(new UpdateFunctionCodeCommand({
+ FunctionName: fnName,
+ ZipFile: buildMinimalZip('index.js', Buffer.from('exports.handler = async () => 3;')),
+ }));
+
+ expect(response.Version).toBe('$LATEST');
+
+ const listed = await lambda.send(new ListVersionsByFunctionCommand({ FunctionName: fnName }));
+ expect((listed.Versions ?? []).map((v) => v.Version).sort()).toEqual(['$LATEST', '1', '2']);
+ });
+});
diff --git a/docs/services/lambda.md b/docs/services/lambda.md
index d402f1cc8d..a47bf72779 100644
--- a/docs/services/lambda.md
+++ b/docs/services/lambda.md
@@ -166,6 +166,13 @@ services:
Function URLs are also reachable directly on `/{proxy:.*}` under the Lambda URL controller, which routes the request into the normal `Invoke` path.
+**Versions:** `CreateFunction` and `UpdateFunctionCode` honour `Publish`, publishing a version
+and reporting it in the response's `Version`. The two differ in the ARN they return, matching the
+live service: `CreateFunction` keeps the unqualified `FunctionArn` while `UpdateFunctionCode`
+returns the qualified one (`...:function:name:2`), as `PublishVersion` does. Without `Publish`
+both answer for `$LATEST` and create nothing. `UpdateFunctionConfiguration` has no `Publish`
+parameter in the AWS API and none here.
+
**Layers:** `PublishLayerVersion`, `GetLayerVersion`, `GetLayerVersionByArn`, `ListLayerVersions`,
`ListLayers`, and `DeleteLayerVersion` are implemented, with real local storage under
`{lambda.codePath}/layers/{name}/{version}`. `CreateFunction`/`UpdateFunctionConfiguration`
diff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
index b1bc49bf24..dc05a11544 100644
--- a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
+++ b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java
@@ -70,8 +70,10 @@ public class LambdaController {
@SuppressWarnings("unchecked")
Map<String, Object> request = objectMapper.readValue(body, Map.class);
LambdaFunction fn = lambdaService.createFunction(region, request);
+ Map<String, Object> configuration = buildFunctionConfiguration(fn);
+ unqualifyArn(configuration);
return Response.status(201)
- .entity(buildFunctionConfiguration(fn))
+ .entity(configuration)
.build();
} catch (AwsException e) {
throw e;
@@ -585,6 +587,18 @@ public class LambdaController {
return result;
}
+ /**
+ * CreateFunction reports the version it published but keeps the unqualified ARN, unlike
+ * UpdateFunctionCode and PublishVersion which both answer with the qualified form. Measured
+ * against the live service; the reference does not distinguish them.
+ */
+ private static void unqualifyArn(Map<String, Object> configuration) {
+ if (configuration.get("FunctionArn") instanceof String arn
+ && !"$LATEST".equals(configuration.get("Version"))) {
+ configuration.put("FunctionArn", arn.substring(0, arn.lastIndexOf(':')));
+ }
+ }
+
private Map<String, Object> buildFunctionConfiguration(LambdaFunction fn) {
ObjectNode node = objectMapper.createObjectNode();
node.put("FunctionName", fn.getFunctionName());
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 73df4b0258..cc59b12a39 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
@@ -454,6 +454,9 @@ public class LambdaService implements ResourceProvider {
functionStore.save(region, fn);
LOG.infov("Created Lambda function: {0} in region {1}", functionName, region);
+ if (Boolean.TRUE.equals(request.get("Publish"))) {
+ return publishVersion(region, functionName, null);
+ }
return fn;
}
@@ -530,6 +533,9 @@ public class LambdaService implements ResourceProvider {
functionStore.save(region, fn);
LOG.infov("Updated code for function: {0}", functionName);
+ if (Boolean.TRUE.equals(request.get("Publish"))) {
+ return publishVersion(region, functionName, null);
+ }
return fn;
}
diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishFlagIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishFlagIntegrationTest.java
new file mode 100644
index 0000000000..93d1586cc2
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishFlagIntegrationTest.java
@@ -0,0 +1,220 @@
+package io.github.hectorvent.floci.services.lambda;
+
+import io.quarkus.test.junit.QuarkusTest;
+import org.junit.jupiter.api.MethodOrderer;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+import java.io.ByteArrayOutputStream;
+import java.util.Base64;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.endsWith;
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.not;
+
+/**
+ * The Publish flag on CreateFunction and UpdateFunctionCode.
+ *
+ * <p>Response shapes here were measured against the live service, which is not consistent
+ * between the two: CreateFunction reports the published version but answers with the
+ * unqualified ARN, while UpdateFunctionCode returns the qualified one.
+ */
+@QuarkusTest
+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
+class LambdaPublishFlagIntegrationTest {
+
+ private static final String FN = "publish-flag-fn";
+ private static final String FN_NO_PUBLISH = "publish-flag-nopub-fn";
+ private static final String ROLE = "arn:aws:iam::000000000000:role/lambda-role";
+
+ private static String zipBase64(String marker) throws Exception {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (ZipOutputStream zos = new ZipOutputStream(baos)) {
+ zos.putNextEntry(new ZipEntry("handler.py"));
+ zos.write(("def handler(e, c):\n return '" + marker + "'\n").getBytes());
+ zos.closeEntry();
+ }
+ return Base64.getEncoder().encodeToString(baos.toByteArray());
+ }
+
+ private static String createBody(String name, String marker, boolean publish) throws Exception {
+ return """
+ {
+ "FunctionName": "%s",
+ "Runtime": "python3.12",
+ "Role": "%s",
+ "Handler": "handler.handler",
+ "Code": { "ZipFile": "%s" },
+ "Publish": %s
+ }
+ """.formatted(name, ROLE, zipBase64(marker), publish);
+ }
+
+ @Test
+ @Order(1)
+ void createWithPublishReturnsVersionOneAndAnUnqualifiedArn() throws Exception {
+ given()
+ .contentType("application/json")
+ .body(createBody(FN, "v1", true))
+ .when()
+ .post("/2015-03-31/functions")
+ .then()
+ .statusCode(201)
+ .body("Version", equalTo("1"))
+ // Measured: CreateFunction keeps the plain ARN even when it publishes.
+ .body("FunctionArn", endsWith(":function:" + FN))
+ .body("FunctionArn", not(endsWith(":1")));
+ }
+
+ @Test
+ @Order(2)
+ void createWithPublishActuallyCreatesTheVersion() {
+ given()
+ .when()
+ .get("/2015-03-31/functions/" + FN + "/versions")
+ .then()
+ .statusCode(200)
+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1"));
+ }
+
+ @Test
+ @Order(3)
+ void unqualifiedGetStillDescribesLatest() {
+ given()
+ .when()
+ .get("/2015-03-31/functions/" + FN)
+ .then()
+ .statusCode(200)
+ .body("Configuration.Version", equalTo("$LATEST"));
+ }
+
+ @Test
+ @Order(4)
+ void updateCodeWithPublishReturnsTheNextVersionAndAQualifiedArn() throws Exception {
+ given()
+ .contentType("application/json")
+ .body("{\"ZipFile\": \"" + zipBase64("v2") + "\", \"Publish\": true}")
+ .when()
+ .put("/2015-03-31/functions/" + FN + "/code")
+ .then()
+ .statusCode(200)
+ .body("Version", equalTo("2"))
+ // Measured: unlike CreateFunction, this one is qualified.
+ .body("FunctionArn", endsWith(":function:" + FN + ":2"));
+
+ given()
+ .when()
+ .get("/2015-03-31/functions/" + FN + "/versions")
+ .then()
+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1", "2"));
+ }
+
+ @Test
+ @Order(5)
+ void updateCodeWithoutPublishReturnsLatestAndCreatesNoVersion() throws Exception {
+ given()
+ .contentType("application/json")
+ .body("{\"ZipFile\": \"" + zipBase64("v3") + "\"}")
+ .when()
+ .put("/2015-03-31/functions/" + FN + "/code")
+ .then()
+ .statusCode(200)
+ .body("Version", equalTo("$LATEST"))
+ .body("FunctionArn", endsWith(":function:" + FN));
+
+ given()
+ .when()
+ .get("/2015-03-31/functions/" + FN + "/versions")
+ .then()
+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1", "2"));
+ }
+
+ @Test
+ @Order(6)
+ void publishedVersionKeepsTheCodeItWasPublishedFrom() {
+ // Version 1 was published from v1's code while $LATEST has since moved to v3, so their
+ // CodeSha256 must differ — the point of publishing being an immutable snapshot.
+ String latestSha = given()
+ .when()
+ .get("/2015-03-31/functions/" + FN)
+ .then()
+ .statusCode(200)
+ .extract().path("Configuration.CodeSha256");
+
+ String versionOneSha = given()
+ .when()
+ .get("/2015-03-31/functions/" + FN + "/versions")
+ .then()
+ .statusCode(200)
+ .extract().path("Versions.find { it.Version == '1' }.CodeSha256");
+
+ org.junit.jupiter.api.Assertions.assertNotEquals(latestSha, versionOneSha);
+ }
+
+ @Test
+ @Order(7)
+ void createWithoutPublishReturnsLatestAndCreatesNoVersion() throws Exception {
+ given()
+ .contentType("application/json")
+ .body(createBody(FN_NO_PUBLISH, "v1", false))
+ .when()
+ .post("/2015-03-31/functions")
+ .then()
+ .statusCode(201)
+ .body("Version", equalTo("$LATEST"))
+ .body("FunctionArn", endsWith(":function:" + FN_NO_PUBLISH));
+
+ given()
+ .when()
+ .get("/2015-03-31/functions/" + FN_NO_PUBLISH + "/versions")
+ .then()
+ .body("Versions.Version", containsInAnyOrder("$LATEST"));
+ }
+
+ @Test
+ @Order(8)
+ void omittingPublishEntirelyBehavesAsFalse() throws Exception {
+ String name = FN_NO_PUBLISH + "-omitted";
+ given()
+ .contentType("application/json")
+ .body("""
+ {
+ "FunctionName": "%s",
+ "Runtime": "python3.12",
+ "Role": "%s",
+ "Handler": "handler.handler",
+ "Code": { "ZipFile": "%s" }
+ }
+ """.formatted(name, ROLE, zipBase64("v1")))
+ .when()
+ .post("/2015-03-31/functions")
+ .then()
+ .statusCode(201)
+ .body("Version", equalTo("$LATEST"));
+
+ given()
+ .when()
+ .delete("/2015-03-31/functions/" + name)
+ .then()
+ .statusCode(204);
+ }
+
+ // ── cleanup ───────────────────────────────────────────────────────────────
+
+ @Test
+ @Order(9)
+ void cleanup_deleteFunctions() {
+ for (String name : new String[] {FN, FN_NO_PUBLISH}) {
+ given()
+ .when()
+ .delete("/2015-03-31/functions/" + name)
+ .then()
+ .statusCode(204);
+ }
+ }
+}