Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Reject parent path segments in sandbox file paths (#1252)

Joshua France25b949c03f56
diff --git a/src/sandbox/exec-file-ops.ts b/src/sandbox/exec-file-ops.ts
index 34f239184..019c87cb0 100644
--- a/src/sandbox/exec-file-ops.ts
+++ b/src/sandbox/exec-file-ops.ts
@@ -8,21 +8,27 @@ import { BLOB_TRANSFER_AUD, mintCapabilityToken } from "../auth/capability-token
import { CAPABILITY_HEADER } from "../api/contract.ts";
import type { BlobTransferStore } from "../persistence/blob-transfer.ts";
-import type {
- AgentComputerExportArea,
- AgentComputerExportEntry,
- AgentComputerExportOptions,
- Sandbox,
- SandboxHandle,
- StageOptions,
+import {
+ hasParentPathSegment,
+ type AgentComputerExportArea,
+ type AgentComputerExportEntry,
+ type AgentComputerExportOptions,
+ type Sandbox,
+ type SandboxHandle,
+ type StageOptions,
} from "./sandbox.ts";
const posixDirname = (p: string): string => p.slice(0, Math.max(0, p.lastIndexOf("/"))) || "/";
const BLOB_TRANSFER_TTL_MS = 2 * 60_000;
+function workspaceRel(rel: string): string {
+ if (hasParentPathSegment(rel)) throw new Error(`${rel} must stay inside the workspace — no .. path segments`);
+ return rel.replace(/^\/+/, "");
+}
+
export function posixJoin(base: string, rel: string): string {
- const clean = rel.replace(/^\/+/, "");
+ const clean = workspaceRel(rel);
return clean ? `${base.replace(/\/+$/, "")}/${clean}` : base;
}
@@ -62,7 +68,7 @@ export function createExecFileOps({ label, exec, writeInline, combineRemoveAndLi
},
async listDir(handle, relDir): Promise<string[]> {
- const rel = relDir.replace(/^\/+/, "") || ".";
+ const rel = workspaceRel(relDir) || ".";
const r = await exec(
handle.id,
`cd ${shq(handle.rootDir)} 2>/dev/null && find ${shq(rel)} -type f 2>/dev/null`,
@@ -78,10 +84,9 @@ export function createExecFileOps({ label, exec, writeInline, combineRemoveAndLi
...(combineRemoveAndList
? {
async removeDirAndList(handle: SandboxHandle, removeRelDir: string, listRelDir: string): Promise<string[]> {
- const remove = removeRelDir.replace(/^\/+/, "");
- const abs = posixJoin(handle.rootDir, remove);
- const prep = remove && abs !== handle.rootDir ? `rm -rf ${shq(abs)} || exit $?; ` : "";
- const rel = listRelDir.replace(/^\/+/, "") || ".";
+ const remove = workspaceRel(removeRelDir);
+ const prep = remove ? `rm -rf ${shq(posixJoin(handle.rootDir, remove))} || exit $?; ` : "";
+ const rel = workspaceRel(listRelDir) || ".";
const r = await exec(
handle.id,
`${prep}listing=$(cd ${shq(handle.rootDir)} 2>/dev/null && find ${shq(rel)} -type f 2>/dev/null) && printf '%s\\n' "$listing"; exit 0`,
@@ -96,11 +101,9 @@ export function createExecFileOps({ label, exec, writeInline, combineRemoveAndLi
}
: {}),
async removeDir(handle, relDir): Promise<void> {
- const rel = relDir.replace(/^\/+/, "");
+ const rel = workspaceRel(relDir);
if (!rel) return;
- const abs = posixJoin(handle.rootDir, rel);
- if (abs === handle.rootDir) return;
- const r = await exec(handle.id, `rm -rf ${shq(abs)}`, 60);
+ const r = await exec(handle.id, `rm -rf ${shq(posixJoin(handle.rootDir, rel))}`, 60);
if (r.code !== 0) throw new Error(`${label} removeDir ${relDir} failed: ${r.stderr}`);
},
};
diff --git a/src/sandbox/sandbox-migrate.ts b/src/sandbox/sandbox-migrate.ts
index af33c93a9..d1c0c19fa 100644
--- a/src/sandbox/sandbox-migrate.ts
+++ b/src/sandbox/sandbox-migrate.ts
@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";
import { posix } from "node:path";
import { shq } from "../util/shell.ts";
import { supportsBlobStaging, type Sandbox, type SandboxHandle } from "./sandbox.ts";
+import { posixJoin } from "./exec-file-ops.ts";
export function translateScript(toHome: string, fromHome: string): string {
const H = shq(toHome);
@@ -42,22 +43,27 @@ export interface PackedHome {
sourceFiles: number;
}
+const HOME_TAR_PREFIX = ".home-";
+
export async function packHome(
fromSandbox: Sandbox,
fromHandle: SandboxHandle,
fromHome: string,
timeoutMs: number,
): Promise<PackedHome> {
- const uid = randomUUID();
- const tarPath = `/tmp/.home-${uid}.tgz`;
+ const tarRel = `${HOME_TAR_PREFIX}${randomUUID()}.tgz`;
+ const tarPath = posixJoin(fromHandle.rootDir, tarRel);
const H = shq(fromHome);
+ const P = shq(tarPath);
const packed = await fromSandbox.run(
fromHandle,
- `cd ${H} && tar czf ${tarPath} . 2>/dev/null; rc=$?; [ "$rc" -le 1 ] || exit "$rc"; sha256sum ${tarPath} | cut -d' ' -f1 && wc -c < ${tarPath} && find . -type f | wc -l`,
+ `cd ${H} && tar czf ${P} --exclude=${shq(`./${posix.relative(fromHome, fromHandle.rootDir)}/${HOME_TAR_PREFIX}*.tgz`)} . 2>/dev/null; rc=$?; [ "$rc" -le 1 ] || exit "$rc"; sha256sum ${P} | cut -d' ' -f1 && wc -c < ${P} && find . -type f ! -name ${shq(`${HOME_TAR_PREFIX}*.tgz`)} | wc -l`,
{ timeoutMs },
);
- if (packed.code !== 0)
+ if (packed.code !== 0) {
+ await fromSandbox.run(fromHandle, `rm -f ${P}`, { timeoutMs: 30_000 }).catch(() => {});
throw new Error(`packHome: source tar failed (${packed.code}): ${(packed.stderr || packed.stdout).slice(0, 200)}`);
+ }
const [shaLine = "", sizeLine = "", filesLine = ""] = packed.stdout.trim().split("\n");
const sha = shaLine.trim();
const bytes = Number.parseInt(sizeLine.trim(), 10);
@@ -65,7 +71,7 @@ export async function packHome(
if (!/^[0-9a-f]{64}$/.test(sha) || !Number.isFinite(bytes) || !Number.isFinite(sourceFiles)) {
throw new Error(`packHome: unreadable source manifest: ${packed.stdout.slice(0, 200)}`);
}
- return { tarPath, tarRel: posix.relative(fromHandle.rootDir, tarPath), sha, bytes, sourceFiles };
+ return { tarPath, tarRel, sha, bytes, sourceFiles };
}
export interface CopyHomeArgs {
@@ -82,47 +88,46 @@ export async function copyHome(args: CopyHomeArgs): Promise<CopyHomeResult> {
const { fromSandbox, fromHandle, fromHome, toSandbox, toHandle, toHome } = args;
const timeoutMs = (args.timeoutSec ?? 900) * 1000;
const T = shq(toHome);
- const {
- tarPath,
- tarRel: fromRel,
- sha,
- bytes,
- sourceFiles,
- } = await packHome(fromSandbox, fromHandle, fromHome, timeoutMs);
- const toRel = posix.relative(toHandle.rootDir, tarPath);
-
- if (supportsBlobStaging(fromSandbox) && supportsBlobStaging(toSandbox)) {
- const stageOpts = { timeoutSec: timeoutMs / 1000 };
- const blobId = await fromSandbox.stageOut(fromHandle, fromRel, stageOpts);
- await toSandbox.stageIn(toHandle, toRel, blobId, stageOpts);
- } else {
- const tarBytes = await fromSandbox.readFileBytes(fromHandle, fromRel);
- if (!tarBytes) throw new Error("copyHome: source tar vanished before read");
- await toSandbox.writeFileBytes(toHandle, toRel, tarBytes);
+ const { tarPath, tarRel, sha, bytes, sourceFiles } = await packHome(fromSandbox, fromHandle, fromHome, timeoutMs);
+ const toTarPath = posixJoin(toHandle.rootDir, tarRel);
+ try {
+ return await transferHome();
+ } finally {
+ await Promise.all([
+ fromSandbox.run(fromHandle, `rm -f ${shq(tarPath)}`, { timeoutMs: 30_000 }).catch(() => {}),
+ toSandbox.run(toHandle, `rm -f ${shq(toTarPath)}`, { timeoutMs: 30_000 }).catch(() => {}),
+ ]);
}
- const extracted = await toSandbox.run(
- toHandle,
- `dsha=$(sha256sum ${tarPath} | cut -d' ' -f1); [ "$dsha" = ${shq(sha)} ] || { echo "sha-mismatch:$dsha"; exit 3; }; mkdir -p ${T} && cd ${T} && tar xzf ${tarPath} 2>/dev/null && find . -type f | wc -l`,
- { timeoutMs },
- );
- if (extracted.code !== 0) {
- throw new Error(
- `copyHome: dest verify/extract failed (${extracted.code}): ${(extracted.stderr || extracted.stdout).slice(0, 200)}`,
- );
- }
- const destFiles = Number.parseInt(extracted.stdout.trim().split("\n").pop() ?? "", 10);
+ async function transferHome(): Promise<CopyHomeResult> {
+ if (supportsBlobStaging(fromSandbox) && supportsBlobStaging(toSandbox)) {
+ const stageOpts = { timeoutSec: timeoutMs / 1000 };
+ const blobId = await fromSandbox.stageOut(fromHandle, tarRel, stageOpts);
+ await toSandbox.stageIn(toHandle, tarRel, blobId, stageOpts);
+ } else {
+ const tarBytes = await fromSandbox.readFileBytes(fromHandle, tarRel);
+ if (!tarBytes) throw new Error("copyHome: source tar vanished before read");
+ await toSandbox.writeFileBytes(toHandle, tarRel, tarBytes);
+ }
- if (fromHome !== toHome) {
- const t = await toSandbox.run(toHandle, translateScript(toHome, fromHome), { timeoutMs: 120_000 });
- if (t.code !== 0)
- throw new Error(`copyHome: translation failed (${t.code}): ${(t.stderr || t.stdout).slice(0, 200)}`);
- }
+ const extracted = await toSandbox.run(
+ toHandle,
+ `dsha=$(sha256sum ${shq(toTarPath)} | cut -d' ' -f1); [ "$dsha" = ${shq(sha)} ] || { echo "sha-mismatch:$dsha"; exit 3; }; mkdir -p ${T} && cd ${T} && tar xzf ${shq(toTarPath)} 2>/dev/null && find . -type f ! -name ${shq(`${HOME_TAR_PREFIX}*.tgz`)} | wc -l`,
+ { timeoutMs },
+ );
+ if (extracted.code !== 0) {
+ throw new Error(
+ `copyHome: dest verify/extract failed (${extracted.code}): ${(extracted.stderr || extracted.stdout).slice(0, 200)}`,
+ );
+ }
+ const destFiles = Number.parseInt(extracted.stdout.trim().split("\n").pop() ?? "", 10);
- await Promise.all([
- fromSandbox.run(fromHandle, `rm -f ${tarPath}`, { timeoutMs: 30_000 }).catch(() => {}),
- toSandbox.run(toHandle, `rm -f ${tarPath}`, { timeoutMs: 30_000 }).catch(() => {}),
- ]);
+ if (fromHome !== toHome) {
+ const t = await toSandbox.run(toHandle, translateScript(toHome, fromHome), { timeoutMs: 120_000 });
+ if (t.code !== 0)
+ throw new Error(`copyHome: translation failed (${t.code}): ${(t.stderr || t.stdout).slice(0, 200)}`);
+ }
- return { bytes, sha, sourceFiles, destFiles };
+ return { bytes, sha, sourceFiles, destFiles };
+ }
}
diff --git a/test/e2b-sandbox.test.ts b/test/e2b-sandbox.test.ts
index b92c5992f..fdcf78f3d 100644
--- a/test/e2b-sandbox.test.ts
+++ b/test/e2b-sandbox.test.ts
@@ -309,8 +309,9 @@ test("adoptHomeSnapshot promotes a staged blob to the snapshot store and resets
await s.adoptHomeSnapshot!(scope, blobId);
const b = await s.provision(layers);
- assert.equal(await s.readFile(b, "../migrated.txt"), "came from sprites\n", "hydrates from the adopted snapshot");
- assert.equal(await s.readFile(b, "../old.txt"), null, "the pre-adopt sandbox was discarded, not reused");
+ const migrated = await s.run(b, "cat ~/migrated.txt");
+ assert.equal(migrated.stdout, "came from sprites\n", "hydrates from the adopted snapshot");
+ assert.notEqual((await s.run(b, "cat ~/old.txt")).code, 0, "the pre-adopt sandbox was discarded, not reused");
});
test("blob staging is advertised only when the channel is actually wired", async () => {
diff --git a/test/exec-file-ops.test.ts b/test/exec-file-ops.test.ts
index f8505f502..76d0f467e 100644
--- a/test/exec-file-ops.test.ts
+++ b/test/exec-file-ops.test.ts
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
-import { createExecFileOps } from "../src/sandbox/exec-file-ops.ts";
+import { createExecFileOps, posixJoin } from "../src/sandbox/exec-file-ops.ts";
const exec = promisify(execFile);
@@ -70,3 +70,10 @@ test("combined cleanup is opt-in for provider implementations", () => {
});
assert.equal(ops.removeDirAndList, undefined);
});
+
+test("posixJoin rejects parent path segments", () => {
+ assert.equal(posixJoin("/root/workspace", "a/b.txt"), "/root/workspace/a/b.txt");
+ assert.equal(posixJoin("/root/workspace/", "/a/./b.txt"), "/root/workspace/a/./b.txt");
+ assert.throws(() => posixJoin("/root/workspace", "../x"), /must stay inside the workspace/);
+ assert.throws(() => posixJoin("/root/workspace", "a/../../x"), /must stay inside the workspace/);
+});
diff --git a/test/modal-sandbox.test.ts b/test/modal-sandbox.test.ts
index dfe7ebaaf..ae39463fd 100644
--- a/test/modal-sandbox.test.ts
+++ b/test/modal-sandbox.test.ts
@@ -428,8 +428,9 @@ test("adoptHomeSnapshot promotes a staged blob to the snapshot store and resets
await s.adoptHomeSnapshot!(scope, blobId);
const b = await s.provision(layers);
- assert.equal(await s.readFile(b, "../migrated.txt"), "came from e2b\n", "hydrates from the adopted snapshot");
- assert.equal(await s.readFile(b, "../old.txt"), null, "the pre-adopt sandbox was discarded, not reused");
+ const migrated = await s.run(b, "cat ~/migrated.txt");
+ assert.equal(migrated.stdout, "came from e2b\n", "hydrates from the adopted snapshot");
+ assert.notEqual((await s.run(b, "cat ~/old.txt")).code, 0, "the pre-adopt sandbox was discarded, not reused");
});
test("persistHomeSnapshot writes the live home to the snapshot store on demand", async () => {
@@ -509,11 +510,13 @@ test("homes larger than the file chunk size snapshot and hydrate through chunked
const h = await s.provision(layers);
const big = Buffer.alloc(50 * 1024 + 7);
for (let i = 0; i < big.length; i++) big[i] = (i * 31) % 256;
- await s.writeFileBytes(h, "../big.bin", big);
+ await s.writeFileBytes(h, "big.bin", big);
+ await s.run(h, "mv ~/workspace/big.bin ~/big.bin");
await s.teardown(h);
fake.terminate(h.id);
const b = await s.provision(layers);
- const back = await s.readFileBytes(b, "../big.bin");
+ await s.run(b, "cp ~/big.bin ~/workspace/big.bin");
+ const back = await s.readFileBytes(b, "big.bin");
assert.ok(back && Buffer.from(back).equals(big), "chunked snapshot + hydrate round-trips the exact bytes");
});
diff --git a/test/sandbox-migrate.test.ts b/test/sandbox-migrate.test.ts
index 4bdeaa4e4..9ec948247 100644
--- a/test/sandbox-migrate.test.ts
+++ b/test/sandbox-migrate.test.ts
@@ -5,13 +5,14 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync
import { tmpdir } from "node:os";
import { join, dirname } from "node:path";
import { copyHome } from "../src/sandbox/sandbox-migrate.ts";
+import { posixJoin } from "../src/sandbox/exec-file-ops.ts";
import type { Sandbox, SandboxHandle, ExecResult } from "../src/sandbox/sandbox.ts";
function hostSandbox(homeDir: string): { sandbox: Sandbox; handle: SandboxHandle } {
mkdirSync(homeDir, { recursive: true });
const rootDir = join(homeDir, "workspace");
mkdirSync(rootDir, { recursive: true });
- const resolve = (rel: string) => join(rootDir, rel);
+ const resolve = (rel: string) => posixJoin(rootDir, rel);
const sandbox: Partial<Sandbox> = {
async run(_h, command): Promise<ExecResult> {
const r = spawnSync("sh", ["-c", command], {
diff --git a/test/sandbox-migration-runner.test.ts b/test/sandbox-migration-runner.test.ts
index 68c421b68..d865bbb14 100644
--- a/test/sandbox-migration-runner.test.ts
+++ b/test/sandbox-migration-runner.test.ts
@@ -14,13 +14,14 @@ import { join, dirname } from "node:path";
import { createSandboxMigrationRunner } from "../src/sandbox/sandbox-migration-runner.ts";
import { createMemoryMap } from "../src/persistence/durable-map.ts";
import type { SandboxRoute } from "../src/sandbox/sandbox-routing.ts";
+import { posixJoin } from "../src/sandbox/exec-file-ops.ts";
import type { Sandbox, SandboxHandle, ExecResult } from "../src/sandbox/sandbox.ts";
function hostBackend(name: string, homeDir: string): Sandbox & { tornDown: number } {
mkdirSync(homeDir, { recursive: true });
const rootDir = join(homeDir, "workspace");
mkdirSync(rootDir, { recursive: true });
- const resolve = (rel: string) => join(rootDir, rel);
+ const resolve = (rel: string) => posixJoin(rootDir, rel);
const s = {
tornDown: 0,
profile: { backend: name, writablePersistence: "resident_disk" as const, processSessions: false },
diff --git a/test/smolmachines-sandbox.test.ts b/test/smolmachines-sandbox.test.ts
index 2595cedd2..7ca38742b 100644
--- a/test/smolmachines-sandbox.test.ts
+++ b/test/smolmachines-sandbox.test.ts
@@ -212,3 +212,16 @@ test("profile advertises resident disk and process sessions", () => {
assert.equal(sandbox.profile.writablePersistence, "resident_disk");
assert.equal(sandbox.profile.processSessions, true);
});
+
+test("read and write refuse parent path segments before any provider request", async () => {
+ const h = await sandbox.provision(layers);
+ fake.calls.length = 0;
+ for (const rel of ["../../../../../machines", "../../../../m-2/files/root/x", "a/../../b"]) {
+ await assert.rejects(sandbox.readFile(h, rel), /must stay inside the workspace/);
+ await assert.rejects(sandbox.writeFile(h, rel, "x"), /must stay inside the workspace/);
+ }
+ assert.deepEqual(
+ fake.calls.filter((c) => c.path.includes("/files")),
+ [],
+ );
+});