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
1 change: 1 addition & 0 deletions src/math/mathRuntimeEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
]);
Expand Down
3 changes: 3 additions & 0 deletions src/runtime/agentSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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?: {
Expand Down
13 changes: 8 additions & 5 deletions src/runtime/codexSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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`]: {
Expand Down Expand Up @@ -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,
},
Expand Down
233 changes: 211 additions & 22 deletions src/runtime/harnessProcess.ts

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/runtime/leanHealthCheck.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<MathAgentOptions,
'workspace' | 'profile' | 'environment' | 'hiddenRoots' | 'isolatedWorkspaceParent' | 'isolateProcess' | 'proofProjectRoot' | 'leanHealthCheck' | 'signal'>): Promise<LeanEnvironmentHealth | undefined> {
'workspace' | 'profile' | 'environment' | 'hiddenRoots' | 'readableRoots' | 'isolatedWorkspaceParent' | 'isolateProcess' | 'proofProjectRoot' | 'leanHealthCheck' | 'signal'>): Promise<LeanEnvironmentHealth | undefined> {
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);
Expand Down
3 changes: 3 additions & 0 deletions src/solver/agentTeam.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>; abort: AbortController; routeAbort: AbortController;
admittedTurnId?: string; runSettled?: boolean };
Expand Down Expand Up @@ -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 => {
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/solver/research.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand Down Expand Up @@ -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,
Expand Down
2 changes: 2 additions & 0 deletions src/solver/researchToolGuide.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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). ' +
Expand Down
16 changes: 9 additions & 7 deletions tests/codexSession.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<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'));
// 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(); }
});

Expand Down
80 changes: 67 additions & 13 deletions 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, hostCredentialRoots, prepareHarnessProcess,
import { confirmHarnessProcessStopped, HARNESS_READ_ROOTS_ENV, harnessReadRoots, hostCredentialRoots, hostPrivateRoots,
prepareHarnessProcess,
type HarnessProcessIdentity } from '../src/runtime/harnessProcess';

function processIdentity(pid: number): HarnessProcessIdentity {
Expand Down Expand Up @@ -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');
Expand Down
Loading