diff --git a/.changeset/remote-exec-pinned-hashes.md b/.changeset/remote-exec-pinned-hashes.md new file mode 100644 index 00000000..fd69fea2 --- /dev/null +++ b/.changeset/remote-exec-pinned-hashes.md @@ -0,0 +1,5 @@ +--- +"@cloudflare/computer": patch +--- + +The `remoteExec()` Vite plugin takes `sha256`, the hashes of the builds pinned in your repository, and refuses a build that doesn't match them, so a release changed after you pinned it can't reach your Worker; see [remote exec](https://github.com/cloudflare/computer/blob/main/docs/20_remote_exec.md). diff --git a/docs/20_remote_exec.md b/docs/20_remote_exec.md index 62d402e4..7cc420c2 100644 --- a/docs/20_remote_exec.md +++ b/docs/20_remote_exec.md @@ -121,7 +121,20 @@ own, and the Worker streams it from `/bundle` with `node:fs` (it needs `nodejs_c chunk at a time to hash it and to copy it in, so the build is never held in memory whole. `vite dev` doesn't put files under `/bundle`, so there the Worker imports the build instead. The plugin takes `arch` for the architectures to carry (`x86_64` by default), `version` for another release, -and `builds` for a directory of local builds. For TypeScript, add +and `builds` for a directory of local builds. + +`SHA256SUMS` comes from the same release as the builds, so it catches a broken download but not a +release changed after it was published. To rule that out, pin the hashes in your repository with +`sha256`, copied from the release's `SHA256SUMS` when you install or bump `@cloudflare/computer`. +A build that doesn't match them fails the build, whether downloaded, cached or local, and a cached one is downloaded again first, in case the release was replaced and the pin updated to match. Hashes may be in either case: + +```ts +remoteExec({ + sha256: { x86_64: "" }, +}); +``` + +For TypeScript, add `"@cloudflare/computer/vite/client"` to `compilerOptions.types`. The plugin needs `@cloudflare/vite-plugin` 1.68.0 or later, whose workerd keeps a container's `exec()` streams open until they finish. diff --git a/examples/remote-exec/README.md b/examples/remote-exec/README.md index c20164c8..fed2babe 100644 --- a/examples/remote-exec/README.md +++ b/examples/remote-exec/README.md @@ -60,7 +60,9 @@ Worker carries the build and copies it into the container on first use. The cont `linux/amd64`, as Cloudflare runs it and `vite dev` builds it, so that's just the x86_64 build. `remoteExec()` in `vite.config.ts` gets it from the `@cloudflare/computer` GitHub release matching -the installed package, checks it against the release's `SHA256SUMS`, and caches it. The Worker +the installed package, checks it against the release's `SHA256SUMS`, and caches it. To check it +against hashes pinned in your own repository as well, pass `sha256`; see +[the remote exec docs](../../docs/20_remote_exec.md). The Worker imports it as `computer:remote-exec`. Built with `vite build`, it streams the build from `/bundle` with `node:fs`, a chunk at a time, so it never holds the 1.5 MB build in memory. Under `vite dev`, which doesn't put files under `/bundle`, it imports the build instead. diff --git a/packages/computer/src/vite/remote-exec.test.ts b/packages/computer/src/vite/remote-exec.test.ts index 4f816b29..04ca7dbd 100644 --- a/packages/computer/src/vite/remote-exec.test.ts +++ b/packages/computer/src/vite/remote-exec.test.ts @@ -242,6 +242,60 @@ describe("remoteExec vite plugin", () => { } }); + it("takes the builds whose SHA-256 `sha256` pins", async () => { + const pins = { x86_64: sha256(builds.x86_64), aarch64: sha256(builds.aarch64) }; + const out = await build(project(), { arch: ["x86_64", "aarch64"], sha256: pins }); + expect(readFileSync(join(out, "remote-exec-linux-x86_64.bin"))).toEqual(builds.x86_64); + expect(readFileSync(join(out, "remote-exec-linux-aarch64.bin"))).toEqual(builds.aarch64); + }); + + it("refuses a build `sha256` doesn't pin, downloaded, cached or local", async () => { + const wrong = { sha256: { x86_64: "0".repeat(64) } }; + const refused = /remote-exec-linux-x86_64 has SHA-256 [0-9a-f]{64}, but `sha256` pins 0{64}/; + const cache = mkdtempSync(join(tmpdir(), "computer-remote-exec-cache-")); + tempDirs.push(cache); + await expect(build(project(), wrong, cache)).rejects.toThrow(refused); + // The cached build doesn't match the pin either, so it's downloaded again, and refused again. + requests.length = 0; + await expect(build(project(), wrong, cache)).rejects.toThrow(refused); + expect(requests).toEqual([`/${TAG}/SHA256SUMS`, `/${TAG}/remote-exec-linux-x86_64`]); + + const dir = mkdtempSync(join(tmpdir(), "computer-remote-exec-builds-")); + tempDirs.push(dir); + writeFileSync(join(dir, "remote-exec-linux-x86_64"), randomBytes(1000)); + await expect(build(project(), { ...wrong, builds: dir })).rejects.toThrow(refused); + }); + + it("downloads again a cached build its pin doesn't match, as after a release is replaced", async () => { + const cache = mkdtempSync(join(tmpdir(), "computer-remote-exec-cache-")); + tempDirs.push(cache); + await build(project(), undefined, cache); + const saved = { bytes: builds.x86_64, sums }; + const replaced = randomBytes(1000); + builds.x86_64 = replaced; + sums = sums.replace(sha256(saved.bytes), sha256(replaced)); + try { + const out = await build(project(), { sha256: { x86_64: sha256(replaced) } }, cache); + expect(readFileSync(join(out, "remote-exec-linux-x86_64.bin"))).toEqual(replaced); + } finally { + builds.x86_64 = saved.bytes; + sums = saved.sums; + } + }); + + it("takes a pin in upper case", async () => { + const out = await build(project(), { sha256: { x86_64: sha256(builds.x86_64).toUpperCase() } }); + expect(readFileSync(join(out, "remote-exec-linux-x86_64.bin"))).toEqual(builds.x86_64); + }); + + it("needs a pin for every architecture it carries", () => { + const sha256 = { x86_64: "0".repeat(64) }; + expect(() => remoteExec({ arch: ["x86_64", "aarch64"], sha256 })).toThrow( + /`sha256` needs a SHA-256 in hex for aarch64/, + ); + expect(() => remoteExec({ sha256: { x86_64: "not a hash" } })).toThrow(/for x86_64/); + }); + it("says what to do when there's no such release", async () => { await expect(build(project(), { version: "0.0.1" })).rejects.toThrow( /404.*Pass `version` to take the builds from another release, or `builds` to use local ones/, diff --git a/packages/computer/src/vite/remote-exec.ts b/packages/computer/src/vite/remote-exec.ts index 38fdacdf..1214ee5b 100644 --- a/packages/computer/src/vite/remote-exec.ts +++ b/packages/computer/src/vite/remote-exec.ts @@ -7,7 +7,9 @@ // It takes the builds from the @cloudflare/computer GitHub release that // matches the installed package, checks them against the release's // SHA256SUMS, and keeps them in Vite's cache directory, so only the first -// build downloads them. +// build downloads them. SHA256SUMS comes from the same release as the +// builds, so it catches a broken download but not a replaced release; +// `sha256` pins the hashes in the consumer's own repository instead. // // `vite build` emits each build as `remote-exec-linux-.bin` beside // the Worker. Nothing imports it: the output wrangler.json has `no_bundle`, @@ -45,6 +47,13 @@ export interface RemoteExecPluginOptions { builds?: string; /** Where releases are downloaded from, for tests. The release's tag is appended. */ releases?: string; + /** + * The SHA-256 each build must have, by architecture, in hex: the release's `SHA256SUMS`, pinned + * in your repository when you install or bump `@cloudflare/computer`. With it, a build that + * doesn't match fails, downloaded, cached or local, so a release changed after you pinned it + * can't reach your Worker. Pin every architecture in `arch`. + */ + sha256?: Partial>; } const SPECIFIER = "computer:remote-exec"; @@ -63,6 +72,7 @@ const carried = (arch: RemoteExecArch) => `${released(arch)}.bin`; export function remoteExec(options: RemoteExecPluginOptions = {}): Plugin { const arches = [...new Set([options.arch ?? "x86_64"].flat())]; + const pinned = pins(options.sha256, arches); let root = ""; let cacheDir = ""; let serving = false; @@ -72,10 +82,20 @@ export function remoteExec(options: RemoteExecPluginOptions = {}): Plugin { const prepare = () => { builds ??= (async () => { - if (options.builds !== undefined) - return local(resolve(root, options.builds), cacheDir, arches); - const version = options.version ?? (await installedVersion()); - return download(options.releases ?? RELEASES, version, join(cacheDir, version), arches); + let files: Build[]; + if (options.builds !== undefined) { + files = await local(resolve(root, options.builds), cacheDir, arches); + } else { + const version = options.version ?? (await installedVersion()); + files = await download( + options.releases ?? RELEASES, + version, + join(cacheDir, version), + arches, + pinned, + ); + } + return pinned === undefined ? files : await checkPinned(files, pinned, cacheDir); })(); // A failure (offline, say) is tried again by the next build rather than remembered. builds.catch(() => (builds = undefined)); @@ -182,6 +202,53 @@ async function local(dir: string, cacheDir: string, arches: RemoteExecArch[]): P return files; } +// The pins, lowercased, with one for every architecture carried. +function pins( + given: Partial> | undefined, + arches: RemoteExecArch[], +): Partial> | undefined { + if (given === undefined) return undefined; + const pinned: Partial> = {}; + for (const arch of arches) { + const hash = given[arch]; + if (typeof hash !== "string" || !/^[0-9a-f]{64}$/i.test(hash)) + throw new Error(`remoteExec: \`sha256\` needs a SHA-256 in hex for ${arch}`); + pinned[arch] = hash.toLowerCase(); + } + return pinned; +} + +async function sha256Of(path: string): Promise { + return createHash("sha256") + .update(await readFile(path)) + .digest("hex"); +} + +// Every build, wherever it came from, against the hashes the consumer +// pinned. A build that matches is kept under its hash, and served from +// there: another build sharing the cache can replace the file it came +// from, but never what's at that path. +async function checkPinned( + files: Build[], + pinned: Partial>, + cacheDir: string, +): Promise { + const checked: Build[] = []; + for (const { arch, path } of files) { + const bytes = await readFile(path); + const sha256 = createHash("sha256").update(bytes).digest("hex"); + if (sha256 !== pinned[arch]) + throw new Error( + `remoteExec: ${released(arch)} has SHA-256 ${sha256}, but \`sha256\` pins ${pinned[arch]}. ` + + "Pin the hashes in the SHA256SUMS of the @cloudflare/computer release you use.", + ); + const kept = join(cacheDir, "sha256", sha256, carried(arch)); + if (!(await exists(kept))) await writeAtomically(kept, bytes); + checked.push({ arch, path: kept }); + } + return checked; +} + async function get(url: string): Promise { let response: Response; try { @@ -199,10 +266,18 @@ async function download( version: string, dir: string, arches: RemoteExecArch[], + pinned: Partial> | undefined, ): Promise { const files: Build[] = arches.map((arch) => ({ arch, path: join(dir, carried(arch)) })); const missing: Build[] = []; - for (const file of files) if (!(await exists(file.path))) missing.push(file); + // A cached build that doesn't match its pin is downloaded again: the + // release may have been replaced since it was cached, and the pin + // updated to match. + for (const file of files) { + const cached = await exists(file.path); + if (!cached || (pinned !== undefined && (await sha256Of(file.path)) !== pinned[file.arch])) + missing.push(file); + } if (missing.length === 0) return files; const release = `${releases}/${encodeURIComponent(`@cloudflare/computer@${version}`)}`;