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 f1fa679257..3cbddad8dc 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 @@ -395,17 +395,51 @@ public class LambdaController { String body) { String region = regionResolver.resolveRegion(headers); String description = null; + String codeSha256 = null; if (body != null && !body.isBlank()) { + Map req; try { @SuppressWarnings("unchecked") - Map req = objectMapper.readValue(body, Map.class); - description = (String) req.get("Description"); - } catch (Exception ignored) {} + Map parsed = objectMapper.readValue(body, Map.class); + req = parsed; + } catch (Exception e) { + // Swallowing this would treat a malformed body as an empty one, so a request whose + // CodeSha256 could not be read would publish instead of failing its precondition. + throw new AwsException("InvalidParameterValueException", + "Could not parse request body: " + e.getMessage(), 400); + } + if (req == null) { + // A literal "null" body parses cleanly to a null map, so it never reaches the catch + // above. Checked here rather than inside the try, where this exception would be + // caught by that same catch and rewrapped as a parse failure it is not. + throw new AwsException("InvalidParameterValueException", + "Request body must be a JSON object", 400); + } + description = stringField(req, "Description"); + codeSha256 = stringField(req, "CodeSha256"); } - LambdaFunction version = lambdaService.publishVersion(region, functionName, description); + LambdaFunction version = lambdaService.publishVersion(region, functionName, description, codeSha256); return Response.status(201).entity(buildFunctionConfiguration(version)).build(); } + /** + * Reads a string field, rejecting a value of the wrong JSON type rather than letting a cast + * failure be swallowed. A {@code CodeSha256} that arrives as a number or an object is a + * malformed precondition, and treating it as absent would publish without checking anything. + */ + private static String stringField(Map req, String name) { + Object value = req.get(name); + if (value == null) { + return null; + } + if (!(value instanceof String text)) { + throw new AwsException("InvalidParameterValueException", + name + " must be a string", 400); + } + return text; + } + + @GET @Path("/functions/{functionName}/versions") public Response listVersionsByFunction(@Context HttpHeaders headers, 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 b00dfd67c2..e57f338ff0 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 @@ -1383,6 +1383,18 @@ public class LambdaService implements ResourceProvider { } public LambdaFunction publishVersion(String region, String functionName, String description) { + return publishVersion(region, functionName, description, null); + } + + /** + * Publishes a version of {@code $LATEST}. + * + *

{@code CodeSha256} is a precondition: "only publish a version if the hash value matches the + * value that's specified". It was never parsed out of the request, so a caller that raced + * someone else's deploy published code it had not authorised, silently (issue #2822). + */ + public LambdaFunction publishVersion(String region, String functionName, String description, + String expectedCodeSha256) { LambdaFunction fn = getFunction(region, functionName); functionName = fn.getFunctionName(); // Shares the per-function lock deleteFunction and extractZipCodeBytes take around their @@ -1391,6 +1403,20 @@ public class LambdaService implements ResourceProvider { // delete, persisting a snapshot.codeLocalPath (below) that names a directory about to // be removed as unreferenced. synchronized (lockForConcurrencyOp(fn.getFunctionArn())) { + // Inside the lock UpdateFunctionCode takes, so the hash cannot be checked against one + // version of $LATEST and the snapshot then taken from another. Checking it outside + // would let an overlapping deploy publish code the caller never authorised. + // No isBlank() exclusion here. A present but empty value was previously treated as + // absent, so it skipped the comparison entirely and published without checking + // anything, which is the failure this precondition exists to prevent. It is simply + // compared like any other value and fails as a mismatch, which avoids inventing an + // error shape for the empty case that has not been measured against the live service. + if (expectedCodeSha256 != null && !expectedCodeSha256.equals(fn.getCodeSha256())) { + throw new AwsException("InvalidParameterValueException", + "CodeSHA256 (" + expectedCodeSha256 + ") is different from current CodeSHA256 in $LATEST", + 400); + } + int version = nextVersionNumber(versionCounterKey(region, fn), legacyVersionCounterKey(region, functionName)); LambdaFunction snapshot = new LambdaFunction(); @@ -2046,12 +2072,24 @@ public class LambdaService implements ResourceProvider { Path codePath = codeStore.getCodePath(ownerAccount(fn), fn.getFunctionName()); try { zipExtractor.extractTo(zipBytes, codePath); - fn.setCodeLocalPath(codePath.toAbsolutePath().normalize().toString()); - fn.setCodeSizeBytes(zipBytes.length); + // Publish the new code identity under the same per-function lock publishVersion holds. + // PublishVersion's CodeSha256 precondition is a check-then-act: it compares the hash and + // then snapshots the code. Mutating these fields without the lock lets an overlapping + // deploy move $LATEST between those two steps, so a version would carry code whose hash + // the caller never authorised even though the check passed. Extraction to disk stays + // outside the lock; only the fields that decide what a snapshot copies are inside it. + String newSha256 = null; try { byte[] digest = java.security.MessageDigest.getInstance("SHA-256").digest(zipBytes); - fn.setCodeSha256(Base64.getEncoder().encodeToString(digest)); + newSha256 = Base64.getEncoder().encodeToString(digest); } catch (java.security.NoSuchAlgorithmException ignored) {} + synchronized (lockForConcurrencyOp(fn.getFunctionArn())) { + fn.setCodeLocalPath(codePath.toAbsolutePath().normalize().toString()); + fn.setCodeSizeBytes(zipBytes.length); + if (newSha256 != null) { + fn.setCodeSha256(newSha256); + } + } // For file-based runtimes, verify handler file exists (skip Java and .NET which use different handler formats) if (fn.getRuntime() != null && !fn.getRuntime().startsWith("java") && !fn.getRuntime().startsWith("dotnet")) { diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishVersionCodeSha256IntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishVersionCodeSha256IntegrationTest.java new file mode 100644 index 0000000000..e68617d3ab --- /dev/null +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaPublishVersionCodeSha256IntegrationTest.java @@ -0,0 +1,153 @@ +package io.github.hectorvent.floci.services.lambda; + +import io.quarkus.test.junit.QuarkusTest; +import org.junit.jupiter.api.Test; + +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.containsString; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.not; + +/** + * Issue #2822, the CodeSha256 half. The field is a precondition: "only publish a version if the + * hash value matches the value that's specified". It was never parsed out of the request, so a + * publish that should have been rejected succeeded and produced a version, which is how a caller + * racing someone else's deploy ends up publishing code it never authorised. + */ +@QuarkusTest +class LambdaPublishVersionCodeSha256IntegrationTest { + + private static String zipB64(String body) 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 {'body': '" + body + "'}\n").getBytes("UTF-8")); + zos.closeEntry(); + } + return Base64.getEncoder().encodeToString(baos.toByteArray()); + } + + private static void createFunction(String name) throws Exception { + given() + .contentType("application/json") + .body(""" + {"FunctionName": "%s", "Runtime": "python3.12", + "Role": "arn:aws:iam::000000000000:role/r", "Handler": "handler.handler", + "Code": {"ZipFile": "%s"}} + """.formatted(name, zipB64("v1"))) + .when().post("/2015-03-31/functions") + .then().statusCode(org.hamcrest.Matchers.anyOf(equalTo(200), equalTo(201))); + } + + @Test + void aMismatchedCodeSha256IsRejectedAndPublishesNothing() throws Exception { + String fn = "pv-sha-" + Long.toString(System.nanoTime(), 36); + createFunction(fn); + + given() + .contentType("application/json") + .body("{\"CodeSha256\": \"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=\"}") + .when().post("/2015-03-31/functions/" + fn + "/versions") + .then() + .statusCode(400) + .body("message", containsString("different from current CodeSHA256")); + + // A rejected publish must not have produced a version: only $LATEST should be listed. + given().when().get("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(200).body("Versions.size()", equalTo(1)); + } + + @Test + void aMatchingCodeSha256Publishes() throws Exception { + String fn = "pv-sha-ok-" + Long.toString(System.nanoTime(), 36); + createFunction(fn); + + String sha = given().when().get("/2015-03-31/functions/" + fn + "/configuration") + .then().statusCode(200).extract().path("CodeSha256"); + + given() + .contentType("application/json") + .body("{\"CodeSha256\": \"%s\"}".formatted(sha)) + .when().post("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(201).body("Version", not(equalTo("$LATEST"))); + } + + @Test + void omittingCodeSha256StillPublishes() throws Exception { + // The precondition is opt in: a request without the field must behave exactly as before. + String fn = "pv-sha-none-" + Long.toString(System.nanoTime(), 36); + createFunction(fn); + + given().contentType("application/json").body("{}") + .when().post("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(201).body("Version", equalTo("1")); + } + + @Test + void aMalformedBodyIsRejectedRatherThanPublished() throws Exception { + // The parse failure used to be swallowed, so a body whose CodeSha256 could not be read was + // treated as one that never sent it: the precondition was skipped and a version published. + String fn = "pv-badbody-" + Long.toString(System.nanoTime(), 36); + createFunction(fn); + + given().contentType("application/json").body("{\"CodeSha256\": ") + .when().post("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(400); + + given().when().get("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(200).body("Versions.size()", equalTo(1)); + } + + @Test + void aNonStringCodeSha256IsRejectedRatherThanIgnored() throws Exception { + // A cast failure was swallowed the same way, so a hash sent as a number checked nothing. + String fn = "pv-badtype-" + Long.toString(System.nanoTime(), 36); + createFunction(fn); + + given().contentType("application/json").body("{\"CodeSha256\": 12345}") + .when().post("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(400); + + given().when().get("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(200).body("Versions.size()", equalTo(1)); + } + + @Test + void aNullJsonBodyIsRejectedRatherThanPublished() throws Exception { + // "null" is valid JSON and parses cleanly to a null map, so it never reaches the parse + // failure path. Without a guard the field reads would throw a NullPointerException, and a + // guard placed inside the try would be caught and reported as a parse failure it is not. + String fn = "pv-nullbody-" + Long.toString(System.nanoTime(), 36); + createFunction(fn); + + given().contentType("application/json").body("null") + .when().post("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(400); + + given().when().get("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(200).body("Versions.size()", equalTo(1)); + } + + @Test + void aBlankCodeSha256IsRejectedRatherThanTreatedAsOmitted() throws Exception { + // An explicit empty string is a present value, not an absent one. It was excluded from the + // comparison by an isBlank() check and so published without checking anything. It is now + // compared like any other value and fails as a mismatch, rather than getting an error shape + // invented for the empty case that has not been measured against the live service. + String fn = "pv-blank-" + Long.toString(System.nanoTime(), 36); + createFunction(fn); + + given().contentType("application/json").body("{\"CodeSha256\": \"\"}") + .when().post("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(400) + .body("message", containsString("different from current CodeSHA256")); + + given().when().get("/2015-03-31/functions/" + fn + "/versions") + .then().statusCode(200).body("Versions.size()", equalTo(1)); + } +}