Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/remote-exec-pinned-hashes.md
Original file line number Diff line number Diff line change
@@ -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).
15 changes: 14 additions & 1 deletion docs/20_remote_exec.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: "<remote-exec-linux-x86_64's hash in SHA256SUMS>" },
});
```
Comment thread
devin-ai-integration[bot] marked this conversation as resolved.
Resolved

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.
Expand Down
4 changes: 3 additions & 1 deletion examples/remote-exec/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
54 changes: 54 additions & 0 deletions packages/computer/src/vite/remote-exec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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`]);
Comment on lines +260 to +261

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Cache test contradicts testing summary

The testing summary says a cached wrong pin makes no requests. The requests assertion expects both the checksum request and the binary download before the build rejects the pin.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


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/,
Expand Down
87 changes: 81 additions & 6 deletions packages/computer/src/vite/remote-exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-<arch>.bin` beside
// the Worker. Nothing imports it: the output wrangler.json has `no_bundle`,
Expand Down Expand Up @@ -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<Record<RemoteExecArch, string>>;
}

const SPECIFIER = "computer:remote-exec";
Expand All @@ -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;
Expand All @@ -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));
Expand Down Expand Up @@ -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<Record<RemoteExecArch, string>> | undefined,
arches: RemoteExecArch[],
): Partial<Record<RemoteExecArch, string>> | undefined {
if (given === undefined) return undefined;
const pinned: Partial<Record<RemoteExecArch, string>> = {};
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<string> {
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<Record<RemoteExecArch, string>>,
cacheDir: string,
): Promise<Build[]> {
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<Uint8Array> {
let response: Response;
try {
Expand All @@ -199,10 +266,18 @@ async function download(
version: string,
dir: string,
arches: RemoteExecArch[],
pinned: Partial<Record<RemoteExecArch, string>> | undefined,
): Promise<Build[]> {
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);
Comment on lines +276 to +279

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 Rejected refresh evicts the cached build

After a release is replaced, download overwrites the version cache even if checkPinned rejects the replacement. Subsequent builds with the original pin fail because download ignores the verified copy stored under that pin.

Learn more

The version cache holds one build per package version and architecture. When that build differs from the requested pin, download fetches a replacement and writes it to the version cache after checking only the release's SHA256SUMS. checkPinned runs afterward, so rejecting the replacement does not undo the write. It stores verified copies under their hashes, but download never looks there. Even a successful refresh with a new pin prevents a later build using the original pin from reusing its verified copy.

Example: Build version 1.0.0 with pin A to warm the cache. The release replaces A with B. Build with a mistyped pin C, then restore pin A. The C build rejects B but leaves B in the version cache. The A build downloads B again and fails even though the verified A file is still on disk.

Recommended fix: Resolve pinned downloads from the hash-keyed cache first and verify the bytes before reuse. On a miss, check the existing version cache and then the release. Verify downloaded bytes against both the release checksum and the requested pin before publishing them to the hash-keyed cache. Leave the version-only cache unchanged during pinned refreshes so a rejected refresh cannot affect other builds.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

}
if (missing.length === 0) return files;

const release = `${releases}/${encodeURIComponent(`@cloudflare/computer@${version}`)}`;
Expand Down
Loading