From 8f306912f40096f8110aa36b9fdadb358403afc3 Mon Sep 17 00:00:00 2001 From: Zhenhao Liu <176368005+LikC1606@users.noreply.github.com> Date: Sun, 29 Nov 2026 21:19:54 +0800 Subject: [PATCH] Hide host credential files from sandboxed harness shells Harness shells read `/`: the outer bwrap ro-binds it and the Codex math-worker profile grants `/`=read. Both masked only /run, /tmp and hidden roots, so a model-run shell could read ~/.codex/auth.json, ~/.config, ~/.claude, ~/.ssh and similar stores. hostCredentialRoots() resolves a fixed list of credential stores under the user's home to real paths, also masks the real targets of symlinked entries, masks a store entry by entry when it holds a path the launch needs, and never masks an ancestor of a home. prepareHarnessProcess adds these roots to its masks; mathWorkerPermissionConfig marks them `none`. Codex keeps CODEX_HOME/tmp visible because its apply_patch helper lives there and is on the shell PATH. Toolchains under home stay readable. Co-Authored-By: Claude Opus 5.5 --- src/runtime/codexSession.ts | 12 +++++--- src/runtime/harnessProcess.ts | 48 ++++++++++++++++++++++++++++- tests/codexSession.test.ts | 22 +++++++++++--- tests/harnessProcess.test.ts | 57 ++++++++++++++++++++++++++++++++++- 4 files changed, 129 insertions(+), 10 deletions(-) diff --git a/src/runtime/codexSession.ts b/src/runtime/codexSession.ts index 4b84bdfc..ff6692a6 100644 --- a/src/runtime/codexSession.ts +++ b/src/runtime/codexSession.ts @@ -18,7 +18,8 @@ import { scheduleMathTimeout } from '../math/mathTimers'; import { assertMathAgentSkillsCurrent, assertMathAgentSkillsDiscovered } from './codexSkills'; import { planMathAgentSession } from './agentSessionPlan'; import { MathAgentToolDispatcher } from './agentTeamTools'; -import { confirmHarnessProcessStopped, prepareHarnessProcess, readHarnessProcessIdentity, type HarnessProcessIdentity } from './harnessProcess'; +import { confirmHarnessProcessStopped, hostCredentialRoots, prepareHarnessProcess, readHarnessProcessIdentity, + type HarnessProcessIdentity } from './harnessProcess'; import { runHarnessLeanHealthCheck } from './leanHealthCheck'; import { NativeAgentControl, NativeAgentControlInputError, NATIVE_AGENT_CONTROL_REQUEST, nativeAgentControlModelCatalog } from './nativeAgentControl'; import { CODEX_FAILURE_CODES, HTTP_FAILURE_CODES, safeFailureReason, safeHttpStatusCode, @@ -85,8 +86,9 @@ export const MATH_WORKER_PERMISSION_PROFILE = 'math-worker'; * 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. */ -export function mathWorkerPermissionConfig(workspace: string, hiddenRoots: readonly string[] = []): Json { - const hidden = ['/run', '/tmp', ...hiddenRoots].filter(root => workspace !== root && !workspace.startsWith(`${root}/`)); +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}/`)); return { default_permissions: MATH_WORKER_PERMISSION_PROFILE, [`permissions.${MATH_WORKER_PERMISSION_PROFILE}.filesystem`]: { @@ -872,7 +874,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), + ...(!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')])), ...shellCredentialPolicy, ...shellTemporaryPolicy } : {}), ...providerSettings, }, diff --git a/src/runtime/harnessProcess.ts b/src/runtime/harnessProcess.ts index aae3dcb4..e5fd83f0 100644 --- a/src/runtime/harnessProcess.ts +++ b/src/runtime/harnessProcess.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import os from 'node:os'; import path from 'node:path'; import { assertMathCanonicalPath, isMathPathWithin } from '../math/paths'; import type { MathAgentOptions } from './agentSession'; @@ -71,6 +72,48 @@ 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. */ +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', + '.local/share/keyrings', '.cache/huggingface/token', '.bash_history', '.zsh_history', '.python_history'] as const; + +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 entries = (directory: string) => { try { return fs.readdirSync(directory); } catch { return []; } }; + const cover = (real: string) => { + 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 */ } + 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 */ } + } + }; + 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(); +} + /** Native tool permissions do not constrain arbitrary shell children. Both CLI harnesses use this OS contract. */ export function prepareHarnessProcess(options: Pick, @@ -115,6 +158,10 @@ export function prepareHarnessProcess(options: Pick isMathPathWithin(parent, mask))) hidden.push(mask); } if (workspaceParent) hidden.push(workspaceParent); + const lock = env.DEEPSCIENTIST_MATH_LEAN_LOCK; + const launched = path.isAbsolute(executable) ? [(() => { try { return fs.realpathSync(executable); } catch { return executable; } })()] : []; + for (const root of hostCredentialRoots([options.workspace, options.profile, ...launched, ...(lock ? [lock] : [])])) + 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', '--ro-bind', '/', '/', '--proc', '/proc', '--dev', '/dev']; @@ -133,7 +180,6 @@ export function prepareHarnessProcess(options: Pick isMathPathWithin(root, lock))) diff --git a/tests/codexSession.test.ts b/tests/codexSession.test.ts index bfc04115..c163bed9 100644 --- a/tests/codexSession.test.ts +++ b/tests/codexSession.test.ts @@ -423,16 +423,30 @@ readline.createInterface({ input: process.stdin }).on('line', line => { }); it('hides host socket roots unless they hold the workspace', () => { - expect(mathWorkerPermissionConfig('/home/user/work')['permissions.math-worker.filesystem']) + expect(mathWorkerPermissionConfig('/home/user/work', [], [])['permissions.math-worker.filesystem']) .toEqual({ '/': 'read', '/home/user/work': 'write', '/run': 'none', '/tmp': 'none' }); - expect(mathWorkerPermissionConfig('/tmp/work')['permissions.math-worker.filesystem']) + expect(mathWorkerPermissionConfig('/tmp/work', [], [])['permissions.math-worker.filesystem']) .toEqual({ '/': 'read', '/tmp/work': 'write', '/run': 'none' }); - expect(mathWorkerPermissionConfig('/tmpfs/work')['permissions.math-worker.filesystem']) + expect(mathWorkerPermissionConfig('/tmpfs/work', [], [])['permissions.math-worker.filesystem']) .toMatchObject({ '/tmp': 'none' }); - expect(mathWorkerPermissionConfig('/work/run/a', ['/opt/app', '/work'])['permissions.math-worker.filesystem']) + expect(mathWorkerPermissionConfig('/work/run/a', ['/opt/app', '/work'], [])['permissions.math-worker.filesystem']) .toEqual({ '/': 'read', '/work/run/a': 'write', '/run': 'none', '/tmp': 'none', '/opt/app': 'none' }); }); + it('denies host credential stores to worker shells by default', () => { + const home = fs.realpathSync(fs.mkdtempSync(path.join(root, 'home-'))); + fs.mkdirSync(path.join(home, '.codex/packages'), { recursive: true }); + fs.writeFileSync(path.join(home, '.codex/auth.json'), '{}'); + fs.mkdirSync(path.join(home, '.ssh')); + vi.stubEnv('HOME', home); + 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')); + } finally { vi.unstubAllEnvs(); } + }); + it('refuses a new thread whose app-server did not adopt the worker profile', async () => { await expect(createCodexMathSession({ ...options, instructions: 'ignore-permissions' })) .rejects.toThrow('math_codex_sandbox_profile_mismatch'); diff --git a/tests/harnessProcess.test.ts b/tests/harnessProcess.test.ts index b17a85e3..674128f6 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, prepareHarnessProcess, type HarnessProcessIdentity } from '../src/runtime/harnessProcess'; +import { confirmHarnessProcessStopped, hostCredentialRoots, prepareHarnessProcess, + type HarnessProcessIdentity } from '../src/runtime/harnessProcess'; function processIdentity(pid: number): HarnessProcessIdentity { const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8'); @@ -52,6 +53,60 @@ describe('shared native harness process isolation', () => { expect(fs.readFileSync(secret, 'utf8')).toBe('hidden file'); }); + it('lists credential stores at their real paths and keeps launch paths and toolchains visible', () => { + const home = path.join(root, 'home'), linked = path.join(outside, 'linked-store'); + for (const directory of ['.config/app', '.config/work', '.codex/packages', '.ssh', '.elan']) fs.mkdirSync(path.join(home, directory), { recursive: true }); + fs.mkdirSync(linked); fs.symlinkSync(linked, path.join(home, '.config/linked')); + fs.writeFileSync(path.join(home, '.codex/auth.json'), '{}'); + expect(hostCredentialRoots([workspace], [home])).toEqual([path.join(home, '.codex/auth.json'), path.join(home, '.config'), + path.join(home, '.ssh'), linked].sort()); + // A store holding the workspace is masked around it; one inside the workspace is not masked. + expect(hostCredentialRoots([path.join(home, '.config/work')], [home])).toEqual([path.join(home, '.codex/auth.json'), + path.join(home, '.config/app'), path.join(home, '.ssh'), linked].sort()); + expect(hostCredentialRoots([home], [home])).toEqual([]); + 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 }); + 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'); + 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')])}) { + 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);`); + expect(result.status, result.stderr).toBe(0); + expect(result.launch.isolationReceipt.hiddenRoots).toEqual(expect.arrayContaining([path.join(home, '.config'), linked])); + } finally { vi.unstubAllEnvs(); } + expect(fs.readFileSync(path.join(home, '.codex/auth.json'), 'utf8')).toBe('codex secret'); + }); + + it('masks credential stores around a workspace that lives inside one', () => { + const home = path.join(root, 'home'); + workspace = path.join(home, '.config/work'); + fs.mkdirSync(workspace, { recursive: true }); fs.mkdirSync(path.join(home, '.config/app')); + fs.writeFileSync(path.join(home, '.config/app/token'), 'config secret'); + vi.stubEnv('HOME', home); + try { + const result = run(`const fs=require('fs'); + fs.writeFileSync(${JSON.stringify(path.join(workspace, 'proof.lean'))}, 'draft'); + if(fs.readdirSync(${JSON.stringify(path.join(home, '.config/app'))}).length) process.exit(7);`); + expect(result.status, result.stderr).toBe(0); + } finally { vi.unstubAllEnvs(); } + expect(fs.readFileSync(path.join(workspace, 'proof.lean'), 'utf8')).toBe('draft'); + }); + it('allows planning notes while the proof workspace and repository metadata are read-only', () => { const proof = path.join(workspace, 'proof.lean'); const gitDirectory = path.join(workspace, '.git');