From ebd849a956147bcc9c5e2e3fa945f716ac2cb671 Mon Sep 17 00:00:00 2001 From: David Date: Tue, 8 Sep 2026 12:23:24 +0100 Subject: [PATCH] fix(lambda): serialise the version snapshot against function updates (#3010) publishVersion copies roughly thirty fields off the live LambdaFunction inside synchronized (lockForConcurrencyOp(...)), but neither updater took that lock, so nothing was serialised. An update landing mid-copy produced a snapshot that was part old code and part new configuration, carrying a sourceRevisionId that identified neither state. #2939 made extractZipCodeBytes publish the code identity fields under the lock, which closed the CodeSha256 precondition hole specifically. The rest of the snapshot copy stayed unprotected, and updateFunctionConfiguration never took the lock at all. Both updaters now take the same per-function lock. Their bodies move unchanged into private *Locked methods behind a thin wrapper, so the change is a small number of production lines rather than a few hundred lines of reindentation. The monitor is one object per function ARN and synchronized is reentrant, so the nested acquisitions inside extractZipCodeBytes, and publishVersion's own when updateFunctionCode is called with Publish, are no-ops rather than a second lock. Every existing acquisition is keyed to a single function, so there is no cross-ARN ordering to invert. Zip extraction now runs inside the lock. extractZipCodeBytes called extractTo outside it and took the lock only to publish the code fields afterwards, so a deploy could rewrite $LATEST's code directory while publishVersion held the lock copying that directory into a version's own (#3041). Serialising the whole updater closes that too. UpdateFunctionConfiguration's structure members stay shape-checked ahead of the function lookup, where #3051 put them, so a malformed member on a function that does not exist still reports SerializationException rather than 404. The locked body re-reads them; structureMember is pure, so the second read cannot fail once the first has passed. That ordering was not pinned by any test, and now is. This also corrects a comment from #2939 claiming the hash check ran "inside the lock UpdateFunctionCode takes". UpdateFunctionCode did not take a lock. Closes #3007 --- .../floci/services/lambda/LambdaService.java | 55 +++++++++++++++--- .../services/lambda/LambdaServiceTest.java | 58 +++++++++++++++++++ ...StructureSerializationIntegrationTest.java | 18 ++++++ 3 files changed, 124 insertions(+), 7 deletions(-) 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 0512207290..38a24a1b16 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 @@ -81,6 +81,15 @@ public class LambdaService implements ResourceProvider { private static final int MAX_HANDLER_LENGTH = 128; private static final List FUNCTION_ARCHITECTURES = List.of("x86_64", "arm64"); + /** + * Structure members {@code UpdateFunctionConfiguration} accepts. Shape-checked before the + * function lookup so a malformed member reports SerializationException rather than 404 (#3051), + * which is why the list is named here rather than left implicit in the extraction below. + */ + private static final List CONFIG_STRUCTURE_MEMBERS = List.of( + "Environment", "EphemeralStorage", "TracingConfig", "DeadLetterConfig", + "VpcConfig", "SnapStart", "LoggingConfig", "ImageConfig"); + private final LambdaFunctionStore functionStore; private final LambdaExecutorService executorService; private final LambdaConcurrencyLimiter concurrencyLimiter; @@ -599,7 +608,20 @@ public class LambdaService implements ResourceProvider { public LambdaFunction updateFunctionCode(String region, String functionName, Map request) { LambdaFunction fn = getFunction(region, functionName); - functionName = fn.getFunctionName(); + // publishVersion copies roughly thirty fields off this same live object. Without the + // updaters holding the lock it copies under, an update landing mid-copy yields a snapshot + // that is part old code and part new configuration, carrying a sourceRevisionId that + // identifies neither state (issue #3007). The monitor is reentrant and per function ARN, so + // the nested acquisitions further down, and publishVersion's own when Publish is set, are + // no-ops rather than a second lock. + synchronized (lockForConcurrencyOp(fn.getFunctionArn())) { + return updateFunctionCodeLocked(region, fn, request); + } + } + + private LambdaFunction updateFunctionCodeLocked(String region, LambdaFunction fn, + Map request) { + String functionName = fn.getFunctionName(); List architectures = validateArchitectures(request.get("Architectures")); String zipFileBase64 = (String) request.get("ZipFile"); @@ -642,6 +664,27 @@ public class LambdaService implements ResourceProvider { } public LambdaFunction updateFunctionConfiguration(String region, String functionName, Map request) { + // Shape-checked ahead of the lookup, which is where #3051 put these: a malformed member on + // a function that does not exist reports SerializationException, not 404. Splitting the + // mutation into a locked body below must not move them behind the lookup, so they stay + // here and the locked body re-reads them. structureMember is pure, so the second read + // cannot fail once these have passed. + for (String member : CONFIG_STRUCTURE_MEMBERS) { + structureMember(request, member); + } + + LambdaFunction fn = getFunction(region, functionName); + // Same reason as updateFunctionCode: publishVersion's snapshot copy must not observe a + // half-applied configuration change (issue #3007). + synchronized (lockForConcurrencyOp(fn.getFunctionArn())) { + return updateFunctionConfigurationLocked(region, fn, request); + } + } + + private LambdaFunction updateFunctionConfigurationLocked(String region, LambdaFunction fn, + Map request) { + String functionName = fn.getFunctionName(); + List architectures = validateArchitectures(request.get("Architectures")); Map environment = structureMember(request, "Environment"); Map environmentVariables = environmentVariables(environment); Map ephemeralStorage = structureMember(request, "EphemeralStorage"); @@ -652,9 +695,6 @@ public class LambdaService implements ResourceProvider { Map loggingConfig = structureMember(request, "LoggingConfig"); Map imageConfig = structureMember(request, "ImageConfig"); - LambdaFunction fn = getFunction(region, functionName); - List architectures = validateArchitectures(request.get("Architectures")); - // Validated before any field mutation below, not inline where Layers is applied further // down - fn is the live object backing this store entry (InMemoryStorage#get returns the // same reference, not a copy), so validating this late would leave every @@ -1948,9 +1988,10 @@ 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. + // Inside the lock UpdateFunctionCode and UpdateFunctionConfiguration now take, 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 diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java index b756fec58d..6daf321c07 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaServiceTest.java @@ -20,6 +20,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.Base64; import java.util.HashSet; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; @@ -1580,4 +1581,61 @@ class LambdaServiceTest { } return Base64.getEncoder().encodeToString(baos.toByteArray()); } + + @Test + void updateFunctionCodeWaitsForAConcurrentHolderOfTheFunctionsConcurrencyLock() throws Exception { + assertUpdaterWaitsForTheLock("update-code-lock-fn", + (service, name) -> service.updateFunctionCode(REGION, name, + new HashMap<>(Map.of("ImageUri", "public.ecr.aws/x/y:1")))); + } + + @Test + void updateFunctionConfigurationWaitsForAConcurrentHolderOfTheFunctionsConcurrencyLock() throws Exception { + assertUpdaterWaitsForTheLock("update-config-lock-fn", + (service, name) -> service.updateFunctionConfiguration(REGION, name, + new HashMap<>(Map.of("Timeout", 42)))); + } + + /** + * publishVersion copies roughly thirty fields off the live function inside this lock. Neither + * updater used to take it, so nothing was serialised and a snapshot could be part old code and + * part new configuration (issue #3007). Proving each updater blocks on the lock closes that + * window regardless of the exact interleaving, rather than relying on timing to catch it. + */ + private void assertUpdaterWaitsForTheLock( + String functionName, + java.util.function.BiFunction updater) throws Exception { + LambdaFunction fn = service.createFunction(REGION, baseRequest(functionName)); + Object lock = service.lockForConcurrencyOp(fn.getFunctionArn()); + + ExecutorService pool = Executors.newFixedThreadPool(1); + CountDownLatch acquired = new CountDownLatch(1); + CountDownLatch release = new CountDownLatch(1); + Thread holder = new Thread(() -> { + synchronized (lock) { + acquired.countDown(); + try { + release.await(); + } catch (InterruptedException ignored) { + Thread.currentThread().interrupt(); + } + } + }); + try { + holder.start(); + assertTrue(acquired.await(2, java.util.concurrent.TimeUnit.SECONDS)); + + Future updateFuture = pool.submit(() -> updater.apply(service, functionName)); + assertThrows(java.util.concurrent.TimeoutException.class, + () -> updateFuture.get(200, java.util.concurrent.TimeUnit.MILLISECONDS), + "the updater must block while another operation holds this function's lock"); + + release.countDown(); + holder.join(); + assertNotNull(updateFuture.get(5, java.util.concurrent.TimeUnit.SECONDS)); + } finally { + release.countDown(); + pool.shutdownNow(); + } + } } diff --git a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java index c15966bf3d..15a6a37268 100644 --- a/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java +++ b/src/test/java/io/github/hectorvent/floci/services/lambda/LambdaStructureSerializationIntegrationTest.java @@ -56,6 +56,24 @@ class LambdaStructureSerializationIntegrationTest { } } + @Test + void updateFunctionConfigurationRejectsScalarStructureMembersOnAnUnknownFunction() { + // The shape check runs ahead of the function lookup, so a malformed member reports + // SerializationException rather than the 404 the lookup would raise. Pinned because this is + // ordering rather than logic: it holds only while the checks stay in front of getFunction, + // and nothing else fails if a refactor moves them behind it. + for (String member : FUNCTION_STRUCTURE_MEMBERS) { + given() + .contentType("application/json") + .body(Map.of(member, 5)) + .when() + .put(BASE_PATH + "/functions/structure-check-on-missing-function/configuration") + .then() + .statusCode(400) + .body("__type", equalTo("SerializationException")); + } + } + @Test void environmentVariablesRejectsScalarBeforeUpdateMutation() { Map createRequest = functionRequest("nested-environment-create");