From 13cf7160d715efce2e22b352affdd52ef7dfc76b Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Mon, 30 Nov 2026 00:46:35 +0800 Subject: [PATCH] Hide the home from harness shells except an allowlist Harness shells ran with `/` read-only and masked a fixed list of credential stores, so a secret in any other home directory (for example a relay's key files) stayed readable. Both the outer bwrap launch and the Codex math-worker permission profile now mask every home around an allowlist: - the launch's workspace, profile, executable and Lean lock; - PATH entries with the installation prefix of each bin directory, every hop of user-owned launcher symlinks and their node package trees; - Lean, cache, tool, retrieval and proof-environment roots the environment names, the default ~/.elan when ELAN_HOME is unset, and DEEPSCIENTIST_MATH_SANDBOX_READ_ROOTS; - a script launcher's #! interpreter; - symlink targets in the workspace and profile (.lake packages, git worktree metadata); - the new readableRoots session option, which solver sessions set to the application root and research tool directory. Credential stores stay masked inside allowed paths, and user-owned link targets outside the home are masked at their real paths. The isolation receipt records homeReadRoots. Co-Authored-By: Claude Opus 5.5 --- src/math/mathRuntimeEnvironment.ts | 1 + src/runtime/agentSession.ts | 3 + src/runtime/codexSession.ts | 13 +- src/runtime/harnessProcess.ts | 233 ++++++++++++++++++++++++++--- src/runtime/leanHealthCheck.ts | 2 +- src/solver/agentTeam.ts | 3 + src/solver/research.ts | 2 + src/solver/researchToolGuide.ts | 2 + tests/codexSession.test.ts | 16 +- tests/harnessProcess.test.ts | 80 ++++++++-- 10 files changed, 307 insertions(+), 48 deletions(-) diff --git a/src/math/mathRuntimeEnvironment.ts b/src/math/mathRuntimeEnvironment.ts index 1e5c43d4..74765b2e 100644 --- a/src/math/mathRuntimeEnvironment.ts +++ b/src/math/mathRuntimeEnvironment.ts @@ -39,6 +39,7 @@ const OPTIONAL_ENV_FILE_KEYS = new Set([ 'DEEPSCIENTIST_MATH_TOOLS_SHA256', 'DEEPSCIENTIST_MATH_PANTOGRAPH_MANIFEST', 'DEEPSCIENTIST_MATH_PANTOGRAPH_SHA256', + 'DEEPSCIENTIST_MATH_SANDBOX_READ_ROOTS', 'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy', 'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY', 'NO_PROXY', ]); diff --git a/src/runtime/agentSession.ts b/src/runtime/agentSession.ts index 3b1f342e..284b4a1b 100644 --- a/src/runtime/agentSession.ts +++ b/src/runtime/agentSession.ts @@ -56,6 +56,9 @@ export type MathAgentOptions = { onItem?: (phase: 'started' | 'completed', item: Json, context?: { turnId?: string }) => void; onItemUpdate?: (item: Json, context?: { turnId?: string }) => void; hiddenRoots?: readonly string[]; + /** Host paths the shells run or read besides the workspace and toolchain, such as the application's own tool + * entry point. The rest of the invoking user's home is hidden from isolated shells. */ + readableRoots?: readonly string[]; /** Hide present and future peer directories, then expose only this workspace below its direct parent. */ isolatedWorkspaceParent?: string; readIsolation?: { diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index ff6692a6..77a303fb 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -18,7 +18,7 @@ import { scheduleMathTimeout } from '../math/mathTimers'; import { assertMathAgentSkillsCurrent, assertMathAgentSkillsDiscovered } from './codexSkills'; import { planMathAgentSession } from './agentSessionPlan'; import { MathAgentToolDispatcher } from './agentTeamTools'; -import { confirmHarnessProcessStopped, hostCredentialRoots, prepareHarnessProcess, readHarnessProcessIdentity, +import { confirmHarnessProcessStopped, harnessReadRoots, hostPrivateRoots, prepareHarnessProcess, readHarnessProcessIdentity, type HarnessProcessIdentity } from './harnessProcess'; import { runHarnessLeanHealthCheck } from './leanHealthCheck'; import { NativeAgentControl, NativeAgentControlInputError, NATIVE_AGENT_CONTROL_REQUEST, nativeAgentControlModelCatalog } from './nativeAgentControl'; @@ -85,10 +85,12 @@ export const MATH_WORKER_PERMISSION_PROFILE = 'math-worker'; * Unix sockets are not path-filtered on Linux, so /run and /tmp, where host services (docker, the * session bus, Codex daemons) listen, are hidden. A thread keeps the policy it started with. * `hiddenRoots` are further directories the shells must not read, such as an application's own code. + * `privateRoots` hide the invoking user's home except the workspace and the toolchain the environment names; + * Codex does not reopen a `read` path below a `none` one, so the home is masked around those paths. */ export function mathWorkerPermissionConfig(workspace: string, hiddenRoots: readonly string[] = [], - credentialRoots: readonly string[] = hostCredentialRoots([workspace])): Json { - const hidden = ['/run', '/tmp', ...hiddenRoots, ...credentialRoots].filter(root => workspace !== root && !workspace.startsWith(`${root}/`)); + privateRoots: readonly string[] = hostPrivateRoots([workspace], harnessReadRoots(process.env, [workspace]))): Json { + const hidden = ['/run', '/tmp', ...hiddenRoots, ...privateRoots].filter(root => workspace !== root && !workspace.startsWith(`${root}/`)); return { default_permissions: MATH_WORKER_PERMISSION_PROFILE, [`permissions.${MATH_WORKER_PERMISSION_PROFILE}.filesystem`]: { @@ -875,8 +877,9 @@ export async function createCodexMathSession(options: MathAgentOptions): Promise model_reasoning_effort: options.effort, // The formalization sandbox is the OS boundary for isolated roles; every other shell runs the worker profile. ...(!isolated ? { ...mathWorkerPermissionConfig(options.workspace, options.hiddenRoots, - // Codex puts its arg0 helpers (apply_patch) under CODEX_HOME/tmp and on the shell PATH. - hostCredentialRoots([options.workspace, path.join(nativeProfile, 'tmp')])), + // Codex puts its arg0 helpers (apply_patch) under CODEX_HOME/tmp and on the shell PATH; they link to the launcher. + hostPrivateRoots([options.workspace, path.join(nativeProfile, 'tmp')], + harnessReadRoots(environment, [options.workspace], options.executable, options.readableRoots))), ...shellCredentialPolicy, ...shellTemporaryPolicy } : {}), ...providerSettings, }, diff --git a/src/runtime/harnessProcess.ts b/src/runtime/harnessProcess.ts index e5fd83f0..4995b357 100644 --- a/src/runtime/harnessProcess.ts +++ b/src/runtime/harnessProcess.ts @@ -72,51 +72,237 @@ export function confirmHarnessProcessStopped(identity: HarnessProcessIdentity): } catch { return { status: 'unconfirmed', reason: 'process-group-unavailable' }; } } -/** Credential stores under the invoking user's home. Harness shells can read `/`, so these are masked; - * native clients get their own profile through CODEX_HOME, CLAUDE_CONFIG_DIR and the XDG variables. */ +/** Credential stores under the invoking user's home. They stay masked even inside a home path the + * launch may read; native clients get their own profile through CODEX_HOME, CLAUDE_CONFIG_DIR and XDG. */ export const HOST_CREDENTIAL_PATHS = ['.ssh', '.gnupg', '.password-store', '.aws', '.azure', '.kube', '.docker', '.config', '.claude', '.claude.json', '.codex/auth.json', '.codex/config.toml', '.gemini', '.grok', '.copilot', '.cloudflared', - '.lark-cli', '.kaggle', '.netrc', '.git-credentials', '.npmrc', '.pypirc', '.local/state', '.local/share/opencode', + '.lark-cli', '.kaggle', '.netrc', '.git-credentials', '.npmrc', '.pypirc', '.cargo/credentials', '.cargo/credentials.toml', + '.local/state', '.local/share/opencode', '.local/share/keyrings', '.cache/huggingface/token', '.bash_history', '.zsh_history', '.python_history'] as const; +/** Extra read-only paths (path-list) a deployment grants harness shells inside a home. */ +export const HARNESS_READ_ROOTS_ENV = 'DEEPSCIENTIST_MATH_SANDBOX_READ_ROOTS'; +// Settings that name a toolchain, a pinned package cache or their data. File-valued settings grant their directory. +const READ_ROOT_DIRECTORIES = ['ELAN_HOME', 'LAKE_HOME', 'LEAN_SYSROOT', 'DEEPSCIENTIST_LEAN_EVAL_ROOT', + 'DEEPSCIENTIST_LEAN_EVAL_TOOLS_ROOT', 'DEEPSCIENTIST_MATH_RETRIEVAL_CORPUS'] as const; +const READ_ROOT_FILES = ['DEEPSCIENTIST_LEAN_EVAL_TOOL_MANIFEST', 'DEEPSCIENTIST_MATH_PANTOGRAPH_MANIFEST', + 'DEEPSCIENTIST_MATH_ENV_FILE'] as const; +const READ_ROOT_LISTS = ['PATH', 'LEAN_PATH', 'DEEPSCIENTIST_MATH_TRUSTED_CACHE_ROOTS', 'DEEPSCIENTIST_MATH_TRUSTED_ELAN_ROOTS', + HARNESS_READ_ROOTS_ENV] as const; +const READ_ROOT_DESCRIPTORS = ['DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT', 'DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT_SANDBOX'] as const; +const LINK_SCAN_DEPTH = 5, LINK_SCAN_ENTRIES = 20_000; + function hostHomes(): string[] { const homes = [os.homedir()]; try { homes.push(os.userInfo().homedir); } catch { /* no passwd entry */ } return homes; } -/** Existing canonical credential paths. A store that holds a path the launch needs (its workspace, - * profile or executable) is masked entry by entry around that path; a store inside one stays visible. - * Masking a directory hides its symlinks but not their targets, so a store's symlinked entries - * are masked at their real paths too. Nothing that contains a home is ever masked. */ -export function hostCredentialRoots(keep: readonly string[], homes: readonly string[] = hostHomes()): string[] { - const roots = new Set(); - const valid = homes.filter(home => home && path.isAbsolute(home) && path.resolve(home) !== '/'); - const seen = new Set(); - keep = keep.map(target => { try { return fs.realpathSync(target); } catch { return path.resolve(target); } }); +const validHomes = (homes: readonly string[]) => + [...new Set(homes.filter(home => home && path.isAbsolute(home) && path.resolve(home) !== '/').map(home => path.resolve(home)))]; +const realOrResolved = (target: string) => { try { return fs.realpathSync(target); } catch { return path.resolve(target); } }; + +/** The lexical path, its real path and every partial resolution, so a path stays reachable by each spelling. */ +function pathSpellings(target: string): string[] { + const resolved = path.resolve(target), spellings = new Set([resolved]); + const parts = resolved.split(path.sep).filter(Boolean); + for (let index = 1; index <= parts.length; index++) { + try { spellings.add(path.join(fs.realpathSync(path.sep + parts.slice(0, index).join(path.sep)), ...parts.slice(index))); } + catch { break; } + } + return [...spellings]; +} + +/** Each path a symlink chain passes through; a masked hop would break the chain even with its target visible. */ +function linkHops(target: string): string[] { + const hops = [path.resolve(target)]; + for (let index = 0; index < 40; index++) { + const current = hops.at(-1)!; + try { + if (!fs.lstatSync(current).isSymbolicLink()) break; + hops.push(path.resolve(path.dirname(current), fs.readlinkSync(current))); + } catch { break; } + } + return hops; +} + +/** A node package launcher needs its whole package tree, including sibling platform packages. */ +function packageTree(file: string): string | undefined { + const parts = file.split(path.sep), index = parts.lastIndexOf('node_modules'); + return index > 0 ? parts.slice(0, index + 1).join(path.sep) : undefined; +} + +/** The absolute interpreter a `#!` script names, if any. */ +function scriptInterpreter(file: string): string | undefined { + let descriptor: number | undefined; + try { + descriptor = fs.openSync(file, 'r'); + const head = Buffer.alloc(256), length = fs.readSync(descriptor, head, 0, head.length, 0); + const interpreter = /^#!\s*(\S+)/u.exec(head.subarray(0, length).toString('utf8'))?.[1]; + return interpreter && path.isAbsolute(interpreter) ? interpreter : undefined; + } catch { return undefined; } finally { if (descriptor !== undefined) fs.closeSync(descriptor); } +} + +/** Targets of symlinks in a launch directory, such as `.lake/packages` or a git worktree's metadata. */ +function linkedTargets(directory: string): string[] { + const targets: string[] = []; + let budget = LINK_SCAN_ENTRIES; + const visit = (current: string, depth: number) => { + let entries: fs.Dirent[]; + try { entries = fs.readdirSync(current, { withFileTypes: true }); } catch { return; } + for (const entry of entries) { + if (--budget < 0) return; + const child = path.join(current, entry.name); + if (entry.isSymbolicLink()) { + try { const real = fs.realpathSync(child); if (!isMathPathWithin(directory, real)) targets.push(real); } catch { /* dangling */ } + } else if (entry.isDirectory() && depth < LINK_SCAN_DEPTH && !['.git', '.scratch', 'node_modules'].includes(entry.name)) { + visit(child, depth + 1); + } else if (entry.isFile() && entry.name === '.git' && depth === 0) { + // A git worktree names its metadata directory; that directory names the shared repository. + try { + const gitdir = path.resolve(current, /^gitdir: (.+)$/mu.exec(fs.readFileSync(child, 'utf8'))![1]!.trim()); + targets.push(gitdir); + const common = fs.readFileSync(path.join(gitdir, 'commondir'), 'utf8').trim(); + targets.push(path.resolve(gitdir, common)); + } catch { /* not a worktree link */ } + } + } + }; + visit(directory, 0); + return targets; +} + +/** + * Home paths a harness launch may read: its PATH (with the installation prefix of each `bin`), the Lean, + * cache and tool roots its environment names, the launcher's package and the targets of symlinks in its + * workspace and profile. Everything else in a home is masked. + */ +export function harnessReadRoots(environment: NodeJS.ProcessEnv, directories: readonly string[] = [], + executable?: string, extra: readonly string[] = [], homes: readonly string[] = hostHomes()): string[] { + const valid = validHomes(homes), roots = new Set(); + const add = (value: string | undefined) => { if (value && path.isAbsolute(value)) roots.add(path.resolve(value)); }; + for (const root of extra) add(root); + for (const key of READ_ROOT_DIRECTORIES) add(environment[key]); + // Lean tools fall back to the default elan installation. + if (!environment.ELAN_HOME) for (const home of valid) add(path.join(home, '.elan')); + for (const key of READ_ROOT_FILES) if (environment[key] && path.isAbsolute(environment[key]!)) add(path.dirname(environment[key]!)); + // A home and its `.local` are never an installation prefix, by any spelling or storage copy. + const personal = new Set(valid.flatMap(home => [home, path.join(home, '.local')].flatMap(pathSpellings))); + const homeNames = new Set(valid.map(home => path.basename(home))); + const personalPrefix = (prefix: string) => personal.has(prefix) || path.basename(prefix) === '.local' || + homeNames.has(path.basename(prefix)); + // `prefix/bin` and `prefix/bin/` come with `prefix/lib` and `prefix/share`. + const addProgramDirectory = (directory: string) => { + add(directory); + for (const [bin, prefix] of [[directory, path.dirname(directory)], [path.dirname(directory), path.dirname(path.dirname(directory))]]) + if (path.basename(bin) === 'bin' && prefix !== '/' && !personalPrefix(prefix)) { add(prefix); break; } + }; + const uid = process.getuid?.(); + for (const key of READ_ROOT_LISTS) for (const entry of (environment[key] ?? '').split(path.delimiter)) { + if (!entry || !path.isAbsolute(entry)) continue; + if (key !== 'PATH') { add(entry); continue; } + addProgramDirectory(path.resolve(entry)); + // A user's own program directory links to installations elsewhere; system directories are already readable. + try { if (uid !== undefined && fs.statSync(entry).uid !== uid) continue; } catch { continue; } + let names: string[] = []; + try { names = fs.readdirSync(entry); } catch { /* absent */ } + for (const name of names) { + try { + const link = path.join(entry, name); + if (!fs.lstatSync(link).isSymbolicLink()) continue; + const real = fs.realpathSync(link), tree = packageTree(real); + for (const hop of linkHops(link)) add(hop); + if (tree) add(tree); else addProgramDirectory(path.dirname(real)); + } catch { /* dangling */ } + } + } + // Math-tool wrappers run programs installed beside their runtime directory. + const tools = environment.DEEPSCIENTIST_MATH_TOOLS_ROOT; + if (tools && path.isAbsolute(tools)) { add(tools); add(path.dirname(path.resolve(tools))); } + for (const key of READ_ROOT_DESCRIPTORS) { + try { + const descriptor = JSON.parse(environment[key] ?? '') as Record; + for (const field of ['rootPath', 'leaseSocket']) if (typeof descriptor[field] === 'string') add(descriptor[field]); + } catch { /* absent or not a descriptor */ } + } + const addProgram = (program: string) => { + const real = realOrResolved(program); + for (const hop of linkHops(program)) add(hop); + add(real); add(packageTree(real)); + return real; + }; + if (executable && path.isAbsolute(executable)) { + // A script launcher needs its `#!` interpreter; `/usr/bin/env` finds one on PATH, which is already readable. + const interpreter = scriptInterpreter(addProgram(executable)); + if (interpreter) addProgram(interpreter); + } + for (const directory of directories) for (const target of linkedTargets(directory)) add(target); + return [...roots].sort(); +} + +/** + * Masks everything under `starts` except paths that hold or lie inside `preserve`. A directory that holds + * a preserved path is masked entry by entry around it. Masking a directory hides its symlinks but not their + * targets, so a masked directory's symlinked entries are masked at their real paths too. `/` is never + * masked. The credential layer never masks a path containing a home; the home layer masks a link target + * outside the homes only when the invoking user owns it, so a link to a system program stays usable. + */ +function maskAround(starts: readonly string[], preserve: readonly string[], homes: readonly string[], homeLayer: boolean): string[] { + const roots = new Set(), seen = new Set(), uid = process.getuid?.(); const entries = (directory: string) => { try { return fs.readdirSync(directory); } catch { return []; } }; - const cover = (real: string) => { + const cover = (real: string, linked: boolean) => { if (seen.has(real)) return; seen.add(real); - if (real === '/' || keep.some(target => isMathPathWithin(target, real)) || valid.some(home => isMathPathWithin(real, home))) return; - if (keep.some(target => isMathPathWithin(real, target))) { - for (const entry of entries(real)) try { cover(fs.realpathSync(path.join(real, entry))); } catch { /* vanished */ } + if (real === '/' || preserve.some(target => isMathPathWithin(target, real))) return; + if (!homeLayer && homes.some(home => isMathPathWithin(real, home))) return; + if (homeLayer && linked && !homes.some(home => isMathPathWithin(home, real))) { + try { if (uid !== undefined && fs.statSync(real).uid !== uid) return; } catch { return; } + } + if (preserve.some(target => isMathPathWithin(real, target))) { + for (const entry of entries(real)) { + const child = path.join(real, entry); + try { cover(fs.realpathSync(child), linked || fs.lstatSync(child).isSymbolicLink()); } catch { /* vanished */ } + } return; } roots.add(real); for (const entry of entries(real)) { const link = path.join(real, entry); - try { if (fs.lstatSync(link).isSymbolicLink()) cover(fs.realpathSync(link)); } catch { /* dangling */ } + try { if (fs.lstatSync(link).isSymbolicLink()) cover(fs.realpathSync(link), true); } catch { /* dangling */ } } }; - for (const home of valid) - for (const name of HOST_CREDENTIAL_PATHS) try { cover(fs.realpathSync(path.join(home, name))); } catch { /* absent */ } - return [...roots].sort(); + for (const start of starts) try { cover(fs.realpathSync(start), false); } catch { /* absent */ } + return [...roots]; +} + +const outermost = (roots: Iterable) => { + const unique = [...new Set(roots)]; + return unique.filter(root => !unique.some(parent => parent !== root && isMathPathWithin(parent, root))).sort(); +}; + +/** Existing canonical credential paths. A store that holds a path the launch needs (its workspace, + * profile or executable) is masked entry by entry around that path; a store inside one stays visible. + * Nothing that contains a home is ever masked. */ +export function hostCredentialRoots(keep: readonly string[], homes: readonly string[] = hostHomes()): string[] { + const valid = validHomes(homes); + const preserve = keep.flatMap(pathSpellings); + return outermost(maskAround(valid.flatMap(home => HOST_CREDENTIAL_PATHS.map(name => path.join(home, name))), + preserve, valid, false)); +} + +/** + * Home allowlist. Every home is masked except paths the launch writes (`keep`) or reads (`read`), so a + * secret in an unlisted directory stays unreadable. Credential stores are masked even inside `read`. + */ +export function hostPrivateRoots(keep: readonly string[], read: readonly string[], homes: readonly string[] = hostHomes()): string[] { + const valid = validHomes(homes); + const preserve = [...keep, ...read].flatMap(pathSpellings); + return outermost([...maskAround(valid, preserve, valid, true), ...hostCredentialRoots(keep, valid)]); } /** Native tool permissions do not constrain arbitrary shell children. Both CLI harnesses use this OS contract. */ export function prepareHarnessProcess(options: Pick, + 'hiddenRoots' | 'readableRoots' | 'isolatedWorkspaceParent' | 'readOnlyWorkspace'>, executable: string, arguments_: readonly string[], infoDescriptor?: number) { if (process.platform !== 'linux' || !fs.existsSync('/usr/bin/bwrap')) throw new Error('math_harness_process_isolation_unavailable'); @@ -160,7 +346,9 @@ export function prepareHarnessProcess(options: Pick { try { return fs.realpathSync(executable); } catch { return executable; } })()] : []; - for (const root of hostCredentialRoots([options.workspace, options.profile, ...launched, ...(lock ? [lock] : [])])) + // Home allowlist: only the launch's own directories and the toolchain its environment names stay readable. + const readable = harnessReadRoots(env, [options.workspace, options.profile], executable, options.readableRoots); + for (const root of hostPrivateRoots([options.workspace, options.profile, ...launched, ...(lock ? [lock] : [])], readable)) if (!hidden.some(parent => isMathPathWithin(parent, root))) hidden.push(root); const masks = hidden.filter(root => !hidden.some(parent => parent !== root && isMathPathWithin(parent, root))); const args = ['--die-with-parent', '--unshare-pid', '--unshare-ipc', '--new-session', '--cap-drop', 'ALL', @@ -190,5 +378,6 @@ export function prepareHarnessProcess(options: Pick }; } diff --git a/src/runtime/leanHealthCheck.ts b/src/runtime/leanHealthCheck.ts index 5bcefc6c..ccc241e7 100644 --- a/src/runtime/leanHealthCheck.ts +++ b/src/runtime/leanHealthCheck.ts @@ -17,7 +17,7 @@ export class LeanEnvironmentHealthCheckError extends Error { /** A disposable process uses the native writer's exact OS isolation inputs, without starting its RPC or model. */ export async function runHarnessLeanHealthCheck(options: Pick): Promise { + 'workspace' | 'profile' | 'environment' | 'hiddenRoots' | 'readableRoots' | 'isolatedWorkspaceParent' | 'isolateProcess' | 'proofProjectRoot' | 'leanHealthCheck' | 'signal'>): Promise { if (!options.leanHealthCheck) return undefined; if (!options.isolateProcess) throw new Error('math_lean_health_check_requires_process_isolation'); const launch = prepareHarnessProcess(options, options.leanHealthCheck.executable, options.leanHealthCheck.arguments); diff --git a/src/solver/agentTeam.ts b/src/solver/agentTeam.ts index 85b6fecd..068bf037 100644 --- a/src/solver/agentTeam.ts +++ b/src/solver/agentTeam.ts @@ -43,6 +43,7 @@ import { AgentTeamNativeControl, nativeSpawnHistory, nativeTeamAssignmentMessage import { IncrementalHelperRejection, landVerifiedHelpers } from './incrementalHelpers'; import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; import { portfolioRouteIdSchema, type RetiredRoute, type routeRetirementSchema } from './routeControl'; +import { researchToolRoots } from './researchToolGuide'; type LiveWorker = { session?: MathAgentSession; task: Promise; abort: AbortController; routeAbort: AbortController; admittedTurnId?: string; runSettled?: boolean }; @@ -533,6 +534,7 @@ export class AgentResearchTeam { skills: [access.researchSkill!], tools: this.tools(worker.id), nativeAgentControl: this.nativeAgentControlOptions(worker.id), hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), this.directory, state.worktree, git(state.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir'])], + readableRoots: researchToolRoots(this.input.root, this.input.modules.M4.tools), isolatedWorkspaceParent: path.dirname(worker.worktree), isolateProcess: true, instructions: context.instructions, signal: this.input.signal, onUsage: () => { throw new Error('math_team_native_idle_usage'); } }).catch(error => { @@ -931,6 +933,7 @@ export class AgentResearchTeam { nativeAgentControl: nativeOptions, hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), this.directory, state.worktree, git(state.worktree, ['rev-parse', '--path-format=absolute', '--git-common-dir'])], + readableRoots: researchToolRoots(this.input.root, this.input.modules.M4.tools), isolatedWorkspaceParent: path.dirname(worker.worktree), isolateProcess: true, instructions: context.instructions, signal, ...turnTiming, diff --git a/src/solver/research.ts b/src/solver/research.ts index 86bd502f..178db4bc 100644 --- a/src/solver/research.ts +++ b/src/solver/research.ts @@ -45,6 +45,7 @@ import { createSkillProofLifecycle } from './skillProofLifecycle'; import { createSoftSlice, softSliceSettings, type SoftSliceSettings } from './softSlice'; import { materializeResearchToolHelp } from './researchToolHelp'; import { assertActiveResearchState } from './researchRetirement'; +import { researchToolRoots } from './researchToolGuide'; const interruptGraceMs = 10_000; const nonToolItems = new Set(['reasoning', 'agentMessage', 'userMessage', 'contextCompaction']); @@ -430,6 +431,7 @@ export async function runResearchLead(input: { ...(team ? { leanHealthCheck: { executable: process.execPath, arguments: [path.join(input.root, 'out/main/check-lean.js'), '--workspace', path.join(worker.worktree, state.problem.projectRelative), '--health', '--timeout-seconds', '0'] } } : {}), hiddenRoots: [prepareTacticBatteryFailureCacheRoot(), ...(team?.hiddenRoots ?? [])], + readableRoots: researchToolRoots(input.root, modules.M4.tools), proofProjectRoot: path.join(worker.worktree, state.problem.projectRelative), completedOutput: singleHandoff.output, workspace, environment: { ...access.environment, ...access.harnessEnvironment, diff --git a/src/solver/researchToolGuide.ts b/src/solver/researchToolGuide.ts index 58050380..e978178a 100644 --- a/src/solver/researchToolGuide.ts +++ b/src/solver/researchToolGuide.ts @@ -7,6 +7,8 @@ import { ResearchToolHelpBuilder } from './researchToolHelp'; const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'"; export const researchToolCommand = (root: string, tools?: string) => `bun ${quote(tools ?? path.join(root, 'bin/math.ts'))}`; +/** What an isolated shell must read to run {@link researchToolCommand}. */ +export const researchToolRoots = (root: string, tools?: string) => [root, ...(tools ? [path.dirname(path.resolve(root, tools))] : [])]; export const longCommandGuidance = 'For a long calculation, record the inputs, print progress and save completed batches in .scratch/tmp. Use unbuffered output for Python (python3 -u). ' + diff --git a/tests/codexSession.test.ts b/tests/codexSession.test.ts index c163bed9..28dcfb93 100644 --- a/tests/codexSession.test.ts +++ b/tests/codexSession.test.ts @@ -433,17 +433,19 @@ readline.createInterface({ input: process.stdin }).on('line', line => { .toEqual({ '/': 'read', '/work/run/a': 'write', '/run': 'none', '/tmp': 'none', '/opt/app': 'none' }); }); - it('denies host credential stores to worker shells by default', () => { + it('denies the home outside its PATH and toolchain to worker shells by default', () => { const home = fs.realpathSync(fs.mkdtempSync(path.join(root, 'home-'))); - fs.mkdirSync(path.join(home, '.codex/packages'), { recursive: true }); + for (const directory of ['.codex/packages', '.ssh', '.local/bin', 'services']) fs.mkdirSync(path.join(home, directory), { recursive: true }); fs.writeFileSync(path.join(home, '.codex/auth.json'), '{}'); - fs.mkdirSync(path.join(home, '.ssh')); - vi.stubEnv('HOME', home); + vi.stubEnv('HOME', home); vi.stubEnv('PATH', `${path.join(home, '.local/bin')}:${process.env.PATH}`); try { const filesystem = mathWorkerPermissionConfig(path.join(root, 'work'))['permissions.math-worker.filesystem'] as Record; - expect(filesystem).toMatchObject({ [path.join(home, '.codex/auth.json')]: 'none', [path.join(home, '.ssh')]: 'none' }); - expect(filesystem).not.toHaveProperty(path.join(home, '.codex')); - expect(filesystem).not.toHaveProperty(path.join(home, '.codex/packages')); + // Codex does not reopen a read path below a denied one, so the home is denied entry by entry around PATH. + expect(filesystem).toMatchObject({ [path.join(home, '.codex')]: 'none', [path.join(home, '.ssh')]: 'none', + [path.join(home, 'services')]: 'none' }); + expect(filesystem).not.toHaveProperty(home); + expect(filesystem).not.toHaveProperty(path.join(home, '.local')); + expect(filesystem).not.toHaveProperty(path.join(home, '.local/bin')); } finally { vi.unstubAllEnvs(); } }); diff --git a/tests/harnessProcess.test.ts b/tests/harnessProcess.test.ts index 674128f6..0bf6fbea 100644 --- a/tests/harnessProcess.test.ts +++ b/tests/harnessProcess.test.ts @@ -3,7 +3,8 @@ import path from 'node:path'; import { spawn, spawnSync } from 'node:child_process'; import { fileURLToPath } from 'node:url'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { confirmHarnessProcessStopped, hostCredentialRoots, prepareHarnessProcess, +import { confirmHarnessProcessStopped, HARNESS_READ_ROOTS_ENV, harnessReadRoots, hostCredentialRoots, hostPrivateRoots, + prepareHarnessProcess, type HarnessProcessIdentity } from '../src/runtime/harnessProcess'; function processIdentity(pid: number): HarnessProcessIdentity { @@ -67,31 +68,84 @@ describe('shared native harness process isolation', () => { expect(hostCredentialRoots([], ['/', '', 'relative'])).toEqual([]); }); - it('hides host credential stores from shell children without hiding host toolchains', () => { - const home = path.join(root, 'home'), linked = path.join(outside, 'linked-store'); - for (const directory of ['.config/app', '.codex/packages', '.ssh']) fs.mkdirSync(path.join(home, directory), { recursive: true }); + it('hides unlisted home files from shell children while its PATH, toolchain and launch roots stay readable', () => { + const home = path.join(root, 'home'), linked = path.join(outside, 'linked-store'), app = path.join(home, 'app'); + for (const directory of ['.config/app', '.codex/packages', '.ssh', '.elan/bin', '.local/bin', 'services/relay', 'app']) + fs.mkdirSync(path.join(home, directory), { recursive: true }); fs.mkdirSync(linked); fs.writeFileSync(path.join(linked, 'token'), 'linked secret'); fs.symlinkSync(linked, path.join(home, '.config/linked')); - fs.writeFileSync(path.join(home, '.config/app/token'), 'config secret'); - fs.writeFileSync(path.join(home, '.codex/auth.json'), 'codex secret'); - fs.writeFileSync(path.join(home, '.codex/packages/tool'), 'toolchain'); - fs.writeFileSync(path.join(home, '.ssh/id'), 'ssh secret'); + const secrets = { '.config/app/token': 'config secret', '.codex/auth.json': 'codex secret', '.codex/packages/tool': 'unlisted', + '.ssh/id': 'ssh secret', 'services/relay/credentials.txt': 'relay secret' }; + for (const [file, text] of Object.entries(secrets)) fs.writeFileSync(path.join(home, file), text); + const visible = { '.elan/bin/lean': 'elan', '.local/bin/tool': 'path tool', 'app/main.js': 'app' }; + for (const [file, text] of Object.entries(visible)) fs.writeFileSync(path.join(home, file), text); vi.stubEnv('HOME', home); try { - const result = run(`const fs=require('fs'), cp=require('child_process'); - for (const file of ${JSON.stringify([path.join(home, '.config/app/token'), path.join(linked, 'token'), - path.join(home, '.codex/auth.json'), path.join(home, '.ssh/id')])}) { + const environment = { ...process.env, PATH: `${path.join(home, '.local/bin')}:${process.env.PATH}`, ELAN_HOME: '' }; + const launch = prepareHarnessProcess({ workspace, profile, environment, readableRoots: [app] }, process.execPath, ['-e', + `const fs=require('fs'), cp=require('child_process'); + for (const file of ${JSON.stringify([...Object.keys(secrets).map(file => path.join(home, file)), path.join(linked, 'token')])}) { let text=''; try { text=fs.readFileSync(file,'utf8'); } catch(e) { if(e.code!=='ENOENT'&&e.code!=='EACCES') throw e; } if(text) process.exit(7); if(cp.spawnSync('/bin/cat',[file]).stdout.length) process.exit(8); } - if(fs.readFileSync(${JSON.stringify(path.join(home, '.codex/packages/tool'))},'utf8')!=='toolchain') process.exit(9);`); + for (const [file, text] of ${JSON.stringify(Object.entries(visible).map(([file, text]) => [path.join(home, file), text]))}) + if(fs.readFileSync(file,'utf8')!==text) process.exit(9);`]); + const result = spawnSync(launch.command, launch.args, { env: launch.env, encoding: 'utf8', timeout: 10_000 }); expect(result.status, result.stderr).toBe(0); - expect(result.launch.isolationReceipt.hiddenRoots).toEqual(expect.arrayContaining([path.join(home, '.config'), linked])); + expect(launch.isolationReceipt.hiddenRoots).toEqual(expect.arrayContaining([path.join(home, '.config'), + path.join(home, '.codex'), path.join(home, 'services'), linked])); + expect(launch.isolationReceipt.homeReadRoots).toEqual(expect.arrayContaining([app, path.join(home, '.elan'), path.join(home, '.local/bin')])); } finally { vi.unstubAllEnvs(); } expect(fs.readFileSync(path.join(home, '.codex/auth.json'), 'utf8')).toBe('codex secret'); }); + it('derives home read roots from the launch environment, executable and workspace links', () => { + const home = path.join(root, 'home'), bin = path.join(home, '.local/bin'); + const release = path.join(home, '.codex/packages/releases/1/bin'), current = path.join(home, '.codex/packages/current'); + const npm = path.join(home, '.npm-global/lib/node_modules'), cache = path.join(home, 'mathlib-cache'); + const gitdir = path.join(home, 'repo/.git/worktrees/work'); + for (const directory of [bin, release, path.join(npm, '@scope/cli'), path.join(root, 'opt/tool/bin'), cache, gitdir, + path.join(workspace, '.lake/packages')]) fs.mkdirSync(directory, { recursive: true }); + fs.writeFileSync(path.join(release, 'codex'), ''); fs.writeFileSync(path.join(npm, '@scope/cli/cli.js'), ''); + fs.symlinkSync('releases/1', current); + fs.symlinkSync(path.join(current, 'bin/codex'), path.join(bin, 'codex')); + fs.symlinkSync(path.join(npm, '@scope/cli/cli.js'), path.join(bin, 'cli')); + fs.symlinkSync(cache, path.join(workspace, '.lake/packages/mathlib')); + fs.writeFileSync(path.join(workspace, '.git'), `gitdir: ${gitdir}\n`); fs.writeFileSync(path.join(gitdir, 'commondir'), '../..\n'); + const roots = harnessReadRoots({ + PATH: `${bin}:${path.join(root, 'opt/tool/bin')}:/usr/bin`, LEAN_PATH: path.join(home, 'lean-path'), + DEEPSCIENTIST_MATH_ENV_FILE: path.join(root, 'conf/math.env'), [HARNESS_READ_ROOTS_ENV]: `${path.join(home, 'granted')}:relative`, + DEEPSCIENTIST_MATH_PROOF_ENVIRONMENT: JSON.stringify({ rootPath: path.join(home, 'proof'), leaseSocket: path.join(home, 'lease.sock') }), + DEEPSCIENTIST_MATH_TOOLS_ROOT: path.join(root, 'tools/runtime'), + }, [workspace], path.join(bin, 'codex'), [path.join(home, 'app')], [home]); + expect(roots).toEqual(expect.arrayContaining([bin, path.join(bin, 'codex'), path.join(current, 'bin/codex'), release, + path.join(home, '.codex/packages/releases/1'), npm, path.join(root, 'opt/tool/bin'), path.join(root, 'opt/tool'), + path.join(home, 'lean-path'), path.join(root, 'conf'), path.join(home, 'granted'), path.join(home, 'proof'), + path.join(home, 'lease.sock'), path.join(root, 'tools/runtime'), path.join(root, 'tools'), path.join(home, '.elan'), + path.join(home, 'app'), cache, gitdir, path.join(home, 'repo/.git')])); + // Neither a home nor its `.local` counts as an installation prefix. + for (const personal of [home, path.join(home, '.local'), '/', 'relative']) expect(roots).not.toContain(personal); + expect(harnessReadRoots({ ELAN_HOME: path.join(root, 'elan') }, [], undefined, [], [home])).toEqual([path.join(root, 'elan')]); + // A script launcher brings its interpreter. + const node = path.join(home, '.local/node-v1/bin/node'), script = path.join(outside, 'native'); + fs.mkdirSync(path.dirname(node), { recursive: true }); fs.writeFileSync(node, ''); + fs.writeFileSync(script, `#!${node}\n`, { mode: 0o700 }); + expect(harnessReadRoots({ ELAN_HOME: path.join(root, 'elan') }, [], script, [], [home])).toEqual([path.join(root, 'elan'), node, script].sort()); + }); + + it('masks a home around its launch and read roots, following user-owned links only', () => { + const home = path.join(root, 'home'), store = path.join(outside, 'store'); + for (const directory of ['work', 'tools/bin', 'notes', '.ssh', '.config/tool']) fs.mkdirSync(path.join(home, directory), { recursive: true }); + fs.writeFileSync(path.join(home, 'tools/secret.txt'), 'secret'); fs.mkdirSync(store); + fs.symlinkSync(store, path.join(home, 'link')); fs.symlinkSync('/usr/bin', path.join(home, 'system')); + expect(hostPrivateRoots([path.join(home, 'work')], [path.join(home, 'tools/bin'), path.join(home, '.config/tool')], [home])) + .toEqual([path.join(home, '.config'), path.join(home, '.ssh'), path.join(home, 'notes'), path.join(home, 'tools/secret.txt'), store].sort()); + expect(hostPrivateRoots([], [], [home])).toEqual([home, store].sort()); + // A launch that writes the whole home keeps it. + expect(hostPrivateRoots([home], [], [home])).toEqual([]); + }); + it('masks credential stores around a workspace that lives inside one', () => { const home = path.join(root, 'home'); workspace = path.join(home, '.config/work');