fix(lambda): replace the extracted package instead of merging into it (#2672)

* fix(lambda): replace the extracted package instead of merging into it

ZipExtractor wrote entries into the function's code directory without
clearing it first, so each deploy was layered on top of the last. Nothing
on the path resets the directory: CodeStore.delete runs only when a
function is deleted, codeStore.exists() is never called, and every deploy
of a function resolves to the same code path. Extraction was a merge where
the domain requires a replace, so a file removed between two deploys
survived and stayed loadable -- a handler pointing at a deleted module kept
resolving and running stale code. Real AWS replaces the package wholesale.

Extract into a sibling staging directory and swap it in once the whole
archive has been read: on success the old tree is deleted and staging is
moved into place, on failure staging is discarded and the previous
deployment is left untouched. That also makes extraction all-or-nothing.

Safe because the code directory is not bind-mounted into Lambda
containers -- ContainerLauncher tar-copies it into /var/task at launch, and
the only bind for task code is the hot-reload path, which uses a different
directory that never goes through extractTo.

Closes #2647

* fix(lambda): keep the previous package until the new one is installed

The install deleted the live tree and then moved the new one into place, so
a failure in the move left the function with no code at all and nothing to
restore: a failed update destroyed a working deployment.

Rename the old tree aside instead, move the new one in, and delete the old
only once the new one has landed. Every failure path now ends with one
complete package on disk. The interval in which the target is absent is two
renames within a directory rather than a recursive delete followed by a
move; it is narrowed, not closed, because POSIX cannot atomically exchange
two directories, and the javadoc records that limit rather than implying
atomicity.

install() is package private so the failure path can be driven directly. It
is unreachable through extractTo, because a rename between siblings does not
fail under any condition a test can arrange there.

* fix(lambda): do not fail a deployment that already installed

Two failure paths in install() reported the wrong outcome.

Deleting the superseded package threw out of install(), so a filesystem
error at that point failed the deployment even though the new tree was
already in place and serving. The caller then skipped its metadata and warm
pool updates for code that was live. That deletion is now best effort: it
logs and leaves the tree behind, because leaving a directory costs disk and
is recoverable, while misreporting the outcome is not.

Restoring the previous package after a failed move was itself unguarded. If
the restore also threw, its exception replaced the original failure and the
working package was left under a generated name nothing would look for. The
restore is now guarded, the original failure stays the exception thrown, the
restore failure is attached to it, and the stranded path is logged so it can
be moved back by hand.

The cleanup path has a regression test. The restore path does not: reaching
it needs the install rename to fail while the restore rename also fails, and
both are renames in one directory, so either both succeed or the first
rename fails before install is reached.
This commit is contained in:
David authored and GitHub committed 2026-08-28 18:51:43 -04:00
1 parent 5c1b69c45f
commit e4c690351f
2 files changed
+226 -15

No files matched your search

@@ -6,15 +6,19 @@ import org.jboss.logging.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.AtomicMoveNotSupportedException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.Comparator;
import java.util.UUID;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/**
* Extracts ZIP bytes to a target directory.
* Extracts ZIP bytes to a target directory, replacing whatever was there before.
* Guards against path traversal attacks by validating entry names.
*/
@ApplicationScoped
@@ -27,7 +31,17 @@ public class ZipExtractor {
public void extractTo(byte[] zipBytes, Path targetDir) throws IOException {
// Resolve to absolute path so that normalize() on entry paths stays comparable
Path absTarget = targetDir.toAbsolutePath().normalize();
Files.createDirectories(absTarget);
Files.createDirectories(absTarget.getParent());
// Extract into a staging directory and swap it in, rather than writing over the target
// in place. A deployment package is the complete contents of the function, so a file
// dropped between two deploys has to disappear — writing in place only ever adds and
// overwrites, leaving removed files behind to stay loadable (issue #2647). Staging also
// makes extraction all-or-nothing: a failure part-way through leaves the previous
// deployment intact instead of a half-replaced mixture of the two.
Path staging = absTarget.resolveSibling(
absTarget.getFileName() + ".floci-staging-" + UUID.randomUUID());
Files.createDirectories(staging);
// Read the archive through its central directory (ZipFile) rather than sequentially
// over the local file headers (ZipInputStream). A streaming packager cannot seek back
@@ -71,8 +85,8 @@ public class ZipExtractor {
continue;
}
Path targetPath = absTarget.resolve(entryName).normalize();
if (!targetPath.startsWith(absTarget)) {
Path targetPath = staging.resolve(entryName).normalize();
if (!targetPath.startsWith(staging)) {
LOG.warnv("Skipping out-of-bounds ZIP entry: {0}", entryName);
continue;
}
@@ -85,13 +99,98 @@ public class ZipExtractor {
}
}
}
// Extraction succeeded in full: install the new tree.
install(staging, absTarget);
} finally {
Files.deleteIfExists(staged);
// A no-op once install() moved it; on failure this discards the partial staging tree
// and leaves the previous extraction untouched.
deleteRecursively(staging);
}
LOG.debugv("Extracted ZIP to: {0}", absTarget);
}
/**
* Installs the freshly extracted tree at {@code absTarget}, keeping the package already there
* until the new one is in place.
*
* <p>The old tree is renamed aside and deleted only after the new one lands, rather than
* deleted up front. Deleting first means a failure in the move leaves the function with no
* code at all and nothing to restore, turning a failed update into a destroyed deployment.
* Every failure path here ends with one complete package on disk.
*
* <p>Both steps are renames within one directory, so the interval in which the target is
* absent is two metadata operations rather than a recursive delete followed by a move. It is
* not zero: POSIX cannot atomically exchange two directories, so a launch landing exactly
* between the renames can still observe a missing code path. Closing that window entirely
* needs a lock shared with the launcher, which is wider than this change.
*
* <p>Package-private so the failure path can be exercised directly; it is not reachable
* otherwise, because a move between siblings only fails under conditions a test cannot
* arrange through {@link #extractTo}.
*/
static void install(Path staging, Path absTarget) throws IOException {
Path previous = null;
if (Files.exists(absTarget)) {
previous = absTarget.resolveSibling(
absTarget.getFileName() + ".floci-previous-" + UUID.randomUUID());
moveIntoPlace(absTarget, previous);
}
try {
moveIntoPlace(staging, absTarget);
} catch (IOException e) {
if (previous != null) {
try {
// Put the working package back before giving up.
moveIntoPlace(previous, absTarget);
} catch (IOException restoreFailed) {
// Both renames failed, so the function has no code at the canonical path and
// the working package is sitting under a generated name nobody will look for.
// Keep the original failure as the one thrown, attach this one, and say
// exactly where the package went so it can be put back by hand.
e.addSuppressed(restoreFailed);
LOG.errorv("Could not restore the previous deployment at {0}. The working "
+ "package is stranded at {1}; move it back to recover.",
absTarget, previous);
}
}
throw e;
}
if (previous != null) {
// Best effort from here. The new package is already live, so failing to drop the
// superseded tree must not be reported as a failed deployment: the caller would skip
// its metadata and warm pool updates while the new code is already serving. Leaving
// the tree behind costs disk and is recoverable; lying about the outcome is not.
try {
deleteRecursively(previous);
} catch (IOException e) {
LOG.warnv("Installed {0} but could not remove the superseded package at {1}: {2}",
absTarget, previous, e.getMessage());
}
}
}
private static void moveIntoPlace(Path source, Path destination) throws IOException {
try {
Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE);
} catch (AtomicMoveNotSupportedException e) {
// Some filesystems (and bind mounts inside containers) cannot rename atomically.
Files.move(source, destination);
}
}
private static void deleteRecursively(Path root) throws IOException {
if (!Files.exists(root)) {
return;
}
try (var paths = Files.walk(root)) {
for (Path p : paths.sorted(Comparator.reverseOrder()).toList()) {
Files.deleteIfExists(p);
}
}
}
/**
* Copies one entry to disk, checking it against the CRC recorded for it in the archive.
* ZipInputStream verified this on its own; ZipFile does not, so without an explicit check
@@ -8,6 +8,7 @@ import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
@@ -267,25 +268,62 @@ class ZipExtractorTest {
}
@Test
void leavesNoStagedArchiveInTheCodeStore(@TempDir Path codeStore) throws IOException {
// ZipFile needs a seekable file, so the archive is staged on disk next to the target
// rather than in the shared java.io.tmpdir. That puts a stray file one level above the
// function's code directory, so pin that none survives: a leaked staging archive would
// sit in the code store indefinitely, and one leaked *inside* a function directory
// would be tar-copied into that function's container at launch.
Path target = codeStore.resolve("fn");
void replacesThePreviousExtractionInsteadOfOverlayingIt(@TempDir Path target) throws IOException {
// Issue #2647: a deployment package is the complete contents of the function, so a file
// present in one deploy and absent from the next has to disappear. Extracting in place
// only ever adds and overwrites, so removed files survived and stayed loadable — a
// handler pointing at a deleted module kept resolving and running stale code.
byte[] v1 = zipWith("index.js", "v1");
extractor.extractTo(v1, target);
Files.writeString(target.resolve("removed.js"), "STALE");
Files.createDirectories(target.resolve("legacy"));
Files.writeString(target.resolve("legacy").resolve("old.js"), "STALE");
byte[] v2 = zipWith("index.js", "v2");
extractor.extractTo(v2, target);
assertEquals("v2", Files.readString(target.resolve("index.js")), "new package must land");
assertFalse(Files.exists(target.resolve("removed.js")),
"a file absent from the new package must not survive the deploy");
assertFalse(Files.exists(target.resolve("legacy")),
"a directory absent from the new package must not survive the deploy");
}
@Test
void leavesThePreviousExtractionIntactWhenExtractionFailsPartWay(@TempDir Path target) throws IOException {
// Extraction is all-or-nothing: a failure must not leave the function holding a mixture
// of the old package and part of the new one. The archive below opens cleanly and only
// fails once its entry has been streamed out, which is exactly when writing directly
// into the target would already have clobbered the previous deploy.
extractor.extractTo(zipWith("index.js", "v1"), target);
assertNoStagedFiles(codeStore);
byte[] corrupt = corruptedPayloadZip("index.js", "v2-but-corrupted-in-transit");
assertThrows(IOException.class, () -> extractor.extractTo(corrupt, target));
assertNoStagedFiles(codeStore);
assertEquals("v1", Files.readString(target.resolve("index.js")),
"a failed deploy must leave the previous package in place");
}
private static void assertNoStagedFiles(Path codeStore) throws IOException {
@Test
void leavesNoStagingArtefactsInTheCodeStore(@TempDir Path codeStore) throws IOException {
// Extraction stages two things beside the target rather than in java.io.tmpdir: the
// archive itself (so ZipFile has a seekable source) and the directory it unpacks into
// before the swap. Both sit one level above the function's code directory, so pin that
// neither survives — an orphan would accumulate one per deploy, and anything leaked
// *inside* a function directory would be tar-copied into its container at launch.
Path target = codeStore.resolve("fn");
extractor.extractTo(zipWith("index.js", "v1"), target);
assertNoStagingArtefacts(codeStore);
byte[] corrupt = corruptedPayloadZip("index.js", "v2-but-corrupted-in-transit");
assertThrows(IOException.class, () -> extractor.extractTo(corrupt, target));
assertNoStagingArtefacts(codeStore);
}
private static void assertNoStagingArtefacts(Path codeStore) throws IOException {
try (var entries = Files.list(codeStore)) {
assertEquals(List.of("fn"), entries.map(p -> p.getFileName().toString()).sorted().toList(),
"no staged archive may survive extraction, successful or failed");
"no staged archive or staging directory may survive extraction, successful or failed");
}
}
@@ -356,4 +394,78 @@ class ZipExtractorTest {
le16(out, 0);
return out.toByteArray();
}
@Test
void aFailedInstallPutsThePreviousPackageBack(@TempDir Path codeStore) throws IOException {
// The install used to delete the live tree and then move the new one in, so a failure in
// the move left the function with no code and nothing to restore: a failed update
// destroyed a working deployment. Driving install() directly is the only way to reach
// that branch, since a rename between siblings does not fail under any condition a test
// can arrange through extractTo.
Path target = Files.createDirectories(codeStore.resolve("fn"));
Files.writeString(target.resolve("index.js"), "v1");
Path staging = codeStore.resolve("fn.floci-staging-never-created");
assertThrows(IOException.class, () -> ZipExtractor.install(staging, target));
assertTrue(Files.isRegularFile(target.resolve("index.js")),
"a failed install must put the previous package back, not leave the function empty");
assertEquals("v1", Files.readString(target.resolve("index.js")));
try (var entries = Files.list(codeStore)) {
assertEquals(List.of("fn"), entries.map(p -> p.getFileName().toString()).sorted().toList(),
"the restored package must not leave a renamed copy behind");
}
}
@Test
void aSuccessfulInstallReplacesAndLeavesNoCopyBehind(@TempDir Path codeStore) throws IOException {
Path target = Files.createDirectories(codeStore.resolve("fn"));
Files.writeString(target.resolve("index.js"), "v1");
Files.writeString(target.resolve("removed.js"), "STALE");
Path staging = Files.createDirectories(codeStore.resolve("fn.floci-staging-x"));
Files.writeString(staging.resolve("index.js"), "v2");
ZipExtractor.install(staging, target);
assertEquals("v2", Files.readString(target.resolve("index.js")));
assertFalse(Files.exists(target.resolve("removed.js")), "install must replace, not merge");
try (var entries = Files.list(codeStore)) {
assertEquals(List.of("fn"), entries.map(p -> p.getFileName().toString()).sorted().toList(),
"neither the staging tree nor the superseded package may survive");
}
}
@Test
void aFailureToDropTheSupersededPackageDoesNotFailTheDeployment(@TempDir Path codeStore)
throws IOException {
// Once the new tree is installed the deployment has happened. Reporting failure because
// the superseded copy could not be deleted would make the caller skip its metadata and
// warm pool updates while the new code is already serving, which is worse than leaving a
// directory behind. Deletion is blocked by removing write permission on a subdirectory,
// so its contents cannot be unlinked.
Path target = Files.createDirectories(codeStore.resolve("fn"));
Files.writeString(target.resolve("index.js"), "v1");
Path locked = Files.createDirectories(target.resolve("locked"));
Files.writeString(locked.resolve("held.txt"), "cannot be removed");
Files.setPosixFilePermissions(locked, PosixFilePermissions.fromString("r-xr-xr-x"));
Path staging = Files.createDirectories(codeStore.resolve("fn.floci-staging-x"));
Files.writeString(staging.resolve("index.js"), "v2");
try {
ZipExtractor.install(staging, target);
assertEquals("v2", Files.readString(target.resolve("index.js")),
"the new package must be installed even though the old one could not be removed");
} finally {
try (var stream = Files.list(codeStore)) {
for (Path p : stream.toList()) {
Path stuck = p.resolve("locked");
if (Files.isDirectory(stuck)) {
Files.setPosixFilePermissions(stuck, PosixFilePermissions.fromString("rwxr-xr-x"));
}
}
}
}
}
}