diff --git a/packages/seat/src/sandbox.mjs b/packages/seat/src/sandbox.mjs index a22c2ef37..0a1ca5029 100644 --- a/packages/seat/src/sandbox.mjs +++ b/packages/seat/src/sandbox.mjs @@ -204,10 +204,11 @@ export function sandboxArgv(list, runDir, command, { business, role, bwrap = BWR // never /tmp, the run directory or a system bind's dest, nor inside or around one, never a parent // of or equal to a runner file, the adapter or node, and never in or around another mount's dest. // At most HOSTED_MOUNTS_MAX mounts. A refusal is a HostedRouteError naming its fence, never a path. -// `codeRoot` is the stack's own code. A protected path the caller names that holds the code root -// (HOME, when the stack runs from a copy or a worktree under it) does not refuse a source whose -// named and real paths both lie in the code root. Every other check still applies to it, and the -// run directory and ALWAYS_PROTECTED are never set aside. +// `codeRoot` is the stack's own code and `codeHolder` the one protected path that may hold it: +// HOME, when the stack runs from a copy or a worktree under it. That path does not refuse a source +// whose named and real paths both lie in the code root. Every other check still applies to it, and +// no other protected path, the run directory or ALWAYS_PROTECTED is ever set aside. A code root in +// or around the run directory or ALWAYS_PROTECTED, in either path's spelling or real path, is refused. export const HOSTED_MOUNTS_MAX = 8; const ROOTS_MAX = 16; const PATH_MAX = 4096; @@ -231,24 +232,30 @@ const secretPath = (p) => p.split("/").some((seg) => /secret/i.test(seg)); const realOr = (p) => { try { return realpathSync(p); } catch { return p; } }; const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o)); -export function checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot = null, runDir, node = process.execPath }) { +export function checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot = null, codeHolder = null, runDir, node = process.execPath }) { if (!cleanPath(runDir)) refuseRoute("protected", "the run directory is not a clean absolute path"); if (!Array.isArray(protectedPaths)) refuseRoute("protected", "no protected paths were given"); + // Lists are copied once, so a Proxy cannot answer one length to a check and another to the map. + protectedPaths = Array.from(protectedPaths); let code = null; if (codeRoot !== null) { if (!cleanPath(codeRoot)) refuseRoute("protected", "the code root is not a clean absolute path"); + if (!protectedPaths.includes(codeHolder)) refuseRoute("protected", "the code root's holder is not a protected path"); code = [codeRoot, realOr(codeRoot)]; - if (code.some((c) => overlaps(c, runDir) || ALWAYS_PROTECTED.some((g) => overlaps(c, g)))) refuseRoute("protected", "the code root is in or around a path that is never set aside"); + const fixed = [runDir, ...ALWAYS_PROTECTED].flatMap((g) => [g, realOr(g)]); + if (code.some((c) => fixed.some((g) => overlaps(c, g)))) refuseRoute("protected", "the code root is in or around a path that is never set aside"); } // Each guarded entry: its spellings, and whether a source in the code root is clear of it. const guarded = []; - for (const [p, mayHoldCode] of [...ALWAYS_PROTECTED.map((g) => [g, false]), ...protectedPaths.map((g) => [g, true]), [runDir, false]]) { + for (const [p, mayHoldCode] of [...ALWAYS_PROTECTED.map((g) => [g, false]), ...protectedPaths.map((g) => [g, g === codeHolder]), [runDir, false]]) { if (!cleanPath(p)) refuseRoute("protected", "a protected path is not a clean absolute path"); const spellings = [p, realOr(p)]; const holdsCode = mayHoldCode && code !== null && spellings.some((g) => code.some((c) => c !== g && within(c, g))); guarded.push({ spellings, holdsCode }); } - if (!Array.isArray(installRoots) || installRoots.length === 0 || installRoots.length > ROOTS_MAX) refuseRoute("roots", "the harness module declares no usable install roots"); + if (!Array.isArray(installRoots)) refuseRoute("roots", "the harness module declares no usable install roots"); + installRoots = Array.from(installRoots); + if (installRoots.length === 0 || installRoots.length > ROOTS_MAX) refuseRoute("roots", "the harness module declares no usable install roots"); const roots = installRoots.map((r) => { if (!cleanPath(r)) refuseRoute("roots", "an install root is not a clean absolute path"); let real; @@ -268,7 +275,9 @@ export function checkHostedRoute({ adapter, harnessMounts, installRoots, protect }; const adapterReal = source(adapter, "adapter", "the adapter"); if (!statSync(adapterReal).isFile()) refuseRoute("adapter", "the adapter is not a file"); - if (!Array.isArray(harnessMounts) || harnessMounts.length > HOSTED_MOUNTS_MAX) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`); + if (!Array.isArray(harnessMounts)) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`); + harnessMounts = Array.from(harnessMounts); + if (harnessMounts.length > HOSTED_MOUNTS_MAX) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`); const apart = ["/tmp", runDir, ...systemBinds(node).map((b) => b.dest ?? b.src)]; const kept = [...RUNNER_FILES, adapter, node]; const dests = []; @@ -296,8 +305,8 @@ export function checkHostedRoute({ adapter, harnessMounts, installRoots, protect // launch or git socket, thread store or org root. Each source inside runDir must be what the host // just made there, never a link the session left: bwrap resolves a bind's source on the host. // The adapter and the mounts pass checkHostedRoute against `installRoots`, `protectedPaths` and -// `codeRoot` here too; without install roots nothing binds. -export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, codeRoot = null, relaySocket, node = process.execPath, readOnly = [] }) { +// `codeRoot` with its `codeHolder` here too; without install roots nothing binds. +export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, codeRoot = null, codeHolder = null, relaySocket, node = process.execPath, readOnly = [] }) { if (relaySocket !== join(runDir, "relay.sock")) throw new Error("hosted binds: the relay socket must be the run directory's relay.sock"); const healthDest = join(runDir, "work", "health"); for (const p of [runDir, healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work"), healthDest]) { @@ -310,7 +319,7 @@ export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], in try { st = lstatSync(p); } catch { throw new Error(`hosted binds: ${relative(runDir, p)} is missing`); } if (!ok(st)) throw new Error(`hosted binds: ${relative(runDir, p)} is not what the host made`); } - const route = checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot, runDir, node }); + const route = checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot, codeHolder, runDir, node }); const out = systemBinds(node); for (const f of RUNNER_FILES) out.push({ kind: "ro", src: f, why: "a repository file the runner loads" }); out.push({ kind: "ro", src: route.adapter.src, ...(route.adapter.src !== adapter ? { dest: adapter } : {}), why: "the harness adapter the runner starts each turn" }); diff --git a/packages/seat/tests/hosted-binds.test.mjs b/packages/seat/tests/hosted-binds.test.mjs index 41cd09a96..b8b75992c 100644 --- a/packages/seat/tests/hosted-binds.test.mjs +++ b/packages/seat/tests/hosted-binds.test.mjs @@ -6,7 +6,7 @@ import assert from "node:assert/strict"; import { createServer } from "node:net"; import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; -import { HOSTED_MOUNTS_MAX, RUNNER_FILES, hostedArgv, hostedBinds } from "../src/sandbox.mjs"; +import { HOSTED_MOUNTS_MAX, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds } from "../src/sandbox.mjs"; function layout(t) { const root = mkdtempSync(join(process.env.TMPDIR, "hb-")); @@ -143,7 +143,7 @@ test("a protected path that holds the code root (HOME over a copy or a worktree) for (const f of ["adapter.sh", "m", join("secrets", "k")]) writeFileSync(join(inst, f), "x"); writeFileSync(join(home, "outside"), "x"); mkdirSync(join(code, "data")); - const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: join(inst, "adapter.sh"), relaySocket: p.relaySocket, installRoots: [inst], protectedPaths: [p.dataRoot, home], codeRoot: code }; + const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: join(inst, "adapter.sh"), relaySocket: p.relaySocket, installRoots: [inst], protectedPaths: [p.dataRoot, home], codeRoot: code, codeHolder: home }; const refused = (opts, fence, label) => assert.throws(() => hostedBinds({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence, label); const list = hostedBinds({ ...base, harnessMounts: [{ src: join(inst, "m"), dest: "/opt/m", why: "w" }] }); assert.ok(list.some((b) => b.src === join(inst, "adapter.sh")) && list.some((b) => b.src === join(inst, "m") && b.dest === "/opt/m")); @@ -165,6 +165,39 @@ test("a protected path that holds the code root (HOME over a copy or a worktree) refused({ codeRoot: p.root, installRoots: [p.root], harnessMounts: [{ src: join(p.dataRoot, "orgs"), why: "w" }] }, "protected", "code root holds the run dir"); refused({ codeRoot: "/srv/mosaic/x" }, "protected", "code root in a fixed path"); refused({ codeRoot: "relative" }, "protected", "relative code root"); + // Only the named holder sets the code aside: another protected path that holds the code still refuses. + refused({ protectedPaths: [p.dataRoot, home, p.root] }, "adapter", "a second protected path holds the code"); + refused({ codeHolder: null }, "protected", "no holder"); + refused({ codeHolder: join(p.root, "elsewhere") }, "protected", "a holder that is not a protected path"); + // A run directory named through a link: a code root in its real path is refused before any check. + const realRun = join(home, "run"); + mkdirSync(join(realRun, "code", "inst"), { recursive: true }); + writeFileSync(join(realRun, "code", "inst", "a.sh"), "x"); + symlinkSync(realRun, join(p.root, "runlink")); + assert.throws(() => checkHostedRoute({ adapter: join(realRun, "code", "inst", "a.sh"), harnessMounts: [], installRoots: [join(realRun, "code", "inst")], protectedPaths: [p.dataRoot, home], codeRoot: join(realRun, "code"), codeHolder: home, runDir: join(p.root, "runlink") }), (e) => e.fence === "protected", "code root in the run dir's real path"); +}); + +test("a list that answers one length to the check and another later is read once", async (t) => { + const p = await layout(t); + const items = []; + for (let i = 0; i <= HOSTED_MOUNTS_MAX; i++) { writeFileSync(join(p.install, `m${i}`), "x"); items.push({ src: join(p.install, `m${i}`), dest: `/opt/m${i}`, why: "w" }); } + let reads = 0; + const mounts = new Proxy(items, { get: (o, k) => (k === "length" ? (reads++ === 0 ? 1 : o.length) : o[k]) }); + assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: mounts, installRoots: p.installRoots, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "mounts"); + // Install roots: two short answers pass the count, then a long one would add roots the count never saw. + const roots = []; + for (let i = 0; i <= 16; i++) { roots.push(join(p.root, `r${i}`)); mkdirSync(roots[i]); } + writeFileSync(join(roots[16], "a.sh"), "x"); + let rootReads = 0; + const rootList = new Proxy(roots, { get: (o, k) => (k === "length" ? (rootReads++ < 2 ? 1 : o.length) : o[k]) }); + assert.throws(() => checkHostedRoute({ adapter: join(roots[16], "a.sh"), harnessMounts: [], installRoots: rootList, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "adapter"); + // Protected paths: the holder check sees HOME, then a shorter answer would leave HOME unguarded. + const home = join(p.root, "home"); + mkdirSync(join(home, "code"), { recursive: true }); + writeFileSync(join(home, "f"), "x"); + let guardReads = 0; + const guards = new Proxy([p.dataRoot, home], { get: (o, k) => (k === "length" ? (guardReads++ === 0 ? 2 : 1) : o[k]) }); + assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: [{ src: join(home, "f"), dest: "/opt/f", why: "w" }], installRoots: [p.install, home], protectedPaths: guards, codeRoot: join(home, "code"), codeHolder: home, runDir: p.runDir }), (e) => e.fence === "protected" || e.fence === "mount-src"); }); test("each mount field is read once, and no mount's dest lies in or around another's", async (t) => { diff --git a/packages/webui/src/triage-host.mjs b/packages/webui/src/triage-host.mjs index 8335b9b9a..16eff6d3f 100644 --- a/packages/webui/src/triage-host.mjs +++ b/packages/webui/src/triage-host.mjs @@ -75,12 +75,12 @@ const ENV_VALUE_MAX = 4096; const HARNESS_ENV_MAX = 64; // Refused in harnessEnv even when the harness module declares them: the runner's own MOSAIC_* // values, loader, libc and interpreter hooks, the shell's start files, a tool's config directory -// and the founder's. A provider name (every ANTHROPIC_* among them) goes through route env or nowhere. +// and the founder's, an askpass program, a CA bundle or a base URL. A provider name (every ANTHROPIC_* among them) goes through route env or nowhere. const REFUSED_PREFIX = /^(MOSAIC_|NODE_|LD_|DYLD_|PYTHON|BASH_|GIT_|MALLOC_|NPM_CONFIG_|XDG_)/; -const REFUSED_SUFFIX = /_(DIR|CONF|CONFIG)$/; +const REFUSED_SUFFIX = /_(DIR|CONF|CONFIG|ASKPASS|CA_BUNDLE|BASE_URL)$/; const REFUSED_NAMES = new Set([ "PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK", "SHELL", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "CDPATH", - "GLOBIGNORE", "PROMPT_COMMAND", "ZDOTDIR", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", + "GLOBIGNORE", "PROMPT_COMMAND", "ZDOTDIR", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "PERLLIB", "LESSOPEN", "LESSCLOSE", "HOSTALIASES", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY", "GCONV_PATH", "GLIBC_TUNABLES", "LOCPATH", "OPENSSL_CONF", "OPENSSL_ENGINES", "OPENSSL_MODULES", "SSL_CERT_FILE", "SSL_CERT_DIR", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS", ...FOUNDER_ENV, @@ -356,7 +356,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async let installRoots; try { installRoots = structuredClone(mod.installRoots({ env })); } catch { refuse("module"); } try { - checkHostedRoute({ adapter: a.adapter, harnessMounts: a.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, runDir: paths.agent, node }); + checkHostedRoute({ adapter: a.adapter, harnessMounts: a.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, runDir: paths.agent, node }); } catch (e) { if (e?.code === "hosted-binds-refused") refuse(e.fence); throw e; @@ -392,7 +392,7 @@ export function createTriageHost({ dataRoot, route = null, readSnapshot = async }); let list; try { - list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, relaySocket: join(paths.agent, "relay.sock"), node, readOnly }); + list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, relaySocket: join(paths.agent, "relay.sock"), node, readOnly }); } catch (e) { if (e?.code !== "hosted-binds-refused") throw e; log(`triage host: route refused at the binds: ${e.fence}`); diff --git a/packages/webui/tests/triage-host.test.mjs b/packages/webui/tests/triage-host.test.mjs index c964f35f1..9a71a88b7 100644 --- a/packages/webui/tests/triage-host.test.mjs +++ b/packages/webui/tests/triage-host.test.mjs @@ -220,7 +220,8 @@ test("fence 1: a harnessEnv name the host refuses is refused even when the harne for (const name of [ "GIT_DIR", "BASH_FUNC_x%%", "LD_AUDIT", "SHELLOPTS", "PS4", "IFS", "HTTPS_PROXY", "NODE_EXTRA_CA_CERTS", "PYTHONHOME", "MOSAIC_X", "GCONV_PATH", "LOCPATH", "MALLOC_CHECK_", "OPENSSL_CONF", "SSL_CERT_FILE", "ZDOTDIR", "PROMPT_COMMAND", "JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "NPM_CONFIG_PREFIX", - "CLAUDE_CONFIG_DIR", "XDG_DATA_HOME", "ANY_CONF", "ANY_CONFIG", + "CLAUDE_CONFIG_DIR", "XDG_DATA_HOME", "ANY_CONF", "ANY_CONFIG", "PERLLIB", "LESSOPEN", "LESSCLOSE", "HOSTALIASES", + "SSH_ASKPASS", "SUDO_ASKPASS", "CURL_CA_BUNDLE", "REQUESTS_CA_BUNDLE", "OPENAI_BASE_URL", "ANY_BASE_URL", ]) assert.equal(refusedHarnessName(name), true, name); for (const name of ["FAKE_OK", "PI_MODEL", "TRIAGE_PROBE"]) assert.equal(refusedHarnessName(name), false, name); }); @@ -392,7 +393,7 @@ test("the shipped harness modules declare what their own env() and mounts() hand // A stack that runs from under HOME (a copy or a worktree): HOME holds the repository, and the // code root keeps HOME from refusing the stack's own files. Without it, HOME refuses them. const underHome = { ...route, protectedPaths: [join(dir, "data"), join(dir, "cfg"), dirname(REPO)] }; - assert.equal(checkHostedRoute({ ...underHome, codeRoot: REPO }).adapter.dest, mod.adapter(), name); + assert.equal(checkHostedRoute({ ...underHome, codeRoot: REPO, codeHolder: dirname(REPO) }).adapter.dest, mod.adapter(), name); assert.throws(() => checkHostedRoute(underHome), (e) => e.fence === "adapter", name); } }); @@ -405,8 +406,11 @@ test("a host whose HOME holds the repository starts the shipped pi harness's own const s = await admittedRoute(t, "pi under HOME", (root) => () => piRoute(root), opts); assert.equal(s.adapter, pi.adapter()); assert.deepEqual(s.harnessEnv, { PI_MODEL: "m", PI_OFFLINE: "1" }); - // A module whose install root is under HOME but outside the repository. - await refusedRoute(t, "under HOME, outside the repository", (root) => ({}), (root) => ({ home: root, harnessModule: fakeModule([join(root, "install")]) })); + // The same host and module, with HOME's own directory (which holds the repository) as an extra + // install root and mount: it is under HOME and not in the code, so it is refused. + const wide = { ...pi, installRoots: (o) => [...pi.installRoots(o), home] }; + const logs = await refusedRoute(t, "under HOME, outside the repository", (root) => () => ({ ...piRoute(root), harnessMounts: [...pi.mounts({ env: {} }), { src: home, dest: "/opt/home", why: "w" }] }), { home, harnessModule: async (name) => (name === "pi" ? wide : null) }); + assert.ok(logs.includes("triage host: route refused: mount-src"), logs.join(" | ")); }); test("a route that changes after the first check is refused at the binds: nothing spawns, what the start wrote is removed, and the next message starts", async (t) => {