fix(aws-lambda): the handler ZIP ships ffmpeg only when it matches its pinned digest (#8665)

build-zip accepted whatever ffmpeg-static's install script downloaded as long as it had a
Linux x86-64 ELF header. It now compares the binary's sha256 with the one pinned for the
installed ffmpeg-static version and stops before the ZIP is built when they differ, or when
a version has no pinned digest.
This commit is contained in:
Miguel Ángel
2026-11-24 08:42:33 +00:00
committed by GitHub
parent 5e1a490c80
commit 5f0fe71cc1
5 changed files with 213 additions and 102 deletions
+1
View File
@@ -14,6 +14,7 @@ on:
# A dependency bump or a ZIP layout change must re-stage the image.
- "packages/aws-lambda/package.json"
- "packages/aws-lambda/scripts/build-zip.ts"
- "packages/aws-lambda/scripts/_ffmpeg.ts"
- "packages/aws-lambda/scripts/runtimeLock.ts"
- "packages/aws-lambda/scripts/runtime-lock/**"
- ".github/workflows/lambda-arm64-image.yml"
+2 -1
View File
@@ -149,7 +149,8 @@ bun run --cwd packages/aws-lambda verify:zip-size # CI gate
The build script bundles `src/handler.ts` via esbuild, stages
`@sparticuz/chromium` and `puppeteer-core` under `node_modules/`, copies
ffmpeg-static into `bin/`, and zips the result. The unzipped layout is
ffmpeg-static into `bin/` once its sha256 matches the one pinned for that
ffmpeg-static version in `scripts/_ffmpeg.ts`, and zips the result. The unzipped layout is
designed to extract cleanly into Lambda's `/var/task/`.
`verify:zip-size` enforces:
+143
View File
@@ -0,0 +1,143 @@
import { createHash } from "node:crypto";
import {
chmodSync,
closeSync,
cpSync,
existsSync,
mkdirSync,
openSync,
readFileSync,
readSync,
} from "node:fs";
import { join } from "node:path";
/**
* sha256 of the linux-x64 ffmpeg each `ffmpeg-static` version downloads at install time. The lockfile
* pins the package, not that download, so a version bump needs its binary's digest added here.
*/
export const PINNED_FFMPEG_STATIC_SHA256: Readonly<Record<string, string>> = {
"5.3.0": "e7e7fb30477f717e6f55f9180a70386c62677ef8a4d4d1a5d948f4098aa3eb99",
};
function assertPinnedFfmpeg(
ffmpegModule: string,
binary: string,
pinned: Readonly<Record<string, string>>,
): void {
const { version } = JSON.parse(readFileSync(join(ffmpegModule, "package.json"), "utf-8")) as {
version: string;
};
const expected = pinned[version];
if (!expected) {
throw new Error(
`[build-zip] ffmpeg-static ${version} has no pinned sha256. Add the digest of the linux-x64 ` +
`binary it downloads to PINNED_FFMPEG_STATIC_SHA256 in scripts/_ffmpeg.ts.`,
);
}
const actual = createHash("sha256").update(readFileSync(binary)).digest("hex");
if (actual !== expected) {
throw new Error(
`[build-zip] ffmpeg-static ${version} binary at ${binary} has sha256 ${actual}, ` +
`not the pinned ${expected}. Delete node_modules/ffmpeg-static and install it again.`,
);
}
}
// ELF header constants used by `assertLinuxX86_64Elf`. Header layout:
// bytes 0..3 magic `0x7F 'E' 'L' 'F'`, byte 4 EI_CLASS (`2` = ELFCLASS64),
// bytes 18..19 e_machine little-endian (`0x3E` = EM_X86_64).
const ELF_MAGIC = Buffer.from([0x7f, 0x45, 0x4c, 0x46]);
const ELF_CLASS_64 = 2;
const ELF_MACHINE_X86_64 = 0x3e;
const ELF_HEADER_BYTES = 20;
/**
* Verify the binary at `path` is a Linux x86-64 ELF executable, the only
* shape the Lambda runtime can exec. Throws with the canonical workaround
* (Docker `--platform=linux/amd64` or `npm_config_platform` /
* `npm_config_arch` overrides) so the build doesn't ship a silently
* broken zip when a non-Linux host's postinstall fetched the wrong arch.
*/
function assertLinuxX86_64Elf(path: string, label: string): void {
const head = readFileHead(path, ELF_HEADER_BYTES, label);
const isElf = head.subarray(0, 4).equals(ELF_MAGIC);
const isElf64 = head[4] === ELF_CLASS_64;
const machine = head.readUInt16LE(18);
if (isElf && isElf64 && machine === ELF_MACHINE_X86_64) return;
const magicHex = head.subarray(0, 4).toString("hex");
throw new Error(
`[build-zip] ${label} at ${path} is not a Linux x86-64 ELF executable ` +
`(magic=0x${magicHex}, ei_class=${head[4]}, e_machine=0x${machine.toString(16)}). ` +
`This usually means the deploy host's postinstall fetched a host-platform binary ` +
`(e.g. macOS arm64 ffmpeg) instead of the linux/x64 binary Lambda needs. ` +
`Re-run the build inside a linux/amd64 container, or pre-install with ` +
`\`npm_config_platform=linux npm_config_arch=x64\` so the package fetches the right binary.`,
);
}
function readFileHead(path: string, byteCount: number, label: string): Buffer {
const fd = openSync(path, "r");
try {
const buf = Buffer.alloc(byteCount);
const bytesRead = readSync(fd, buf, 0, byteCount, 0);
if (bytesRead < byteCount) {
throw new Error(
`[build-zip] ${label} at ${path} is too short — read ${bytesRead} of ${byteCount} bytes.`,
);
}
return buf;
} finally {
closeSync(fd);
}
}
export function stageFfmpeg(
stagingDir: string,
ffmpegModule: string,
ffprobeModule: string,
pinned: Readonly<Record<string, string>> = PINNED_FFMPEG_STATIC_SHA256,
): void {
const binDir = join(stagingDir, "bin");
mkdirSync(binDir, { recursive: true });
// ffmpeg from `ffmpeg-static`. The package only ships the encoder
// binary; the audio pad/trim path also needs ffprobe, which comes
// from `ffprobe-static`.
//
// `ffmpeg-static`'s postinstall fetches a binary for the host platform
// (e.g. arm64 Mach-O on Apple Silicon macOS). Lambda runs Linux x86-64,
// so a build from a non-Linux host silently produces a zip that boots
// but fails at first ffmpeg invocation with `cannot execute binary file`.
// Verify the ELF header up front and bail with a clear message instead.
const ffmpegBinary = join(ffmpegModule, "ffmpeg");
if (!existsSync(ffmpegBinary)) {
throw new Error(
`[build-zip] ffmpeg-static binary missing at ${ffmpegBinary}. Did postinstall run?`,
);
}
assertLinuxX86_64Elf(ffmpegBinary, "ffmpeg-static binary");
assertPinnedFfmpeg(ffmpegModule, ffmpegBinary, pinned);
const ffmpegDest = join(binDir, "ffmpeg");
cpSync(ffmpegBinary, ffmpegDest);
chmodSync(ffmpegDest, 0o755);
// ffprobe lives at `ffprobe-static/bin/<platform>/<arch>/ffprobe`.
// The producer's `audioPadTrim` spawns `ffprobe` from PATH so we need
// it alongside ffmpeg under /var/task/bin/.
const ffprobeCandidates = [
join(ffprobeModule, "bin", "linux", "x64", "ffprobe"),
join(ffprobeModule, "bin", "linux", "arm64", "ffprobe"),
];
const ffprobeBinary = ffprobeCandidates.find((p) => existsSync(p));
if (!ffprobeBinary) {
throw new Error(
`[build-zip] ffprobe-static binary not found under ${ffprobeModule}/bin/linux/. Did postinstall run?`,
);
}
const ffprobeDest = join(binDir, "ffprobe");
cpSync(ffprobeBinary, ffprobeDest);
chmodSync(ffprobeDest, 0o755);
console.log(`[build-zip] staged ffmpeg + ffprobe → bin/`);
}
@@ -9,6 +9,7 @@ import {
statSync,
writeFileSync,
} from "node:fs";
import { createHash } from "node:crypto";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { pathToFileURL } from "node:url";
@@ -16,6 +17,7 @@ import { headlessShellDigest, managedChromeVersion } from "@hyperframes/engine/c
import * as esbuild from "esbuild";
import { BUNDLED_SHELL_DIR } from "../src/chromium.js";
import { stageChromeHeadlessShell } from "./_chromeHeadlessShell.js";
import { stageFfmpeg } from "./_ffmpeg.js";
import { HANDLER_BANNER } from "./_handlerBanner.js";
// The handler ships as ESM (.mjs) but inlines CJS deps that assume Node's CJS
@@ -184,3 +186,64 @@ describe("build-zip chrome-headless-shell staging", () => {
}
});
});
describe("build-zip ffmpeg staging", () => {
// A Linux x86-64 ELF header, so only the digest can tell this binary from the real one.
const elfX64 = (tail: string) => {
const head = Buffer.alloc(20);
Buffer.from([0x7f, 0x45, 0x4c, 0x46, 2]).copy(head);
head.writeUInt16LE(0x3e, 18);
return Buffer.concat([head, Buffer.from(tail)]);
};
function modules(ffmpeg: Buffer, version = "5.3.0") {
const root = mkdtempSync(join(tmpdir(), "hf-ffmpeg-modules-"));
const ffmpegModule = join(root, "ffmpeg-static");
const ffprobeModule = join(root, "ffprobe-static");
mkdirSync(ffmpegModule, { recursive: true });
writeFileSync(join(ffmpegModule, "package.json"), JSON.stringify({ version }));
writeFileSync(join(ffmpegModule, "ffmpeg"), ffmpeg);
mkdirSync(join(ffprobeModule, "bin/linux/x64"), { recursive: true });
writeFileSync(join(ffprobeModule, "bin/linux/x64/ffprobe"), "probe");
return { root, ffmpegModule, ffprobeModule };
}
const sha256 = (bytes: Buffer) => createHash("sha256").update(bytes).digest("hex");
it("refuses an ffmpeg whose bytes differ from the pinned digest", () => {
// fails without the fix: any file with a Linux x86-64 ELF header was copied into bin/ffmpeg.
const { root, ffmpegModule, ffprobeModule } = modules(elfX64("swapped"));
try {
expect(() => stageFfmpeg(root, ffmpegModule, ffprobeModule)).toThrow(
/ffmpeg-static 5\.3\.0 binary .* has sha256 [0-9a-f]{64}, not the pinned e7e7fb30/,
);
expect(existsSync(join(root, "bin/ffmpeg"))).toBe(false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("refuses an ffmpeg-static version with no pinned digest", () => {
const binary = elfX64("next");
const { root, ffmpegModule, ffprobeModule } = modules(binary, "5.4.0");
try {
expect(() =>
stageFfmpeg(root, ffmpegModule, ffprobeModule, { "5.3.0": sha256(binary) }),
).toThrow(/ffmpeg-static 5\.4\.0 has no pinned sha256/);
expect(existsSync(join(root, "bin/ffmpeg"))).toBe(false);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
it("stages an ffmpeg that matches its version's pinned digest", () => {
const binary = elfX64("real");
const { root, ffmpegModule, ffprobeModule } = modules(binary);
try {
stageFfmpeg(root, ffmpegModule, ffprobeModule, { "5.3.0": sha256(binary) });
expect(readFileSync(join(root, "bin/ffmpeg")).equals(binary)).toBe(true);
expect(statSync(join(root, "bin/ffmpeg")).mode & 0o111).not.toBe(0);
expect(readFileSync(join(root, "bin/ffprobe"), "utf-8")).toBe("probe");
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
+4 -101
View File
@@ -33,15 +33,11 @@
import { spawnSync } from "node:child_process";
import {
chmodSync,
closeSync,
copyFileSync,
cpSync,
existsSync,
mkdirSync,
openSync,
readdirSync,
readSync,
rmSync,
statSync,
writeFileSync,
@@ -51,6 +47,7 @@ import { fileURLToPath } from "node:url";
import * as esbuild from "esbuild";
import { BUNDLED_SHELL_DIR } from "../src/chromium.js";
import { stageChromeHeadlessShell } from "./_chromeHeadlessShell.js";
import { stageFfmpeg } from "./_ffmpeg.js";
import { formatBytes } from "./_formatBytes.js";
import { HANDLER_BANNER } from "./_handlerBanner.js";
import { RUNTIME_LOCK_DIR, assertRuntimeLockCurrent } from "./runtimeLock.js";
@@ -132,7 +129,7 @@ async function main(): Promise<void> {
stageRuntimeModules(stagingDir, opts.source);
// 3. Stage the ffmpeg binary.
stageFfmpeg(stagingDir);
stageFfmpeg(stagingDir, resolveModuleDir("ffmpeg-static"), resolveModuleDir("ffprobe-static"));
// 3b. Stage the hyperframe runtime manifest + IIFE as siblings of
// handler.mjs. The producer's `hyperframeRuntimeLoader` checks
@@ -280,8 +277,8 @@ function stageRuntimeModules(stagingDir: string, source: BuildOptions["source"])
function resolveModuleDir(moduleName: string): string {
// Walk up from packageRoot to find a matching node_modules entry.
// Used by stageFfmpeg below; the @sparticuz/chromium + puppeteer-core
// paths now go through npm install instead.
// Used for ffmpeg-static and ffprobe-static; the @sparticuz/chromium +
// puppeteer-core paths go through npm install instead.
let dir = packageRoot;
for (let i = 0; i < 5; i++) {
const candidate = join(dir, "node_modules", moduleName);
@@ -308,100 +305,6 @@ function stageHyperframeRuntime(stagingDir: string): void {
console.log(`[build-zip] staged hyperframe.manifest.json + hyperframe.runtime.iife.js`);
}
// ELF header constants used by `assertLinuxX86_64Elf`. Header layout:
// bytes 0..3 magic `0x7F 'E' 'L' 'F'`, byte 4 EI_CLASS (`2` = ELFCLASS64),
// bytes 18..19 e_machine little-endian (`0x3E` = EM_X86_64).
const ELF_MAGIC = Buffer.from([0x7f, 0x45, 0x4c, 0x46]);
const ELF_CLASS_64 = 2;
const ELF_MACHINE_X86_64 = 0x3e;
const ELF_HEADER_BYTES = 20;
/**
* Verify the binary at `path` is a Linux x86-64 ELF executable, the only
* shape the Lambda runtime can exec. Throws with the canonical workaround
* (Docker `--platform=linux/amd64` or `npm_config_platform` /
* `npm_config_arch` overrides) so the build doesn't ship a silently
* broken zip when a non-Linux host's postinstall fetched the wrong arch.
*/
function assertLinuxX86_64Elf(path: string, label: string): void {
const head = readFileHead(path, ELF_HEADER_BYTES, label);
const isElf = head.subarray(0, 4).equals(ELF_MAGIC);
const isElf64 = head[4] === ELF_CLASS_64;
const machine = head.readUInt16LE(18);
if (isElf && isElf64 && machine === ELF_MACHINE_X86_64) return;
const magicHex = head.subarray(0, 4).toString("hex");
throw new Error(
`[build-zip] ${label} at ${path} is not a Linux x86-64 ELF executable ` +
`(magic=0x${magicHex}, ei_class=${head[4]}, e_machine=0x${machine.toString(16)}). ` +
`This usually means the deploy host's postinstall fetched a host-platform binary ` +
`(e.g. macOS arm64 ffmpeg) instead of the linux/x64 binary Lambda needs. ` +
`Re-run the build inside a linux/amd64 container, or pre-install with ` +
`\`npm_config_platform=linux npm_config_arch=x64\` so the package fetches the right binary.`,
);
}
function readFileHead(path: string, byteCount: number, label: string): Buffer {
const fd = openSync(path, "r");
try {
const buf = Buffer.alloc(byteCount);
const bytesRead = readSync(fd, buf, 0, byteCount, 0);
if (bytesRead < byteCount) {
throw new Error(
`[build-zip] ${label} at ${path} is too short — read ${bytesRead} of ${byteCount} bytes.`,
);
}
return buf;
} finally {
closeSync(fd);
}
}
function stageFfmpeg(stagingDir: string): void {
const binDir = join(stagingDir, "bin");
mkdirSync(binDir, { recursive: true });
// ffmpeg from `ffmpeg-static`. The package only ships the encoder
// binary; the audio pad/trim path also needs ffprobe, which comes
// from `ffprobe-static`.
//
// `ffmpeg-static`'s postinstall fetches a binary for the host platform
// (e.g. arm64 Mach-O on Apple Silicon macOS). Lambda runs Linux x86-64,
// so a build from a non-Linux host silently produces a zip that boots
// but fails at first ffmpeg invocation with `cannot execute binary file`.
// Verify the ELF header up front and bail with a clear message instead.
const ffmpegBinary = join(resolveModuleDir("ffmpeg-static"), "ffmpeg");
if (!existsSync(ffmpegBinary)) {
throw new Error(
`[build-zip] ffmpeg-static binary missing at ${ffmpegBinary}. Did postinstall run?`,
);
}
assertLinuxX86_64Elf(ffmpegBinary, "ffmpeg-static binary");
const ffmpegDest = join(binDir, "ffmpeg");
cpSync(ffmpegBinary, ffmpegDest);
chmodSync(ffmpegDest, 0o755);
// ffprobe lives at `ffprobe-static/bin/<platform>/<arch>/ffprobe`.
// The producer's `audioPadTrim` spawns `ffprobe` from PATH so we need
// it alongside ffmpeg under /var/task/bin/.
const ffprobeModule = resolveModuleDir("ffprobe-static");
const ffprobeCandidates = [
join(ffprobeModule, "bin", "linux", "x64", "ffprobe"),
join(ffprobeModule, "bin", "linux", "arm64", "ffprobe"),
];
const ffprobeBinary = ffprobeCandidates.find((p) => existsSync(p));
if (!ffprobeBinary) {
throw new Error(
`[build-zip] ffprobe-static binary not found under ${ffprobeModule}/bin/linux/. Did postinstall run?`,
);
}
const ffprobeDest = join(binDir, "ffprobe");
cpSync(ffprobeBinary, ffprobeDest);
chmodSync(ffprobeDest, 0o755);
console.log(`[build-zip] staged ffmpeg + ffprobe → bin/`);
}
function zipDirectory(sourceDir: string, zipPath: string): void {
const result = spawnSync("zip", ["-rq", zipPath, "."], { cwd: sourceDir, stdio: "inherit" });
if (result.status !== 0) {