Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/runtime/codexSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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`]: {
Expand Down Expand Up @@ -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,
},
Expand Down
48 changes: 47 additions & 1 deletion src/runtime/harnessProcess.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -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<string>();
const valid = homes.filter(home => home && path.isAbsolute(home) && path.resolve(home) !== '/');
const seen = new Set<string>();
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<MathAgentOptions, 'workspace' | 'profile' | 'environment' |
'hiddenRoots' | 'isolatedWorkspaceParent' | 'readOnlyWorkspace'>,
Expand Down Expand Up @@ -115,6 +158,10 @@ export function prepareHarnessProcess(options: Pick<MathAgentOptions, 'workspace
if (!hidden.some(parent => 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'];
Expand All @@ -133,7 +180,6 @@ export function prepareHarnessProcess(options: Pick<MathAgentOptions, 'workspace
args.push(options.readOnlyWorkspace ? '--ro-bind' : '--bind', options.workspace, options.workspace,
'--bind', options.profile, options.profile);
if (options.readOnlyWorkspace) args.push('--bind', scratch, scratch);
const lock = env.DEEPSCIENTIST_MATH_LEAN_LOCK;
if (lock) {
assertMathCanonicalPath(lock);
if (!fs.statSync(lock).isFile() || masks.some(root => isMathPathWithin(root, lock)))
Expand Down
22 changes: 18 additions & 4 deletions tests/codexSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>;
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');
Expand Down
57 changes: 56 additions & 1 deletion tests/harnessProcess.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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');
Expand Down
Loading