fix(lambda): honour the CodeSha256 precondition on PublishVersion (#2939)

* fix(lambda): honour the CodeSha256 precondition on PublishVersion

CodeSha256 is documented as a precondition: "only publish a version if the
hash value matches the value that's specified". The controller parsed only
Description out of the request body, so the field never reached the service
and a publish that should have been rejected succeeded and produced a
version. A caller that raced someone else's deploy published code it had
never authorised, with nothing to say so.

A mismatch is now InvalidParameterValueException carrying the message shape
AWS uses, and no version is created. The check sits inside the lock
UpdateFunctionCode takes, so the hash cannot be validated against one state
of $LATEST and the snapshot then taken from another.

Opt in: a request without the field behaves exactly as before, which
omittingCodeSha256StillPublishes pins.

Part of #2822; the unchanged-publish half follows separately because it
changes behaviour for existing callers.

* fix(lambda): close the CodeSha256 race and reject malformed preconditions

Two gaps found in review of the precondition itself.

The check was not atomic with UpdateFunctionCode. The earlier claim that it
sat inside that lock was wrong: extractZipCodeBytes sets codeLocalPath,
codeSizeBytes and codeSha256 with no lock held, and the only synchronized
block in there wraps an unrelated legacy-directory cleanup further down. So
PublishVersion holding its own lock serialised nothing, and a deploy landing
between the hash matching and the snapshot being taken still published code
the caller had not authorised.

Make the writer take the lock. Hashing stays outside it, being pure
computation on bytes already in hand, as does extraction to disk so a large
package does not serialise unrelated work; only the fields that decide what
a snapshot copies are published inside it.

A malformed precondition also bypassed the check. {"CodeSha256": 12345}
throws a ClassCastException into the body-parse catch, leaving the field
null and indistinguishable from omitted, so the publish succeeded with 201.
An unparseable body behaved the same way. Both are now 400: field extraction
rejects a wrong JSON type rather than letting the cast fail silently, and a
body that cannot be parsed is an error rather than an empty request.

* fix(lambda): reject a null JSON body on PublishVersion

A body of literal "null" is valid JSON that parses cleanly to a null map, so
it never reaches the parse-failure path and then threw a
NullPointerException on the field reads, surfacing as a 500 rather than a
400.

Guarded outside the try rather than inside it. Inside, the exception would
be caught by that method's own catch and rewrapped as a parse failure, which
it is not, giving "Could not parse request body: Request body must be a JSON
object".

* fix(lambda): compare a blank CodeSha256 rather than treating it as absent

An isBlank() check short-circuited the whole condition, so an explicit empty
or whitespace-only CodeSha256 skipped the comparison and published without
checking anything: the same present-but-malformed value behaving like an
absent one that the rest of this branch addresses.

The exclusion is simply removed, so an empty string is compared like any
other value and fails as a mismatch. Rejecting it with a dedicated error
would mean inventing an error shape for the empty case that has not been
measured against the live service; a mismatch is one AWS demonstrably
produces for a hash that does not match.
This commit is contained in:
David authored and GitHub committed 2026-09-02 18:41:14 -04:00
1 parent 97ce09f22a
commit 3d2b8828ad
3 files changed
+232 -7

No files matched your search

@@ -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<String, Object> req;
try {
@SuppressWarnings("unchecked")
Map<String, Object> req = objectMapper.readValue(body, Map.class);
description = (String) req.get("Description");
} catch (Exception ignored) {}
Map<String, Object> 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<String, Object> 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,
@@ -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}.
*
* <p>{@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")) {
@@ -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));
}
}