fix(lambda): bound ZIP extraction resources (#3127)

* fix(lambda): bound ZIP extraction resources

Limit Lambda ZIP compressed and expanded sizes and configurable entry counts for function and layer deployments. Preserve previous extracted code when a package exceeds a resource limit.

* refactor(test): centralize ZIP fixture encoding

* docs(test): explain ZIP fixture headers
This commit is contained in:
Niels Kootstra authored and GitHub committed 2026-09-06 10:31:50 -04:00
1 parent daeea78ee6
commit 0fce2d2407
9 files changed
+308 -59

No files matched your search

@@ -1885,6 +1885,14 @@ public interface EmulatorConfig {
@WithDefault("./data/lambda-code")
String codePath();
/**
* Maximum number of entries accepted in a Lambda ZIP archive.
*
* Env var: FLOCI_SERVICES_LAMBDA_ZIP_MAX_ENTRIES
*/
@WithDefault("100000")
int zipMaxEntries();
@WithDefault("1000")
long pollIntervalMs();
@@ -131,6 +131,11 @@ public class LambdaLayerService {
// Resolve the zip content
byte[] zipBytes = resolveLayerContent(content);
if (content.get("ZipFile") != null
&& zipBytes.length > ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES) {
throw new AwsException("RequestEntityTooLargeException",
"Request must be smaller than 52428800 bytes.", 413);
}
// Determine the next version number
long nextVersion = layerStore.getLatestVersion(region, layerName) + 1;
@@ -138,7 +143,7 @@ public class LambdaLayerService {
// Extract the layer zip to disk
Path layerPath = getLayerCodePath(layerName, nextVersion);
try {
zipExtractor.extractTo(zipBytes, layerPath);
zipExtractor.extractTo(zipBytes, layerPath, configuredZipMaxEntries());
} catch (IOException e) {
throw new AwsException("InvalidParameterValueException",
"Failed to extract layer archive: " + e.getMessage(), 400);
@@ -181,6 +186,16 @@ public class LambdaLayerService {
return layerVersion;
}
private int configuredZipMaxEntries() {
int configured = config.services().lambda().zipMaxEntries();
if (configured < 1) {
LOG.warnv("Ignoring invalid Lambda ZIP entry limit {0}; using {1}",
configured, ZipExtractor.DEFAULT_MAX_ENTRIES);
return ZipExtractor.DEFAULT_MAX_ENTRIES;
}
return configured;
}
/**
* Keeps the exact layer archive in Floci's S3 so GetLayerVersion can serve a real
* Content.Location and the kubernetes executor's init container can download it.
@@ -2589,13 +2589,18 @@ public class LambdaService implements ResourceProvider {
}
private void extractZipCode(LambdaFunction fn, String zipFileBase64, String region) {
extractZipCodeBytes(fn, Base64.getDecoder().decode(zipFileBase64), region);
byte[] zipBytes = Base64.getDecoder().decode(zipFileBase64);
if (zipBytes.length > ZipExtractor.DIRECT_UPLOAD_MAX_COMPRESSED_BYTES) {
throw new AwsException("RequestEntityTooLargeException",
"Request must be smaller than 52428800 bytes.", 413);
}
extractZipCodeBytes(fn, zipBytes, region);
}
private void extractZipCodeBytes(LambdaFunction fn, byte[] zipBytes, String region) {
Path codePath = codeStore.getCodePath(ownerAccount(fn), fn.getFunctionName());
try {
zipExtractor.extractTo(zipBytes, codePath);
zipExtractor.extractTo(zipBytes, codePath, configuredZipMaxEntries());
// 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
@@ -2658,6 +2663,19 @@ public class LambdaService implements ResourceProvider {
}
}
private int configuredZipMaxEntries() {
if (config == null || config.services() == null || config.services().lambda() == null) {
return ZipExtractor.DEFAULT_MAX_ENTRIES;
}
int configured = config.services().lambda().zipMaxEntries();
if (configured < 1) {
LOG.warnv("Ignoring invalid Lambda ZIP entry limit {0}; using {1}",
configured, ZipExtractor.DEFAULT_MAX_ENTRIES);
return ZipExtractor.DEFAULT_MAX_ENTRIES;
}
return configured;
}
private void storeDeploymentPackage(LambdaFunction fn, byte[] zipBytes, String region) {
boolean stored = putTasksObjectQuietly(s3Service, region, codeObjectKey(fn), zipBytes,
"deployment package for " + fn.getFunctionName());
@@ -27,8 +27,25 @@ public class ZipExtractor {
private static final Logger LOG = Logger.getLogger(ZipExtractor.class);
private static final char BACKSLASH = '\\';
public static final long DIRECT_UPLOAD_MAX_COMPRESSED_BYTES = 50L * 1024 * 1024;
private static final long S3_MAX_COMPRESSED_BYTES = 250L * 1024 * 1024;
static final long MAX_EXPANDED_BYTES = 250L * 1024 * 1024;
static final long MAX_ENTRY_BYTES = 250L * 1024 * 1024;
public static final int DEFAULT_MAX_ENTRIES = 100_000;
public void extractTo(byte[] zipBytes, Path targetDir) throws IOException {
extractTo(zipBytes, targetDir, DEFAULT_MAX_ENTRIES);
}
public void extractTo(byte[] zipBytes, Path targetDir, int maxEntries) throws IOException {
if (maxEntries < 1) {
throw new IOException("ZIP archive entry limit must be at least 1: " + maxEntries);
}
if (zipBytes.length > S3_MAX_COMPRESSED_BYTES) {
throw new IOException("ZIP archive exceeds the " + S3_MAX_COMPRESSED_BYTES
+ " byte compressed limit: " + zipBytes.length);
}
// Resolve to absolute path so that normalize() on entry paths stays comparable
Path absTarget = targetDir.toAbsolutePath().normalize();
Files.createDirectories(absTarget.getParent());
@@ -65,7 +82,13 @@ public class ZipExtractor {
Files.write(staged, zipBytes);
try (ZipFile zip = new ZipFile(staged.toFile())) {
var entries = zip.entries();
int entryCount = 0;
long expandedBytes = 0;
while (entries.hasMoreElements()) {
if (++entryCount > maxEntries) {
throw new IOException("ZIP archive contains more than the configured "
+ maxEntries + " entries");
}
ZipEntry entry = entries.nextElement();
String entryName = entry.getName();
@@ -91,12 +114,29 @@ public class ZipExtractor {
continue;
}
long declaredSize = entry.getSize();
if (declaredSize > MAX_ENTRY_BYTES) {
throw new IOException("ZIP entry exceeds the " + MAX_ENTRY_BYTES
+ " byte limit: " + entryName);
}
long accountedSize = declaredSize >= 0 ? declaredSize : 0;
if (accountedSize > MAX_EXPANDED_BYTES - expandedBytes) {
throw new IOException("ZIP archive exceeds the " + MAX_EXPANDED_BYTES
+ " byte expanded limit");
}
if (entry.isDirectory()) {
Files.createDirectories(targetPath);
} else {
Files.createDirectories(targetPath.getParent());
copyVerified(zip, entry, targetPath);
long copyLimit = declaredSize >= 0
? Math.min(declaredSize, MAX_EXPANDED_BYTES - expandedBytes)
: MAX_EXPANDED_BYTES - expandedBytes;
long copiedBytes = copyVerified(zip, entry, targetPath,
MAX_ENTRY_BYTES, copyLimit);
accountedSize = declaredSize >= 0 ? declaredSize : copiedBytes;
}
expandedBytes += accountedSize;
}
}
// Extraction succeeded in full: install the new tree.
@@ -197,15 +237,21 @@ public class ZipExtractor {
* 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 {
private static long copyVerified(ZipFile zip, ZipEntry entry, Path targetPath,
long maxEntryBytes, long remainingExpandedBytes) throws IOException {
CRC32 checksum = new CRC32();
long bytesWritten = 0;
try (InputStream in = zip.getInputStream(entry);
OutputStream out = Files.newOutputStream(targetPath)) {
byte[] buffer = new byte[8192];
int read;
while ((read = in.read(buffer)) >= 0) {
if (read > maxEntryBytes - bytesWritten || read > remainingExpandedBytes - bytesWritten) {
throw new IOException("ZIP archive exceeds its extraction size limit");
}
checksum.update(buffer, 0, read);
out.write(buffer, 0, read);
bytesWritten += read;
}
}
long expected = entry.getCrc();
@@ -214,5 +260,6 @@ public class ZipExtractor {
"invalid entry CRC for \"%s\" (expected 0x%08x but got 0x%08x)",
entry.getName(), expected, checksum.getValue()));
}
return bytesWritten;
}
}