mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
fix(lambda): read deployment packages via the zip central directory (#2649)
* fix(lambda): read deployment packages via the zip central directory ZipExtractor read archives with ZipInputStream, a forward-only reader that sees only local file headers. A streaming packager (the Serverless Framework's archiver, for one) cannot seek back to patch an entry's header, so it sets general-purpose bit 3, zeroes the CRC and sizes in the local header, and writes the real values in a trailing data descriptor; content that does not compress is written STORED. ZipInputStream rejects that pairing with "only DEFLATED entries can have EXT descriptor", because a STORED entry with deferred sizes has no end marker for a sequential reader to find. CreateFunction therefore 400d on any Serverless package bundling node_modules, which real AWS accepts. Read through the central directory with ZipFile instead, which always carries the true method, CRC and sizes regardless of the descriptor flag. The bytes are staged to a temp file because ZipFile needs a seekable source. The traversal guards, backslash warning and directory handling are unchanged, as is the method signature. ZipFile does not verify per-entry CRC while ZipInputStream did, so each entry is now checked against the CRC recorded for it in the archive. Without that, a package corrupted in transit would have deployed silently as garbage rather than being rejected. Closes #2593 * fix(lambda): stage the deployment package in the code store, not /tmp Reading the archive through ZipFile needs a seekable file, and the first version of this change staged it under java.io.tmpdir. That added a new consumer of the shared temp filesystem where there was none before: the extractor previously read straight from the in-memory byte[]. Concurrent deployments of large packages could exhaust that shared space, and doing so fails unrelated temp-file users, not just Lambda. Stage beside the extraction target instead. The code store already has to hold this package's uncompressed contents -- always at least as large as the archive, usually much larger -- so the volume is already provisioned for it, and the staged copy is released as soon as extraction ends. * fix(lambda): read the deployment package without staging a copy on disk The previous commit staged the archive on disk because java.util.zip.ZipFile only reads a central directory from a File. Commons Compress reads the same structure straight off a SeekableInMemoryByteChannel over the bytes already held, so no second copy of the package is written anywhere: extraction now costs exactly what the extracted output needs, as it did before this branch. That removes the staging copy as a resource concern entirely rather than bounding it. commons-compress is already on the compile classpath via docker-java-core; it is declared explicitly here because ZipExtractor uses it directly and must not break if that transitive path changes. Two behaviours of java.util.zip that Commons Compress does not share are restored explicitly: Commons Compress rewrites every '\' to '/' for a FAT-platform entry whose name contains no '/', which would turn a PowerShell-produced literal filename into a nested path -- the opposite of what #1215 established, since real AWS Lambda extracts "wwwroot\app.css" as one flat file. The raw name field is the bytes as written, so the rewrite is undone when it carries a backslash and no forward slash, leaving charset handling to Commons Compress. java.util.zip throws on an unknown compression method, while Commons Compress reports the entry unreadable and yields an empty stream, which would write a zero-byte file and deploy a function whose code silently vanished. Entries that cannot be read are now rejected. * fix(lambda): read the package with java.util.zip, not Commons Compress Reverts the in-memory Commons Compress reader from the previous commit. It removed the staged copy, but it cannot be built into the native image, which is a shipped artifact of this project. ZipFile.getInputStream hard-references four codecs, two of which -- xz and zstandard -- need libraries that are deliberately not on the classpath. The build uses --link-at-build-time, so every reachable method must resolve, and native-image fails during analysis: Discovered unresolved method during parsing: org.apache.commons.compress.compressors.xz.XZCompressorInputStream.<init> Error encountered while parsing ZipFile.getInputStream(ZipFile.java:1226) This is a linking failure rather than a class-initialization one, so --initialize-at-run-time does not address it; verified by building the image locally with that option in place. Resolving it properly would mean adding two compression libraries, one of them shipping JNI natives, purely so GraalVM can link paths a Lambda package cannot exercise -- AWS deployment packages are STORED or DEFLATE only. Back to java.util.zip.ZipFile, staging the archive in the code store. The staged copy costs at most one archive on the volume that already has to hold the same package's uncompressed contents, and the native image builds. Keeps the unknown-compression-method test from the reverted work: the JDK rejects such an archive when opening it, so the guarantee holds without a guard, and the test now pins it.
This commit is contained in:
1 parent
f019573bf1
commit
cd3f3677f8
2 files changed
+366
-34
No files matched your search
@@ -3,13 +3,15 @@ package io.github.hectorvent.floci.services.lambda.zip;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import org.jboss.logging.Logger;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.zip.CRC32;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipInputStream;
|
||||
import java.util.zip.ZipException;
|
||||
import java.util.zip.ZipFile;
|
||||
|
||||
/**
|
||||
* Extracts ZIP bytes to a target directory.
|
||||
@@ -27,47 +29,91 @@ public class ZipExtractor {
|
||||
Path absTarget = targetDir.toAbsolutePath().normalize();
|
||||
Files.createDirectories(absTarget);
|
||||
|
||||
try (ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(zipBytes))) {
|
||||
ZipEntry entry;
|
||||
while ((entry = zis.getNextEntry()) != null) {
|
||||
String entryName = entry.getName();
|
||||
// Read the archive through its central directory (ZipFile) rather than sequentially
|
||||
// over the local file headers (ZipInputStream). A streaming packager cannot seek back
|
||||
// to patch an entry's sizes, so it sets the data-descriptor flag (general-purpose bit
|
||||
// 3) and writes the real CRC and sizes after the data instead; anything that does not
|
||||
// compress is written STORED. ZipInputStream rejects that pairing outright with "only
|
||||
// DEFLATED entries can have EXT descriptor", because for a STORED entry it has no way
|
||||
// to find where the data ends. The central directory always carries the true method,
|
||||
// CRC and sizes regardless of the flag, so reading it accepts the same archives real
|
||||
// AWS Lambda does — e.g. a Serverless Framework package bundling node_modules
|
||||
// (issue #2593).
|
||||
//
|
||||
// ZipFile needs a seekable file, so the bytes are staged on disk. Stage inside the code
|
||||
// store rather than java.io.tmpdir: the shared temp filesystem must not become a new
|
||||
// unbounded consumer that concurrent deployments can exhaust and that unrelated
|
||||
// services would then fail on. The code store already has to hold this package's
|
||||
// *uncompressed* contents — always at least as large as the archive — so it is already
|
||||
// provisioned for the size, and the staged copy is released as soon as extraction ends.
|
||||
Path staged = Files.createTempFile(absTarget.getParent(), ".floci-staging-", ".zip");
|
||||
try {
|
||||
Files.write(staged, zipBytes);
|
||||
try (ZipFile zip = new ZipFile(staged.toFile())) {
|
||||
var entries = zip.entries();
|
||||
while (entries.hasMoreElements()) {
|
||||
ZipEntry entry = entries.nextElement();
|
||||
String entryName = entry.getName();
|
||||
|
||||
// PowerShell 5 Compress-Archive writes '\' as a literal filename byte on
|
||||
// Linux. Real AWS Lambda does NOT normalize this (the archive extracts to
|
||||
// a flat "wwwroot\app.css" file), so neither do we; masking it would let
|
||||
// a broken package pass locally and then fail on deploy.
|
||||
if (entryName.indexOf(BACKSLASH) >= 0) {
|
||||
LOG.warnv("ZIP entry \"{0}\" uses backslash separators (PowerShell Compress-Archive). "
|
||||
+ "It extracts as a literal filename and will also fail on real AWS Lambda. "
|
||||
+ "Repackage with tar, PowerShell Core (pwsh), or the dotnet lambda CLI.", entryName);
|
||||
}
|
||||
// PowerShell 5 Compress-Archive writes '\' as a literal filename byte on
|
||||
// Linux. Real AWS Lambda does NOT normalize this (the archive extracts to
|
||||
// a flat "wwwroot\app.css" file), so neither do we; masking it would let
|
||||
// a broken package pass locally and then fail on deploy.
|
||||
if (entryName.indexOf(BACKSLASH) >= 0) {
|
||||
LOG.warnv("ZIP entry \"{0}\" uses backslash separators (PowerShell Compress-Archive). "
|
||||
+ "It extracts as a literal filename and will also fail on real AWS Lambda. "
|
||||
+ "Repackage with tar, PowerShell Core (pwsh), or the dotnet lambda CLI.", entryName);
|
||||
}
|
||||
|
||||
// Security: prevent path traversal
|
||||
if (entryName.contains("..") || entryName.startsWith("/")) {
|
||||
LOG.warnv("Skipping suspicious ZIP entry: {0}", entryName);
|
||||
zis.closeEntry();
|
||||
continue;
|
||||
}
|
||||
// Security: prevent path traversal
|
||||
if (entryName.contains("..") || entryName.startsWith("/")) {
|
||||
LOG.warnv("Skipping suspicious ZIP entry: {0}", entryName);
|
||||
continue;
|
||||
}
|
||||
|
||||
Path targetPath = absTarget.resolve(entryName).normalize();
|
||||
if (!targetPath.startsWith(absTarget)) {
|
||||
LOG.warnv("Skipping out-of-bounds ZIP entry: {0}", entryName);
|
||||
zis.closeEntry();
|
||||
continue;
|
||||
}
|
||||
Path targetPath = absTarget.resolve(entryName).normalize();
|
||||
if (!targetPath.startsWith(absTarget)) {
|
||||
LOG.warnv("Skipping out-of-bounds ZIP entry: {0}", entryName);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
Files.createDirectories(targetPath);
|
||||
} else {
|
||||
Files.createDirectories(targetPath.getParent());
|
||||
try (OutputStream out = Files.newOutputStream(targetPath)) {
|
||||
zis.transferTo(out);
|
||||
if (entry.isDirectory()) {
|
||||
Files.createDirectories(targetPath);
|
||||
} else {
|
||||
Files.createDirectories(targetPath.getParent());
|
||||
copyVerified(zip, entry, targetPath);
|
||||
}
|
||||
}
|
||||
zis.closeEntry();
|
||||
}
|
||||
} finally {
|
||||
Files.deleteIfExists(staged);
|
||||
}
|
||||
|
||||
LOG.debugv("Extracted ZIP to: {0}", absTarget);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* a package corrupted in transit would be deployed silently as garbage code rather than
|
||||
* rejected. The message mirrors the JDK's own so existing reports stay recognisable.
|
||||
*/
|
||||
private static void copyVerified(ZipFile zip, ZipEntry entry, Path targetPath) throws IOException {
|
||||
CRC32 checksum = new CRC32();
|
||||
try (InputStream in = zip.getInputStream(entry);
|
||||
OutputStream out = Files.newOutputStream(targetPath)) {
|
||||
byte[] buffer = new byte[8192];
|
||||
int read;
|
||||
while ((read = in.read(buffer)) >= 0) {
|
||||
checksum.update(buffer, 0, read);
|
||||
out.write(buffer, 0, read);
|
||||
}
|
||||
}
|
||||
long expected = entry.getCrc();
|
||||
if (expected != -1L && checksum.getValue() != expected) {
|
||||
throw new ZipException(String.format(
|
||||
"invalid entry CRC for \"%s\" (expected 0x%08x but got 0x%08x)",
|
||||
entry.getName(), expected, checksum.getValue()));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user