fix(webui): triage fences review, HOME is not counted against the stack's own code: a caller's protected path that holds the code root sets aside a source whose named and real paths both lie in it, never the run dir or a fixed path, so pi starts from a copy or worktree under HOME; a refusal at the binds answers triage-route-invalid and removes what the start wrote; each mount field is read once and no dest lies in or around another; values refuse every C0 and C1 control and U+2028/U+2029; the token shape drops the m flag; the refuse list adds MALLOC_, NPM_CONFIG_, XDG_, names ending _DIR, _CONF or _CONFIG, and the libc, shell, OpenSSL and Java hooks (#1873, lane triage-fences)
This commit is contained in:
1 parent
1ca3a38f86
commit
2f91ff5bea
6 files changed
+195
-43
No files matched your search
@@ -264,13 +264,18 @@ export returns:
|
||||
names `env()` returns, less the provider's. The host takes a route's
|
||||
`harnessEnv` name only when it is listed here and is not one the host
|
||||
always refuses: `MOSAIC_*`, `NODE_*`, `LD_*`, `DYLD_*`, `PYTHON*`, `BASH_*`,
|
||||
`GIT_*`, PATH, HOME, TMPDIR, ENV, the founder's and the provider's names
|
||||
and a few shell and proxy names. `installRoots` lists the directories
|
||||
`GIT_*`, `MALLOC_*`, `NPM_CONFIG_*`, `XDG_*`, any name ending in `_DIR`,
|
||||
`_CONF` or `_CONFIG`, PATH, HOME, TMPDIR, ENV, the founder's and the
|
||||
provider's names, and named shell, proxy, libc, OpenSSL and Java hooks. `installRoots` lists the directories
|
||||
where the adapter and the mounts live. A hosted adapter or mount source
|
||||
must resolve inside one of them, and never in or around the data root,
|
||||
the config directory, HOME, `/srv/mosaic` or a path with a `secret`
|
||||
segment. Every claude-code name is `MOSAIC_*`, so a hosted session cannot
|
||||
run Claude Code yet.
|
||||
segment. HOME does not count against a source inside the stack's own
|
||||
code, so a copy or a worktree under HOME still passes. Every claude-code
|
||||
name is `MOSAIC_*`, so a hosted session cannot run Claude Code yet. pi's
|
||||
`MOSAIC_TOOLS`, `MOSAIC_EXTENSIONS` and `MOSAIC_THINKING` are refused the
|
||||
same way, so a hosted pi gets no tools and no extension until the host
|
||||
sets those names itself.
|
||||
- `compactions({store, cursors, budget, streams, first})` reads a thread
|
||||
session's native store for row 270's compaction count (row 307). Core keeps
|
||||
the ledger (`packages/seat/src/compactions.mjs`) and passes `store` as
|
||||
|
||||
@@ -120,7 +120,9 @@ export function env({ policy, tools, session, proxy = null }) {
|
||||
|
||||
// #1873 triage-fences: the names env() returns, less the provider key, and the directories its
|
||||
// adapter and mounts live in. A hosted session's host (Triage) takes harnessEnv names and mount
|
||||
// sources only from these; launches don't read them.
|
||||
// sources only from these; launches don't read them. The host refuses every MOSAIC_* name from a
|
||||
// route, so MOSAIC_TOOLS, MOSAIC_EXTENSIONS and MOSAIC_THINKING are listed only to say what env()
|
||||
// hands a session: a hosted pi needs the host to set them itself (a later slice).
|
||||
export const envNames = Object.freeze(["PI_OFFLINE", "MOSAIC_TOOLS", "MOSAIC_EXTENSIONS", "PI_PROVIDER", "PI_MODEL", "MOSAIC_THINKING"]);
|
||||
export const installRoots = () => [join(REPO, "adapters", "pi"), join(REPO, "packages", "plugins", "harness", "pi"), realpathSync(join(REPO, "node_modules")), join(REPO, "tools", "unslop-hook")];
|
||||
|
||||
|
||||
@@ -202,8 +202,12 @@ export function sandboxArgv(list, runDir, command, { business, role, bwrap = BWR
|
||||
// a source may neither lie inside one nor contain one. The bind's source is the real path, so a
|
||||
// link swapped after the check cannot steer it. A mount's dest (its source when it names none) is
|
||||
// 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 repeated. At most
|
||||
// HOSTED_MOUNTS_MAX mounts. A refusal is a HostedRouteError naming its fence, never a path.
|
||||
// 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.
|
||||
export const HOSTED_MOUNTS_MAX = 8;
|
||||
const ROOTS_MAX = 16;
|
||||
const PATH_MAX = 4096;
|
||||
@@ -227,13 +231,22 @@ 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, runDir, node = process.execPath }) {
|
||||
export function checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot = 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");
|
||||
let code = null;
|
||||
if (codeRoot !== null) {
|
||||
if (!cleanPath(codeRoot)) refuseRoute("protected", "the code root is not a clean absolute 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");
|
||||
}
|
||||
// Each guarded entry: its spellings, and whether a source in the code root is clear of it.
|
||||
const guarded = [];
|
||||
for (const p of [...ALWAYS_PROTECTED, ...protectedPaths, runDir]) {
|
||||
for (const [p, mayHoldCode] of [...ALWAYS_PROTECTED.map((g) => [g, false]), ...protectedPaths.map((g) => [g, true]), [runDir, false]]) {
|
||||
if (!cleanPath(p)) refuseRoute("protected", "a protected path is not a clean absolute path");
|
||||
guarded.push(p, realOr(p));
|
||||
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");
|
||||
const roots = installRoots.map((r) => {
|
||||
@@ -248,7 +261,8 @@ export function checkHostedRoute({ adapter, harnessMounts, installRoots, protect
|
||||
let real;
|
||||
try { real = realpathSync(src); } catch { refuseRoute(fence, `${what} is missing`); }
|
||||
if (!roots.some((r) => (within(src, r.named) || within(src, r.real)) && within(real, r.real))) refuseRoute(fence, `${what} is not under an install root`);
|
||||
if ([src, real].some((p) => guarded.some((g) => overlaps(p, g)))) refuseRoute(fence, `${what} is in or around a protected path`);
|
||||
const inCode = code !== null && code.some((c) => within(src, c)) && within(real, code[1]);
|
||||
if (guarded.some((g) => !(g.holdsCode && inCode) && [src, real].some((p) => g.spellings.some((s) => overlaps(p, s))))) refuseRoute(fence, `${what} is in or around a protected path`);
|
||||
if ([src, real].some(secretPath)) refuseRoute(fence, `${what} is in a secrets path`);
|
||||
return real;
|
||||
};
|
||||
@@ -257,16 +271,19 @@ export function checkHostedRoute({ adapter, harnessMounts, installRoots, protect
|
||||
if (!Array.isArray(harnessMounts) || 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 = new Set();
|
||||
const dests = [];
|
||||
const mounts = harnessMounts.map((m, i) => {
|
||||
const what = `harness mount ${i + 1}`;
|
||||
if (!plainObject(m) || Object.keys(m).some((k) => !MOUNT_KEYS.includes(k)) || typeof m.why !== "string" || !m.why || m.why.length > 256) refuseRoute("mounts", `${what} is not { src, dest, why }`);
|
||||
if (m.dest !== undefined && !cleanPath(m.dest)) refuseRoute("mount-dest", `${what}'s dest is not a clean absolute path`);
|
||||
const real = source(m.src, "mount-src", what);
|
||||
const dest = m.dest ?? m.src;
|
||||
if (apart.some((p) => overlaps(dest, p)) || kept.some((p) => within(p, dest)) || dests.has(dest)) refuseRoute("mount-dest", `${what}'s dest would cover a path the session needs`);
|
||||
dests.add(dest);
|
||||
return { src: real, dest, why: m.why };
|
||||
if (!plainObject(m) || Object.keys(m).some((k) => !MOUNT_KEYS.includes(k))) refuseRoute("mounts", `${what} is not { src, dest, why }`);
|
||||
// Each field is read once, so a getter cannot answer one value to a check and another to the bind.
|
||||
const { src, dest: named, why } = m;
|
||||
if (typeof why !== "string" || !why || why.length > 256) refuseRoute("mounts", `${what} is not { src, dest, why }`);
|
||||
if (named !== undefined && !cleanPath(named)) refuseRoute("mount-dest", `${what}'s dest is not a clean absolute path`);
|
||||
const real = source(src, "mount-src", what);
|
||||
const dest = named ?? src;
|
||||
if (apart.some((p) => overlaps(dest, p)) || kept.some((p) => within(p, dest)) || dests.some((d) => overlaps(dest, d))) refuseRoute("mount-dest", `${what}'s dest would cover a path the session needs`);
|
||||
dests.push(dest);
|
||||
return { src: real, dest, why };
|
||||
});
|
||||
return { adapter: { src: adapterReal, dest: adapter }, mounts };
|
||||
}
|
||||
@@ -278,9 +295,9 @@ export function checkHostedRoute({ adapter, harnessMounts, installRoots, protect
|
||||
// calls through stay read-only inside it, and its tmp/ is /tmp. There is no workspace, broker,
|
||||
// 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` and `protectedPaths`
|
||||
// here too; without install roots nothing binds.
|
||||
export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, relaySocket, node = process.execPath, readOnly = [] }) {
|
||||
// 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 = [] }) {
|
||||
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]) {
|
||||
@@ -293,7 +310,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, runDir, node });
|
||||
const route = checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot, 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" });
|
||||
|
||||
@@ -132,3 +132,53 @@ test("hosted binds bind the real file of a link that stays inside the install ro
|
||||
assert.ok(list.some((b) => b.kind === "ro" && b.src === join(p.install, "real.mjs") && b.dest === "/opt/real.mjs" && b.why === "w2"));
|
||||
assert.ok(!list.some((b) => b.src === join(p.install, "named.mjs")));
|
||||
});
|
||||
|
||||
test("a protected path that holds the code root (HOME over a copy or a worktree) does not refuse a source inside the code root; everything else still holds", async (t) => {
|
||||
const p = await layout(t);
|
||||
// home/ holds the code root code/, which holds the install root.
|
||||
const home = join(p.root, "home");
|
||||
const code = join(home, "code");
|
||||
const inst = join(code, "inst");
|
||||
mkdirSync(join(inst, "secrets"), { recursive: true });
|
||||
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 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"));
|
||||
// Without the code root, HOME refuses the same adapter.
|
||||
refused({ codeRoot: null }, "adapter", "no code root");
|
||||
// A code root that is HOME itself sets nothing aside.
|
||||
refused({ codeRoot: home }, "adapter", "code root is HOME");
|
||||
// A source under HOME outside the code root, even inside an install root.
|
||||
refused({ installRoots: [home], adapter: join(home, "outside") }, "adapter", "outside the code root");
|
||||
// A link inside the code root to a file outside it.
|
||||
symlinkSync(join(home, "outside"), join(inst, "out"));
|
||||
refused({ installRoots: [inst, home], harnessMounts: [{ src: join(inst, "out"), why: "w" }] }, "mount-src", "link out of the code root");
|
||||
// A protected path inside the code root still refuses.
|
||||
writeFileSync(join(code, "data", "f"), "x");
|
||||
refused({ installRoots: [code], protectedPaths: [p.dataRoot, home, join(code, "data")], harnessMounts: [{ src: join(code, "data", "f"), why: "w" }] }, "mount-src", "protected path in the code root");
|
||||
// The secrets check still holds inside the code root.
|
||||
refused({ harnessMounts: [{ src: join(inst, "secrets", "k"), why: "w" }] }, "mount-src", "secrets in the code root");
|
||||
// The run directory and the fixed list are never set aside, and a code root around them is refused.
|
||||
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");
|
||||
});
|
||||
|
||||
test("each mount field is read once, and no mount's dest lies in or around another's", async (t) => {
|
||||
const p = await layout(t);
|
||||
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
|
||||
writeFileSync(join(p.install, "m"), "x");
|
||||
writeFileSync(join(p.install, "n"), "x");
|
||||
let reads = 0;
|
||||
const list = hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), why: "w", get dest() { return reads++ === 0 ? undefined : "/opt/../tmp"; } }] });
|
||||
assert.equal(reads, 1);
|
||||
assert.ok(list.some((b) => b.src === join(p.install, "m") && b.dest === undefined));
|
||||
assert.ok(!list.some((b) => b.dest === "/opt/../tmp"));
|
||||
for (const [a, b] of [["/opt/x", "/opt/x/f"], ["/opt/x/f", "/opt/x"], ["/opt/x", "/opt/x"]]) {
|
||||
assert.throws(() => hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: a, why: "w" }, { src: join(p.install, "n"), dest: b, why: "w" }] }), (e) => e.fence === "mount-dest", `${a} then ${b}`);
|
||||
}
|
||||
assert.equal(hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: "/opt/x", why: "w" }, { src: join(p.install, "n"), dest: "/opt/xy", why: "w" }] }).filter((b) => b.dest?.startsWith("/opt/")).length, 2);
|
||||
});
|
||||
@@ -29,8 +29,9 @@
|
||||
// ANTHROPIC_BASE_URL loopback http on a port (the host's proxyPort when it names one) and the
|
||||
// token matching the host's tokenPattern when it names one. The adapter and the mounts pass
|
||||
// checkHostedRoute (sandbox.mjs) against the module's installRoots and the data root, the config
|
||||
// directory and HOME, here and again in hostedBinds. A refused answer reaches no spawn, answers
|
||||
// triage-route-invalid, and writes ROUTE_REFUSED to the transcript.
|
||||
// directory and HOME (HOME not counted against the stack's own code), here and again in
|
||||
// hostedBinds. A refused answer reaches no spawn, answers triage-route-invalid, and writes
|
||||
// ROUTE_REFUSED to the transcript; a refusal at the binds also removes what the start wrote.
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
@@ -73,16 +74,20 @@ const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
||||
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 and interpreter hooks, the shell's start files and the founder's. A provider
|
||||
// name (every ANTHROPIC_* among them) goes through route env or nowhere.
|
||||
const REFUSED_PREFIX = /^(MOSAIC_|NODE_|LD_|DYLD_|PYTHON|BASH_|GIT_)/;
|
||||
// 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.
|
||||
const REFUSED_PREFIX = /^(MOSAIC_|NODE_|LD_|DYLD_|PYTHON|BASH_|GIT_|MALLOC_|NPM_CONFIG_|XDG_)/;
|
||||
const REFUSED_SUFFIX = /_(DIR|CONF|CONFIG)$/;
|
||||
const REFUSED_NAMES = new Set([
|
||||
"PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK", "SHELL", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "CDPATH",
|
||||
"GLOBIGNORE", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
|
||||
"GLOBIGNORE", "PROMPT_COMMAND", "ZDOTDIR", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "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,
|
||||
]);
|
||||
export const refusedHarnessName = (k) => typeof k !== "string" || !ENV_NAME.test(k) || REFUSED_PREFIX.test(k) || REFUSED_NAMES.has(k) || isProviderVariable(k);
|
||||
const cleanValue = (v) => typeof v === "string" && v.length <= ENV_VALUE_MAX && !/[\0\n\r]/.test(v);
|
||||
export const refusedHarnessName = (k) => typeof k !== "string" || !ENV_NAME.test(k) || REFUSED_PREFIX.test(k) || REFUSED_SUFFIX.test(k) || REFUSED_NAMES.has(k) || isProviderVariable(k);
|
||||
// No control character of any kind (C0, DEL, C1) and no line or paragraph separator.
|
||||
const cleanValue = (v) => typeof v === "string" && v.length <= ENV_VALUE_MAX && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(v);
|
||||
const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o));
|
||||
// The proxy is on this machine: http, 127.0.0.1, a port, nothing after it.
|
||||
const LOOPBACK_URL = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/;
|
||||
@@ -227,15 +232,17 @@ export function createRelay({ socket, cap, take, read, onSend, log = () => {} })
|
||||
// tokenPattern a RegExp the whole ANTHROPIC_AUTH_TOKEN must match, or null for no shape check
|
||||
// harnessModule async (name) -> the harness module (envNames, installRoots) or null; the
|
||||
// repository's packages/plugins/harness/<name> by default
|
||||
// home HOME, which no mount may reach; the Console user's by default
|
||||
// home HOME, which no mount may reach outside the stack's own code; the Console user's by default
|
||||
export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), devOwner = false, log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null, proxyPort = null, tokenPattern = null, harnessModule = repoHarnessModule, home = homedir() }) {
|
||||
if (typeof dataRoot !== "string" || !dataRoot.startsWith("/")) throw new TriageError("triage-no-data-root", "no data root");
|
||||
if (proxyPort !== null && !(Number.isInteger(proxyPort) && proxyPort > 0 && proxyPort <= 65535)) throw new TypeError("proxyPort must be a port number or null");
|
||||
if (tokenPattern !== null && !(tokenPattern instanceof RegExp)) throw new TypeError("tokenPattern must be a RegExp or null");
|
||||
if (typeof harnessModule !== "function") throw new TypeError("harnessModule must be a function");
|
||||
const tokenShape = tokenPattern && new RegExp(`^(?:${tokenPattern.source})$`, tokenPattern.flags.replace(/[gy]/g, ""));
|
||||
// What no mount source may lie in or around, besides the run directory and the fixed list.
|
||||
const tokenShape = tokenPattern && new RegExp(`^(?:${tokenPattern.source})$`, tokenPattern.flags.replace(/[gmy]/g, ""));
|
||||
// What no mount source may lie in or around, besides the run directory and the fixed list. HOME
|
||||
// does not refuse the stack's own code when the stack runs from under it (a copy or a worktree).
|
||||
const protectedPaths = [dataRoot, systemConfigDir(env), home];
|
||||
const codeRoot = REPO;
|
||||
const paths = triagePaths(dataRoot);
|
||||
const role = JSON.parse(readFileSync(join(roleDir, "triage.json"), "utf8"));
|
||||
const contract = readFileSync(join(roleDir, role.contract), "utf8");
|
||||
@@ -349,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, runDir: paths.agent, node });
|
||||
checkHostedRoute({ adapter: a.adapter, harnessMounts: a.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, runDir: paths.agent, node });
|
||||
} catch (e) {
|
||||
if (e?.code === "hosted-binds-refused") refuse(e.fence);
|
||||
throw e;
|
||||
@@ -385,10 +392,14 @@ 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, 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, 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}`);
|
||||
// Nothing of the refused start stays: the relay, its socket, the bundle and session.json go.
|
||||
relay?.close();
|
||||
relay = null;
|
||||
for (const f of ["relay.sock", "session.json", "bundle"]) rmSync(join(paths.agent, f), { recursive: true, force: true });
|
||||
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
|
||||
}
|
||||
const argv = hostedArgv(list, paths.agent, [node, RUNNER, paths.agent], { bwrap });
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { connect } from "node:net";
|
||||
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { Client } from "../../bus/src/client.mjs";
|
||||
import { REPO, RUNNER_FILES, checkHostedRoute, sandboxProblem } from "../../seat/src/sandbox.mjs";
|
||||
@@ -102,7 +102,7 @@ const REFUSED_TRIED = [
|
||||
"MOSAIC_POLICY_FILE", "MOSAIC_TOOLS_FILE", "MOSAIC_CONFIG", "MOSAIC_BUS_CONSOLE_SOCKET", "NODE_OPTIONS", "NODE_PATH", "LD_PRELOAD",
|
||||
"LD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES", "PYTHONPATH", "PYTHONSTARTUP", "PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK",
|
||||
"GITEA_TOKEN", "GH_TOKEN", "GIT_ASKPASS", "GIT_CONFIG_PARAMETERS", "VIKUNJA_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN",
|
||||
"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY",
|
||||
"ANTHROPIC_API_KEY", "CLAUDE_CODE_OAUTH_TOKEN", "OPENAI_API_KEY", "GLIBC_TUNABLES", "PI_CODING_AGENT_DIR", "XDG_CONFIG_HOME",
|
||||
];
|
||||
// The fake harness module: it declares the probe names and every refused one, so only the host's
|
||||
// own refusal stops those. Its one install root is <root>/install.
|
||||
@@ -217,12 +217,19 @@ test("fence 1: a harnessEnv name the host refuses is refused even when the harne
|
||||
for (const name of ["lower", "Mosaic_policy_file", "mosaic_policy_file", "FAKE_OK=x", "A=B", "FAKE_OK\0", " FAKE_OK", "fake_ok"]) {
|
||||
await refusedRoute(t, JSON.stringify(name), () => ({ harnessEnv: { [name]: "x" } }), (root) => ({ harnessModule: fakeModule([join(root, "install")], [...DECLARED, name]) }));
|
||||
}
|
||||
for (const name of ["GIT_DIR", "BASH_FUNC_x%%", "LD_AUDIT", "SHELLOPTS", "PS4", "IFS", "HTTPS_PROXY", "NODE_EXTRA_CA_CERTS", "PYTHONHOME", "MOSAIC_X"]) assert.equal(refusedHarnessName(name), true, name);
|
||||
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",
|
||||
]) assert.equal(refusedHarnessName(name), true, name);
|
||||
for (const name of ["FAKE_OK", "PI_MODEL", "TRIAGE_PROBE"]) assert.equal(refusedHarnessName(name), false, name);
|
||||
});
|
||||
|
||||
test("fence 1: values are strings of at most 4096 characters with no NUL, newline or carriage return, and at most 64 names", async (t) => {
|
||||
for (const [label, v] of [["newline", "x\ny"], ["nul", "x\0"], ["cr", "x\ry"], ["4097", "a".repeat(4097)], ["number", 5], ["null", null], ["object", {}], ["array", ["x"]]]) {
|
||||
test("fence 1: values are strings of at most 4096 characters with no control character or line separator, and at most 64 names", async (t) => {
|
||||
for (const [label, v] of [
|
||||
["newline", "x\ny"], ["nul", "x\0"], ["cr", "x\ry"], ["tab", "x\ty"], ["escape", "x\u001by"], ["del", "x\u007f"], ["c1 next line", "x\u0085y"],
|
||||
["line separator", "x\u2028y"], ["paragraph separator", "x\u2029y"], ["4097", "a".repeat(4097)], ["number", 5], ["null", null], ["object", {}], ["array", ["x"]],
|
||||
]) {
|
||||
await refusedRoute(t, label, () => ({ harnessEnv: { FAKE_OK: v } }));
|
||||
}
|
||||
const many = Object.fromEntries(Array.from({ length: 65 }, (_, i) => [`FAKE_N${i}`, "x"]));
|
||||
@@ -271,7 +278,7 @@ test("fence 2: route env holds only the proxy's two names, the base URL is http
|
||||
for (const extra of ["OTHER", "MOSAIC_CONFIG", "ANTHROPIC_API_KEY", "PATH", "anthropic_base_url"]) {
|
||||
await refusedRoute(t, `env ${extra}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", [extra]: "x" } }));
|
||||
}
|
||||
await refusedRoute(t, "token with a newline", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: "a\nb" } }));
|
||||
for (const token of ["a\nb", "a\u2028b", "a\u0000b", "a\u007fb"]) await refusedRoute(t, `token ${JSON.stringify(token)}`, () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:9", ANTHROPIC_AUTH_TOKEN: token } }));
|
||||
await refusedRoute(t, "env array", () => ({ env: ["ANTHROPIC_BASE_URL"] }));
|
||||
await admittedRoute(t, "port 65535", () => ({ env: { ANTHROPIC_BASE_URL: "http://127.0.0.1:65535" } }));
|
||||
// The host's port.
|
||||
@@ -345,6 +352,13 @@ test("fence 3: a mount dest that is or holds /tmp, the run directory, the relay
|
||||
writeFileSync(join(root, "install", "g"), "x");
|
||||
return { harnessMounts: [{ src: join(root, "install", "f"), dest: "/opt/x", why: "w" }, { src: join(root, "install", "g"), dest: "/opt/x", why: "w" }] };
|
||||
});
|
||||
for (const [label, a, b] of [["nested dest", "/opt/x", "/opt/x/f"], ["parent dest", "/opt/x/f", "/opt/x"]]) {
|
||||
await refusedRoute(t, label, (root) => {
|
||||
writeFileSync(join(root, "install", "f"), "x");
|
||||
writeFileSync(join(root, "install", "g"), "x");
|
||||
return { harnessMounts: [{ src: join(root, "install", "f"), dest: a, why: "w" }, { src: join(root, "install", "g"), dest: b, why: "w" }] };
|
||||
});
|
||||
}
|
||||
await admittedRoute(t, "dest /opt/x", withDest("/opt/x"));
|
||||
});
|
||||
|
||||
@@ -372,11 +386,64 @@ test("the shipped harness modules declare what their own env() and mounts() hand
|
||||
}));
|
||||
assert.deepEqual(keys.filter((k) => !isProviderVariable(k)).sort(), [...mod.envNames].sort(), name);
|
||||
const roots = mod.installRoots({ env: {} });
|
||||
const got = checkHostedRoute({ adapter: mod.adapter(), harnessMounts: mod.mounts({ env: {} }), installRoots: roots, protectedPaths: [join(dir, "data"), join(dir, "cfg"), join(dir, "home")], runDir: join(dir, "data", "triage", "agent") });
|
||||
const route = { adapter: mod.adapter(), harnessMounts: mod.mounts({ env: {} }), installRoots: roots, runDir: join(dir, "data", "triage", "agent") };
|
||||
const got = checkHostedRoute({ ...route, protectedPaths: [join(dir, "data"), join(dir, "cfg"), join(dir, "home")] });
|
||||
assert.equal(got.adapter.dest, mod.adapter(), name);
|
||||
// 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.throws(() => checkHostedRoute(underHome), (e) => e.fence === "adapter", name);
|
||||
}
|
||||
});
|
||||
|
||||
test("a host whose HOME holds the repository starts the shipped pi harness's own route; a source under HOME outside the repository is still refused", async (t) => {
|
||||
const pi = await import(new URL("../../plugins/harness/pi/index.mjs", import.meta.url).href);
|
||||
const home = dirname(REPO);
|
||||
const opts = { home, harnessModule: async (name) => (name === "pi" ? pi : null) };
|
||||
const piRoute = (root) => answer(root, { harness: "pi", adapter: pi.adapter(), harnessMounts: pi.mounts({ env: {} }), harnessEnv: { PI_MODEL: "m", PI_OFFLINE: "1" } });
|
||||
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")]) }));
|
||||
});
|
||||
|
||||
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) => {
|
||||
const root = scratch();
|
||||
mkdirSync(join(root, "install"), { recursive: true });
|
||||
writeFileSync(join(root, "outside.sh"), "exit 0\n");
|
||||
const logs = [];
|
||||
let checked = false;
|
||||
let swapped = false;
|
||||
const harnessModule = async (name) => (name === "fake" ? { envNames: DECLARED, installRoots: () => { checked = true; return [join(root, "install")]; } } : null);
|
||||
// The run id in session.json reads the clock after the first check: the adapter becomes a link
|
||||
// out of the install root then, so only hostedBinds' own check can see it.
|
||||
const now = () => {
|
||||
if (checked && !swapped) {
|
||||
swapped = true;
|
||||
rmSync(join(root, "install", "adapter.sh"));
|
||||
symlinkSync(join(root, "outside.sh"), join(root, "install", "adapter.sh"));
|
||||
}
|
||||
return new Date("2026-11-16T12:00:00.000Z");
|
||||
};
|
||||
const route = { admit: async () => answer(root) };
|
||||
const { h, dataRoot } = host(t, root, { route, bwrap: spy(root), log: (l) => logs.push(l), harnessModule, now });
|
||||
const agent = join(dataRoot, "triage", "agent");
|
||||
await assert.rejects(h.message("hello"), (e) => e.code === "triage-route-invalid" && e.message === "the model route's answer is not usable");
|
||||
assert.ok(swapped, "the swap happened between the checks");
|
||||
assert.ok(logs.includes("triage host: route refused at the binds: adapter"), logs.join(" | "));
|
||||
assert.equal(existsSync(join(root, "spawned")), false);
|
||||
assert.equal(h.running, false);
|
||||
for (const f of ["session.json", "relay.sock", "bundle"]) assert.equal(existsSync(join(agent, f)), false, f);
|
||||
const [owner, note, ...rest] = (await h.state()).transcript;
|
||||
assert.deepEqual([owner.from, note.from, note.in_reply_to, note.text, rest.length], ["owner", "host", owner.id, ROUTE_REFUSED, 0]);
|
||||
rmSync(join(root, "install", "adapter.sh"));
|
||||
writeFileSync(join(root, "install", "adapter.sh"), "exit 0\n");
|
||||
await h.message("again");
|
||||
await waitFor(() => existsSync(join(root, "spawned")));
|
||||
});
|
||||
|
||||
test("a read and a message that arrive together share one snapshot read", async (t) => {
|
||||
let reads = 0, release;
|
||||
const gate = new Promise((r) => { release = r; });
|
||||
|
||||
Reference in new issue
Block a user