Light, fluffy, and always free - The AWS Local Emulator alternative
fix(lambda): delete only the named version when DeleteFunction has a Qualifier (#2824)
Brian Taylorca4c84c9e0f0
diff --git a/compatibility-tests/sdk-test-node/tests/lambda.test.ts b/compatibility-tests/sdk-test-node/tests/lambda.test.tsindex 02124dc00c..54349ecfc4 100644--- a/compatibility-tests/sdk-test-node/tests/lambda.test.ts+++ b/compatibility-tests/sdk-test-node/tests/lambda.test.ts@@ -241,3 +241,72 @@ describe('Lambda Publish flag', () => {expect((listed.Versions ?? []).map((v) => v.Version).sort()).toEqual(['$LATEST', '1', '2']);});});++describe('Lambda version deletion', () => {+ let lambda: LambdaClient;+ let fnName: string;++ const versions = async () => {+ const r = await lambda.send(new ListVersionsByFunctionCommand({ FunctionName: fnName }));+ return (r.Versions ?? []).map((v) => v.Version).sort();+ };++ beforeAll(async () => {+ lambda = makeClient(LambdaClient);+ fnName = `test-delver-${uniqueName()}`;++ 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;')) },+ }));+ await lambda.send(new PublishVersionCommand({ FunctionName: fnName }));+ await lambda.send(new UpdateFunctionCodeCommand({+ FunctionName: fnName,+ ZipFile: buildMinimalZip('index.js', Buffer.from('exports.handler = async () => 2;')),+ }));+ await lambda.send(new PublishVersionCommand({ FunctionName: fnName }));+ });++ afterAll(async () => {+ await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName })).catch(() => {});+ });++ it('should delete only the qualified version, leaving the function intact', async () => {+ expect(await versions()).toEqual(['$LATEST', '1', '2']);++ await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName, Qualifier: '2' }));++ // The function survives — before this was fixed, the whole function was deleted.+ const fn = await lambda.send(new GetFunctionCommand({ FunctionName: fnName }));+ expect(fn.Configuration?.FunctionName).toBe(fnName);+ expect(await versions()).toEqual(['$LATEST', '1']);+ });++ it('should refuse to delete $LATEST by qualifier', async () => {+ await expect(+ lambda.send(new DeleteFunctionCommand({ FunctionName: fnName, Qualifier: '$LATEST' }))+ ).rejects.toThrow(/cannot be deleted without deleting the function/);+ expect(await versions()).toEqual(['$LATEST', '1']);+ });++ it('should refuse to delete a version an alias references', async () => {+ await lambda.send(new CreateAliasCommand({+ FunctionName: fnName,+ Name: 'pinned',+ FunctionVersion: '1',+ }));++ await expect(+ lambda.send(new DeleteFunctionCommand({ FunctionName: fnName, Qualifier: '1' }))+ ).rejects.toThrow(/aliases reference it/);+ expect(await versions()).toEqual(['$LATEST', '1']);+ });++ it('should treat a version that does not exist as a no-op', async () => {+ await lambda.send(new DeleteFunctionCommand({ FunctionName: fnName, Qualifier: '99' }));+ expect(await versions()).toEqual(['$LATEST', '1']);+ });+});diff --git a/docs/services/lambda.md b/docs/services/lambda.mdindex 2cdb5cd2ff..5b0be8cb1c 100644--- a/docs/services/lambda.md+++ b/docs/services/lambda.md@@ -173,6 +173,13 @@ returns the qualified one (`...:function:name:2`), as `PublishVersion` does. Witboth answer for `$LATEST` and create nothing. `UpdateFunctionConfiguration` has no `Publish`parameter in the AWS API and none here.+`DeleteFunction` honours `Qualifier` — it removes that published version only, leaving `$LATEST`,+the other versions and the function's aliases in place; without a qualifier the whole function+goes. Matching the live service, deleting `$LATEST` by qualifier and naming an alias are both+rejected with `InvalidParameterValueException`, a version an alias points at is a+`ResourceConflictException`, and a version that does not exist is a silent success rather than+a 404.+**Layers:** `PublishLayerVersion`, `GetLayerVersion`, `GetLayerVersionByArn`, `ListLayerVersions`,`ListLayers`, and `DeleteLayerVersion` are implemented, with real local storage under`{lambda.codePath}/layers/{name}/{version}`. `ListLayers` and `ListLayerVersions` honourdiff --git a/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.java b/src/main/java/io/github/hectorvent/floci/services/lambda/LambdaController.javaindex dc05a11544..134dbfdc19 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@@ -196,9 +196,10 @@ public class LambdaController {@DELETE@Path("/functions/{functionName}")public Response deleteFunction(@Context HttpHeaders headers,- @PathParam("functionName") String functionName) {+ @PathParam("functionName") String functionName,+ @QueryParam("Qualifier") String qualifier) {String region = regionResolver.resolveRegion(headers);- lambdaService.deleteFunction(region, functionName);+ lambdaService.deleteFunction(region, functionName, qualifier);return Response.noContent().build();}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.javaindex cc59b12a39..6dea6670da 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@@ -57,6 +57,14 @@ import java.util.regex.Pattern;public class LambdaService implements ResourceProvider {private static final Logger LOG = Logger.getLogger(LambdaService.class);++ /**+ * Qualifier constraint the live service enforces, taken from its own ValidationException+ * rather than the API reference, which publishes a laxer pattern. Notably it is ASCII-only,+ * so a non-ASCII digit is rejected here rather than being read as a version number.+ */+ private static final String QUALIFIER_PATTERN = "\\$(LATEST(\\.PUBLISHED)?)|[a-zA-Z0-9-_$]+";+ private static final Pattern QUALIFIER = Pattern.compile(QUALIFIER_PATTERN);private static final Pattern EFS_ACCESS_POINT_ARN = Pattern.compile("^arn:aws[a-zA-Z-]*:elasticfilesystem:(?:eusc-)?[a-z]{2}"+ "(?:(?:-gov)|(?:-iso(?:b)?))?-[a-z]+-\\d:"@@ -706,7 +714,74 @@ public class LambdaService implements ResourceProvider {return fn;}+ /**+ * DeleteFunction without a Qualifier: removes the function and every version of it.+ */public void deleteFunction(String region, String functionName) {+ deleteFunction(region, functionName, null);+ }++ /**+ * DeleteFunction. A Qualifier names a single published version to remove, leaving the+ * function and its other versions in place; without one the whole function goes.+ */+ public void deleteFunction(String region, String functionName, String qualifier) {+ if (qualifier != null && !qualifier.isEmpty()) {+ deleteFunctionVersion(region, functionName, qualifier);+ return;+ }+ deleteWholeFunction(region, functionName);+ }++ /**+ * Removes one published version. Error behaviour follows the live service: deleting+ * {@code $LATEST} or naming an alias is rejected, a version an alias points at is a+ * conflict, and a version that does not exist is a silent success rather than a 404.+ */+ private void deleteFunctionVersion(String region, String functionName, String qualifier) {+ if (!QUALIFIER.matcher(qualifier).matches()) {+ throw new AwsException("ValidationException",+ "1 validation error detected: Value '" + qualifier + "' at 'qualifier' failed"+ + " to satisfy constraint: Member must satisfy regular expression"+ + " pattern: " + QUALIFIER_PATTERN, 400);+ }+ LambdaFunction fn = getFunction(region, functionName);+ if ("$LATEST".equals(qualifier)) {+ throw new AwsException("InvalidParameterValueException",+ "$LATEST version cannot be deleted without deleting the function.", 400);+ }+ if (!qualifier.chars().allMatch(c -> c >= '0' && c <= '9')) {+ // A non-numeric qualifier names an alias, which the live service refuses to+ // resolve here rather than deleting the version behind it.+ throw new AwsException("InvalidParameterValueException",+ "Deletion of aliases is not currently supported.", 400);+ }+ String name = fn.getFunctionName();+ List<String> referencing = aliasStore == null ? List.of()+ : aliasStore.list(region, name).stream()+ .filter(alias -> qualifier.equals(alias.getFunctionVersion()))+ .map(LambdaAlias::getName)+ .toList();+ if (!referencing.isEmpty()) {+ throw new AwsException("ResourceConflictException",+ "Unable to delete version because the following aliases reference it: "+ + referencing, 409);+ }+ Optional<LambdaFunction> version = functionStore.get(region, name, qualifier);+ if (version.isEmpty()) {+ return;+ }+ synchronized (lockForConcurrencyOp(fn.getFunctionArn())) {+ warmPool.drainEnvironment(version.get());+ functionStore.deleteVersion(region, name, qualifier);+ // The snapshot shares $LATEST's code directory, so this only reclaims once no+ // remaining version references it.+ reclaimLegacyCodeDirectoryIfUnused(name);+ }+ LOG.infov("Deleted version {0} of Lambda function: {1}", qualifier, name);+ }++ private void deleteWholeFunction(String region, String functionName) {LambdaFunction fn = getFunction(region, functionName); // throws 404 if not foundfunctionName = fn.getFunctionName();String arn = fn.getFunctionArn();diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDeleteFunctionQualifierIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDeleteFunctionQualifierIntegrationTest.javanew file mode 100644index 0000000000..ec5da17868--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaDeleteFunctionQualifierIntegrationTest.java@@ -0,0 +1,286 @@+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.containsString;+import static org.hamcrest.Matchers.equalTo;++/**+ * DeleteFunction with a Qualifier removes one published version, not the function.+ *+ * <p>Behaviour here mirrors the live service, which was measured for each case: deleting+ * {@code $LATEST} or an alias name is rejected, a version an alias references is a conflict,+ * a version that does not exist is a silent success, and the function, its other versions+ * and its aliases all survive.+ */+@QuarkusTest+@TestMethodOrder(MethodOrderer.OrderAnnotation.class)+class LambdaDeleteFunctionQualifierIntegrationTest {++ private static final String FN = "del-qualifier-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 void updateCode(String marker) throws Exception {+ given()+ .contentType("application/json")+ .body("{\"ZipFile\": \"" + zipBase64(marker) + "\"}")+ .when()+ .put("/2015-03-31/functions/" + FN + "/code")+ .then()+ .statusCode(200);+ }++ private static void publish() {+ given()+ .contentType("application/json")+ .body("{}")+ .when()+ .post("/2015-03-31/functions/" + FN + "/versions")+ .then()+ .statusCode(201);+ }++ @Test+ @Order(1)+ void seedFunctionWithThreeVersions() throws Exception {+ given()+ .contentType("application/json")+ .body("""+ {+ "FunctionName": "%s",+ "Runtime": "python3.12",+ "Role": "%s",+ "Handler": "handler.handler",+ "Code": { "ZipFile": "%s" }+ }+ """.formatted(FN, ROLE, zipBase64("v1")))+ .when()+ .post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ publish(); // version 1+ updateCode("v2");+ publish(); // version 2+ updateCode("v3");+ publish(); // version 3++ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/versions")+ .then()+ .statusCode(200)+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1", "2", "3"));+ }++ @Test+ @Order(2)+ void deletingLatestByQualifierIsRejected() {+ given()+ .queryParam("Qualifier", "$LATEST")+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterValueException"))+ .body("message", equalTo("$LATEST version cannot be deleted without deleting the function."));+ }++ @Test+ @Order(3)+ void deletingByAliasNameIsRejected() {+ given()+ .queryParam("Qualifier", "notaversion")+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(400)+ .body("__type", equalTo("InvalidParameterValueException"))+ .body("message", equalTo("Deletion of aliases is not currently supported."));+ }++ @Test+ @Order(3)+ void nonAsciiQualifierIsRejectedByThePattern() {+ // Character.isDigit accepts non-ASCII decimal digits, so a full-width or Arabic-Indic+ // digit would otherwise be read as a version number and answered with a silent 204.+ // The live service pattern-validates the qualifier first; measured on GetFunction,+ // which enforces the same constraint.+ for (String qualifier : new String[] {"\uFF13", "\u0663"}) {+ given()+ .queryParam("Qualifier", qualifier)+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(400)+ .body("__type", equalTo("ValidationException"))+ .body("message", containsString("at 'qualifier' failed to satisfy constraint"));+ }++ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/versions")+ .then()+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1", "2", "3"));+ }++ @Test+ @Order(4)+ void deletingAVersionThatDoesNotExistSucceedsSilently() {+ // Measured: the live service returns success and changes nothing, rather than 404.+ given()+ .queryParam("Qualifier", "99")+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(204);++ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/versions")+ .then()+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1", "2", "3"));+ }++ @Test+ @Order(5)+ void versionReferencedByAnAliasCannotBeDeleted() {+ given()+ .contentType("application/json")+ .body("{\"Name\": \"live\", \"FunctionVersion\": \"1\"}")+ .when()+ .post("/2015-03-31/functions/" + FN + "/aliases")+ .then()+ .statusCode(201);++ given()+ .queryParam("Qualifier", "1")+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(409)+ .body("__type", equalTo("ResourceConflictException"))+ .body("message", equalTo(+ "Unable to delete version because the following aliases reference it: [live]"));++ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/versions")+ .then()+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1", "2", "3"));+ }++ @Test+ @Order(6)+ void deletingAnUnreferencedVersionRemovesOnlyThatVersion() {+ given()+ .queryParam("Qualifier", "2")+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(204);++ // The regression this test exists for: before the qualifier was honoured, this call+ // deleted the whole function.+ given()+ .when()+ .get("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(200)+ .body("Configuration.FunctionName", equalTo(FN));++ // Checked through ListVersionsByFunction rather than a qualified GetFunction:+ // GetFunction ignores Qualifier today and would answer for $LATEST either way.+ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/versions")+ .then()+ .body("Versions.Version", containsInAnyOrder("$LATEST", "1", "3"));++ // The alias, pointing at a different version, is untouched.+ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/aliases/live")+ .then()+ .statusCode(200)+ .body("FunctionVersion", equalTo("1"));+ }++ @Test+ @Order(8)+ void deleteWithoutAQualifierStillRemovesTheWholeFunction() {+ given()+ .when()+ .delete("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(204);++ given()+ .when()+ .get("/2015-03-31/functions/" + FN)+ .then()+ .statusCode(404);++ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "/versions")+ .then()+ .statusCode(404);+ }++ @Test+ @Order(9)+ void emptyQualifierIsTreatedAsAbsent() throws Exception {+ // RESTEasy binds an empty query value as null, so ?Qualifier= is a whole-function+ // delete; pinned so the distinction is not lost if that binding ever changes.+ given()+ .contentType("application/json")+ .body("""+ {+ "FunctionName": "%s-empty",+ "Runtime": "python3.12",+ "Role": "%s",+ "Handler": "handler.handler",+ "Code": { "ZipFile": "%s" }+ }+ """.formatted(FN, ROLE, zipBase64("v1")))+ .when()+ .post("/2015-03-31/functions")+ .then()+ .statusCode(201);++ given()+ .queryParam("Qualifier", "")+ .when()+ .delete("/2015-03-31/functions/" + FN + "-empty")+ .then()+ .statusCode(204);++ given()+ .when()+ .get("/2015-03-31/functions/" + FN + "-empty")+ .then()+ .statusCode(404);+ }+}