diff --git a/package-lock.json b/package-lock.json index 8dca43c..a7616b4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0", "@modelcontextprotocol/sdk": "^1.32.2", "quickjs-emscripten-core": "^0.32.0", + "smol-toml": "^1.9.1", "zod": "^4.6.7" }, "bin": { @@ -2500,6 +2501,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/smol-toml": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz", + "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==", + "license": "BSD-3-Clause", + "engines": { + "node": ">= 18" + }, + "funding": { + "url": "https://github.com/sponsors/cyyynthia" + } + }, "node_modules/source-map-js": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", diff --git a/package.json b/package.json index dd7b34e..bac9d57 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "@jitl/quickjs-ng-wasmfile-release-sync": "^0.32.0", "@modelcontextprotocol/sdk": "^1.32.2", "quickjs-emscripten-core": "^0.32.0", + "smol-toml": "^1.9.1", "zod": "^4.6.7" }, "devDependencies": { diff --git a/src/core/dispatcher.test.ts b/src/core/dispatcher.test.ts index bf26232..002183d 100644 --- a/src/core/dispatcher.test.ts +++ b/src/core/dispatcher.test.ts @@ -138,6 +138,76 @@ describe('Dispatcher', () => { expect(adapter.staticChecked).toHaveLength(2); }); + describe('a rewrite bound to the prepared file', () => { + it('commits the rewrite when the file is unchanged', async () => { + const { dispatcher, tools } = await setup( + { hook: { kind: 'updatedArgs', args: { path: 'a.txt', content: 'rewritten' }, bindsPreparedFile: true } }, + { files: { 'a.txt': 'old' } }, + ); + expect((await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' })).ok).toBe(true); + expect(tools.read('a.txt')).toBe('rewritten'); + }); + + it('commits a bound rewrite of a write that creates the file', async () => { + const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: { path: 'new.txt', content: 'rewritten' }, bindsPreparedFile: true } }); + expect((await dispatcher.dispatch('write', { path: 'new.txt', content: 'x' })).ok).toBe(true); + expect(tools.read('new.txt')).toBe('rewritten'); + }); + + it('denies when the file changed between the hook and the second preparation', async () => { + let runtime: MemoryToolRuntime | undefined; + const { dispatcher, tools } = await setup( + { + hook: () => { + // The file moves on after the hook evaluated the first version. + runtime?.externalWrite('a.txt', 'changed meanwhile'); + return { kind: 'updatedArgs', args: { path: 'a.txt', content: 'rewritten' }, bindsPreparedFile: true }; + }, + }, + { files: { 'a.txt': 'old' } }, + ); + runtime = tools; + const err = errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' })); + expect(err).toMatchObject({ name: 'PermissionDenied', source: 'hook' }); + expect(err.message).toContain('changed after the hook evaluated it'); + expect(tools.read('a.txt')).toBe('changed meanwhile'); + expect(tools.commits).toHaveLength(0); + }); + + it('denies when the file was created between the hook and the second preparation', async () => { + let runtime: MemoryToolRuntime | undefined; + const { dispatcher, tools } = await setup({ + hook: () => { + runtime?.externalWrite('a.txt', 'created meanwhile'); + return { kind: 'updatedArgs', args: { path: 'a.txt', content: 'rewritten' }, bindsPreparedFile: true }; + }, + }); + runtime = tools; + expect(errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' }))).toMatchObject({ source: 'hook' }); + expect(tools.read('a.txt')).toBe('created meanwhile'); + expect(tools.commits).toHaveLength(0); + }); + + it('denies a bound rewrite that targets another file with the same bytes', async () => { + const { dispatcher, tools } = await setup( + { hook: { kind: 'updatedArgs', args: { path: 'b.txt', content: 'rewritten' }, bindsPreparedFile: true } }, + { files: { 'a.txt': 'same', 'b.txt': 'same' } }, + ); + const err = errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'new' })); + expect(err).toMatchObject({ name: 'PermissionDenied', source: 'hook' }); + expect(err.message).toContain('destination'); + expect(tools.read('a.txt')).toBe('same'); + expect(tools.read('b.txt')).toBe('same'); + expect(tools.commits).toHaveLength(0); + }); + + it('denies a bound rewrite of a call that has no file effect', async () => { + const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: { command: 'echo b' }, bindsPreparedFile: true } }); + expect(errorOf(await dispatcher.dispatch('bash', { command: 'echo a' }))).toMatchObject({ source: 'hook' }); + expect(tools.commits).toHaveLength(0); + }); + }); + it('refuses updatedArgs that point outside the workspace', async () => { const { dispatcher, tools } = await setup({ hook: { kind: 'updatedArgs', args: { path: '../etc/passwd', content: 'x' } } }); const err = errorOf(await dispatcher.dispatch('write', { path: 'a.txt', content: 'x' })); diff --git a/src/core/dispatcher.ts b/src/core/dispatcher.ts index 30a1ecc..cc855d7 100644 --- a/src/core/dispatcher.ts +++ b/src/core/dispatcher.ts @@ -72,6 +72,23 @@ function containmentEquals(a: BashContainment, b: BashContainment): boolean { ); } +/** + * For a hook rewrite bound to the prepared file: why the re-prepared call is + * not the file version the hook evaluated, or undefined when it is. + */ +function boundFileMismatch(first: PreparedCall, second: PreparedCall): string | undefined { + if ((first.tool !== 'write' && first.tool !== 'edit') || (second.tool !== 'write' && second.tool !== 'edit') || first.tool !== second.tool) { + return 'hook bound its rewrite to a file version, but the call has no file effect'; + } + if (second.effect.absPath !== first.effect.absPath) { + return `hook rewrite changed the destination after the hook evaluated ${first.effect.absPath}`; + } + if (second.effect.beforeHash !== first.effect.beforeHash) { + return `${first.effect.absPath} changed after the hook evaluated it; the rewrite was not applied`; + } + return undefined; +} + function raceAbort(promise: Promise, signal: AbortSignal): Promise { if (signal.aborted) { promise.catch(() => undefined); @@ -103,7 +120,9 @@ function raceAbort(promise: Promise, signal: AbortSignal): Promise { const reason = second.kind === 'deny' ? second.reason : second.error.message; return fail({ kind: 'deny', source: second.kind === 'deny' ? second.source : 'hook', reason: `hook updated input was refused: ${reason}` }); } + if (decision.bindsPreparedFile === true) { + const unbound = boundFileMismatch(prepared, second.prepared); + if (unbound !== undefined) return fail({ kind: 'deny', source: 'hook', reason: unbound }); + } const recheck = this.#checkStatic(second.prepared, policy); if (recheck) return fail(recheck); prepared = second.prepared; diff --git a/src/core/schemas.test.ts b/src/core/schemas.test.ts index cef9a3b..a3e7190 100644 --- a/src/core/schemas.test.ts +++ b/src/core/schemas.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; import { ToolError } from './errors.js'; -import { parseRunArgs, parseToolCall } from './schemas.js'; +import { DecisionSchema, parseRunArgs, parseToolCall } from './schemas.js'; describe('parseToolCall', () => { it('returns a typed call for valid args', () => { @@ -41,3 +41,13 @@ describe('parseRunArgs', () => { expect(parseRunArgs({ code: 'x', timeoutMs: -1 }).ok).toBe(false); }); }); + +describe('DecisionSchema', () => { + it('accepts an allow bound to the prepared file', () => { + expect(DecisionSchema.safeParse({ kind: 'allow', updatedArgs: { path: 'a', content: 'x' }, bindsPreparedFile: true }).success).toBe(true); + }); + + it.each([false, 'true', 1, null])('rejects bindsPreparedFile %j', (value) => { + expect(DecisionSchema.safeParse({ kind: 'allow', updatedArgs: { path: 'a', content: 'x' }, bindsPreparedFile: value }).success).toBe(false); + }); +}); diff --git a/src/core/schemas.ts b/src/core/schemas.ts index b0c21b7..dc54e4f 100644 --- a/src/core/schemas.ts +++ b/src/core/schemas.ts @@ -32,7 +32,12 @@ export function isToolName(tool: string): tool is ToolName { } export const DecisionSchema = z.discriminatedUnion('kind', [ - z.object({ kind: z.literal('allow'), reason: z.string().optional(), updatedArgs: z.unknown().optional() }), + z.object({ + kind: z.literal('allow'), + reason: z.string().optional(), + updatedArgs: z.unknown().optional(), + bindsPreparedFile: z.literal(true).optional(), + }), z.object({ kind: z.literal('ask'), reason: z.string() }), z.object({ kind: z.literal('deny'), diff --git a/src/core/types.ts b/src/core/types.ts index 34193eb..7e0b40a 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -382,11 +382,16 @@ export type DenySource = * this project's camelCase args shape for the same tool (the adapter maps * from the host's native shape). It is untrusted: the dispatcher re-validates, * re-prepares and re-checks it statically. + * - `bindsPreparedFile: true` (only meaningful with `updatedArgs`): the hook + * evaluated a write/edit against the file version the first preparation + * read. The re-prepared call must then target the same `absPath` with the + * same `beforeHash` (null included), or the dispatcher denies it (source + * `hook`). Without it, a rewrite may point anywhere the static rules allow. * - `ask`: the host would prompt the user. Without an interactive channel the * dispatcher turns it into `deny` with source `ask-unavailable`. */ export type Decision = - | { readonly kind: 'allow'; readonly updatedArgs?: unknown; readonly reason?: string } + | { readonly kind: 'allow'; readonly updatedArgs?: unknown; readonly bindsPreparedFile?: true; readonly reason?: string } | { readonly kind: 'deny'; readonly reason: string; readonly source: DenySource } | { readonly kind: 'ask'; readonly reason: string }; diff --git a/src/hosts/codex/adapter.test.ts b/src/hosts/codex/adapter.test.ts new file mode 100644 index 0000000..c611a92 --- /dev/null +++ b/src/hosts/codex/adapter.test.ts @@ -0,0 +1,549 @@ +import { createHash } from 'node:crypto'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { afterAll, describe, expect, it } from 'vitest'; +import { Dispatcher } from '../../core/dispatcher.js'; +import type { PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; +import { MemoryToolRuntime } from '../../testing/memory-tool-runtime.js'; +import { CodexHostAdapter, type CodexPolicy } from './adapter.js'; +import { applyHunk, parsePatch } from './apply-patch.js'; +import { CodexContextProvider } from './context.js'; +import { commandHookHash } from './hooks.js'; +import { shellCommandFor } from './native.js'; +import { memoryIo } from './test-io.js'; + +const posix = process.platform !== 'win32'; +const sha = (s: string): string => createHash('sha256').update(s, 'utf8').digest('hex'); + +const tmp = mkdtempSync(path.join(os.tmpdir(), 'acm-codex-')); +afterAll(() => rmSync(tmp, { recursive: true, force: true })); + +/** Writes an example hook script and returns the command that runs it. */ +function hook(name: string, body: string): string { + const file = path.join(tmp, `${name}.mjs`); + writeFileSync( + file, + `import { readFileSync, writeFileSync } from 'node:fs';\nconst input = JSON.parse(readFileSync(0, 'utf8'));\n${body}\n`, + ); + return `"${process.execPath}" "${file}"`; +} + +const hooks = { + denyRm: hook('deny-rm', `if (String(input.tool_input.command).includes('rm ')) { process.stderr.write('rm is not allowed'); process.exit(2); }`), + denyJson: hook('deny-json', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: 'blocked by policy' } }));`), + rewrite: hook('rewrite-echo', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', updatedInput: { command: 'echo rewritten' } } }));`), + sleep: hook('sleep-forever', `writeFileSync(process.env.PID_FILE ?? '${path.join(tmp, 'pid').replace(/\\/g, '\\\\')}', String(process.pid)); setInterval(() => {}, 1000);`), + crash: hook('crash', `throw new Error('boom');`), + badJson: hook('bad-json', `process.stdout.write('{not json');`), + silent2: hook('exit2-silent', `process.exit(2);`), + ask: hook('ask', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'ask', permissionDecisionReason: 'confirm' } }));`), + allowOnly: hook('allow-only', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow' } }));`), + text: hook('plain-text', `console.log('looks fine to me');`), + record: hook('record', `writeFileSync(${JSON.stringify(path.join(tmp, 'stdin.json'))}, JSON.stringify(input)); writeFileSync(${JSON.stringify(path.join(tmp, 'cwd.txt'))}, process.cwd());`), + wrongEvent: hook('wrong-event', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PostToolUse', permissionDecision: 'allow', updatedInput: { command: 'echo x' } } }));`), + extraField: hook('extra-field', `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', updatedInput: { command: 'echo x', extra: 1 } } }));`), + patchRewrite: hook( + 'patch-rewrite', + `console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'allow', updatedInput: { command: String(input.tool_input.command).replace('+world', '+WORLD') } } }));`, + ), +}; + +interface Group { + matcher?: string; + hooks: { type: 'command'; command: string; timeout?: number }[]; +} + +function hooksJson(groups: Group[]): string { + return JSON.stringify({ hooks: { PreToolUse: groups } }); +} + +const WS = path.join(tmp, 'ws'); +mkdirSync(path.join(WS, 'sub'), { recursive: true }); + +function ctx(over: Partial = {}): SessionContext { + return { host: 'codex', cwd: WS, roots: [], permissionMode: 'default', sources: {}, sessionId: 's1', turnId: 't1', model: 'm1', toolUseId: 'call-9', ...over }; +} + +function adapter(files: Record, extra: { argv?: string[]; current?: Record } = {}): CodexHostAdapter { + return new CodexHostAdapter({ + io: () => memoryIo({ files, argv: extra.argv ?? ['codex'] }), + hookEnv: { ...process.env, SHELL: '/bin/sh' }, + stateDir: '/state', + tmpDirs: { slashTmp: '/tmp', tmpdir: null }, + readCurrent: async (abs) => extra.current?.[abs] ?? null, + }); +} + +async function policyOf(a: CodexHostAdapter, c = ctx()): Promise> { + const p = await a.loadPolicy(c); + if ('error' in p) throw new Error(p.error); + return p; +} + +const bash = (command: string, cwd = WS): PreparedCall => ({ id: 'c1', tool: 'bash', args: { command }, effect: { command, cwd, timeoutMs: 1000, containment: { mode: 'none' } } }); +const write = (absPath: string, before: string | null, after: string): PreparedCall => ({ + id: 'c2', + tool: 'write', + args: { path: path.posix.relative(WS, absPath) || absPath, content: after }, + effect: { absPath, beforeHash: before === null ? null : sha(before), afterContent: after, diff: '' }, +}); +const edit = (absPath: string, before: string, after: string): PreparedCall => ({ + id: 'c3', + tool: 'edit', + args: { path: path.posix.relative(WS, absPath), oldString: 'x', newString: 'y' }, + effect: { absPath, beforeHash: sha(before), afterContent: after, diff: '', matchedOldString: 'x', matchStrategy: 'exact', replacements: 1 }, +}); +const read = (absPath: string): PreparedCall => ({ id: 'c4', tool: 'read', args: { path: absPath, offset: 3, limit: 10 }, effect: { absPath, offset: 3, limit: 10 } }); + +async function authorize(a: CodexHostAdapter, prepared: PreparedCall, c = ctx()) { + const p = await policyOf(a, c); + return a.authorize(prepared, c, p, new AbortController().signal); +} + +const managed = (groups: Group[]): Record => ({ '/etc/codex/hooks.json': hooksJson(groups) }); + +describe.runIf(posix)('Codex hooks', () => { + it('denies on exit 2 with stderr', async () => { + const a = adapter(managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.denyRm }] }])); + expect(await authorize(a, bash('rm -rf build'))).toEqual({ kind: 'deny', source: 'hook', reason: 'rm is not allowed' }); + expect(await authorize(a, bash('ls'))).toEqual({ kind: 'allow' }); + }); + + it('denies on JSON permissionDecision deny', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.denyJson }] }])); + expect(await authorize(a, bash('ls'))).toEqual({ kind: 'deny', source: 'hook', reason: 'blocked by policy' }); + }); + + it('maps updatedInput back to bash args', async () => { + const a = adapter(managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.rewrite }] }])); + const decision = await authorize(a, bash('echo original')); + expect(decision).toMatchObject({ kind: 'allow', updatedArgs: { command: 'echo rewritten' } }); + // A bash rewrite has no file version to bind to. + expect(decision).not.toHaveProperty('bindsPreparedFile'); + }); + + it('times out, kills the hook and denies', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.sleep, timeout: 1 }] }])); + const d = await authorize(a, bash('ls')); + expect(d).toMatchObject({ kind: 'deny', source: 'hook-timeout' }); + const pid = Number(readFileSync(path.join(tmp, 'pid'), 'utf8')); + await new Promise((r) => setTimeout(r, 300)); + expect(() => process.kill(pid, 0)).toThrow(); + }); + + it('fails closed where Codex is non-blocking: crash, invalid JSON, exit 2 without stderr, ask, allow alone', async () => { + for (const cmd of [hooks.crash, hooks.badJson, hooks.silent2, hooks.ask, hooks.allowOnly, hooks.wrongEvent, hooks.extraField]) { + const a = adapter(managed([{ hooks: [{ type: 'command', command: cmd }] }])); + expect(await authorize(a, bash('ls')), cmd).toMatchObject({ kind: 'deny', source: 'hook-error' }); + } + }); + + it('denies when a hook prints output that is not JSON (Codex ignores it)', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.text }] }])); + expect(await authorize(a, bash('ls'))).toMatchObject({ kind: 'deny', source: 'hook-error', reason: expect.stringContaining('not JSON') }); + }); + + it('matches hook matchers with Rust regex semantics', async () => { + for (const matcher of ['\\ABash\\z', '(?i)^bash$', '^(?PBa)sh$', '[[:upper:]]ash', 'B\\x{61}sh']) { + const a = adapter(managed([{ matcher, hooks: [{ type: 'command', command: hooks.denyJson }] }])); + expect(await authorize(a, bash('ls')), matcher).toMatchObject({ kind: 'deny', source: 'hook' }); + } + // A matcher that cannot be translated exactly is refused before any hook runs. + for (const matcher of ['(?x) ^ Write $', '(?i)\\P{Lu}ash']) { + const odd = adapter(managed([{ matcher, hooks: [{ type: 'command', command: hooks.record }] }])); + rmSync(path.join(tmp, 'stdin.json'), { force: true }); + expect(await authorize(odd, bash('ls')), matcher).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + expect(existsSync(path.join(tmp, 'stdin.json'))).toBe(false); + } + // A translated matcher still does not match other tools. + const other = adapter(managed([{ matcher: '\\Aapply_patch\\z', hooks: [{ type: 'command', command: hooks.denyJson }] }])); + expect(await authorize(other, bash('ls'))).toEqual({ kind: 'allow' }); + }); + + it('matches apply_patch with the Write|Edit alias, and Bash hooks do not', async () => { + const file = `${WS}/a.txt`; + const a = adapter(managed([{ matcher: 'Write|Edit', hooks: [{ type: 'command', command: hooks.denyJson }] }]), { current: { [file]: 'hello\n' } }); + expect(await authorize(a, write(file, 'hello\n', 'hello\nworld\n'))).toMatchObject({ kind: 'deny', source: 'hook' }); + expect(await authorize(a, edit(file, 'hello\n', 'bye\n'))).toMatchObject({ kind: 'deny', source: 'hook' }); + expect(await authorize(a, bash('ls'))).toEqual({ kind: 'allow' }); + const regex = adapter(managed([{ matcher: '^apply_', hooks: [{ type: 'command', command: hooks.denyJson }] }]), { current: { [file]: 'hello\n' } }); + expect(await authorize(regex, write(file, 'hello\n', 'x\n'))).toMatchObject({ kind: 'deny' }); + }); + + it('runs only user hooks whose trusted_hash matches', async () => { + const group: Group = { matcher: 'Bash', hooks: [{ type: 'command', command: hooks.denyJson }] }; + const key = '/home/u/.codex/hooks.json:pre_tool_use:0:0'; + const hash = commandHookHash({ matcher: 'Bash', command: hooks.denyJson, timeoutSec: 600, async: false }); + const files = (state: string) => ({ '/home/u/.codex/hooks.json': hooksJson([group]), '/home/u/.codex/config.toml': state }); + expect(await authorize(adapter(files('')), bash('ls'))).toEqual({ kind: 'allow' }); + expect(await authorize(adapter(files(`[hooks.state."${key}"]\ntrusted_hash = "${hash}"\n`)), bash('ls'))).toMatchObject({ kind: 'deny', source: 'hook' }); + expect(await authorize(adapter(files(`[hooks.state."${key}"]\ntrusted_hash = "sha256:other"\n`)), bash('ls'))).toEqual({ kind: 'allow' }); + expect(await authorize(adapter(files(`[hooks.state."${key}"]\ntrusted_hash = "${hash}"\nenabled = false\n`)), bash('ls'))).toEqual({ kind: 'allow' }); + // --dangerously-bypass-hook-trust runs it without state. + expect(await authorize(adapter(files(''), { argv: ['codex', '--dangerously-bypass-hook-trust'] }), bash('ls'))).toMatchObject({ kind: 'deny' }); + }); + + it('denies calls matched by a hook whose trust cannot be verified, without running it', async () => { + const files = (cmd: string) => ({ + '/home/u/.codex/hooks.json': hooksJson([{ hooks: [{ type: 'command', command: cmd }] }]), + '/home/u/.codex/config.toml': '[hooks]\nstate = "corrupted"\n', + }); + for (const cmd of [hooks.denyJson, hooks.crash, hooks.rewrite]) { + expect(await authorize(adapter(files(cmd)), bash('ls'))).toMatchObject({ kind: 'deny', source: 'unsupported-config', reason: expect.stringContaining('trust') }); + } + }); + + it('reads hook trust from the --profile layer', async () => { + const key = '/home/u/.codex/hooks.json:pre_tool_use:0:0'; + const hash = commandHookHash({ matcher: undefined, command: hooks.denyJson, timeoutSec: 600, async: false }); + const files = { '/home/u/.codex/hooks.json': hooksJson([{ hooks: [{ type: 'command', command: hooks.denyJson }] }]), '/home/u/.codex/work.config.toml': `[hooks.state."${key}"]\ntrusted_hash = "${hash}"\n` }; + expect(await authorize(adapter(files, { argv: ['codex', '-p', 'work'] }), bash('ls'))).toMatchObject({ kind: 'deny', source: 'hook' }); + }); + + it('refuses required hooks it cannot load and plugin hooks of an unverifiable installation', async () => { + const required = adapter({ '/etc/codex/requirements.toml': '[[hooks.PreToolUse]]\n[[hooks.PreToolUse.hooks]]\ntype = "prompt"\n' }); + expect(await required.loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('required hook') }); + const plugin = adapter({ '/home/u/.codex/config.toml': '[plugins."tool@market"]\nenabled = true\n' }); + expect(await plugin.loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('active installation') }); + }); + + it('respects features.hooks and allow_managed_hooks_only', async () => { + const userHooks = { '/home/u/.codex/hooks.json': hooksJson([{ hooks: [{ type: 'command', command: hooks.denyJson }] }]) }; + const off = adapter({ ...managed([{ hooks: [{ type: 'command', command: hooks.denyJson }] }]), '/home/u/.codex/config.toml': '[features]\nhooks = false\n' }); + expect(await authorize(off, bash('ls'))).toEqual({ kind: 'allow' }); + const managedOnly = adapter({ ...userHooks, '/home/u/.codex/config.toml': '[hooks]\nstate = 1\n', '/etc/codex/requirements.toml': 'allow_managed_hooks_only = true\n' }); + expect(await authorize(managedOnly, bash('ls'))).toEqual({ kind: 'allow' }); + }); + + it('reads inline [hooks] tables from config.toml', async () => { + const toml = `[[hooks.PreToolUse]]\nmatcher = "Bash"\n[[hooks.PreToolUse.hooks]]\ntype = "command"\ncommand = ${JSON.stringify(hooks.denyRm)}\n`; + expect(await authorize(adapter({ '/etc/codex/config.toml': toml }), bash('rm x'))).toMatchObject({ kind: 'deny', source: 'hook' }); + }); + + it('refuses a broken hooks.json instead of skipping it', async () => { + expect(await adapter({ '/etc/codex/hooks.json': '{' }).loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('invalid JSON') }); + expect(await adapter({ '/etc/codex/hooks.json': '{"hooks":{},"extra":1}' }).loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('invalid hooks file') }); + }); +}); + +describe.runIf(posix)('exactness: what the hook sees is what will be applied', () => { + const recorded = (): Record => JSON.parse(readFileSync(path.join(tmp, 'stdin.json'), 'utf8')); + + it('shows bash as Bash {command} with the Codex hook input fields', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.record }] }])); + const call = bash('git status && ls -la', `${WS}/sub`); + await authorize(a, call); + const input = recorded(); + expect(input).toEqual({ + session_id: 's1', + turn_id: 't1', + transcript_path: null, + cwd: `${WS}/sub`, + hook_event_name: 'PreToolUse', + model: 'm1', + permission_mode: 'default', + tool_name: 'Bash', + tool_input: { command: call.tool === 'bash' ? call.effect.command : '' }, + tool_use_id: 'call-9/c1', + }); + // The hook process runs in the session cwd; the tool's cwd is only reported. + expect(readFileSync(path.join(tmp, 'cwd.txt'), 'utf8')).toBe(realpathSync(WS)); + }); + + it('builds no native input for a call no hook matches', async () => { + const a = new CodexHostAdapter({ + io: () => memoryIo({ files: managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.record }] }]), argv: ['codex'] }), + readCurrent: () => Promise.reject(new Error('must not read')), + }); + expect(await authorize(a, write(`${WS}/a.txt`, 'a\n', 'b\n'))).toEqual({ kind: 'allow' }); + }); + + it('shows the effective read range and the search caps', () => { + expect(shellCommandFor({ id: 'r', tool: 'read', args: { path: 'a' }, effect: { absPath: '/w/a', offset: 1, limit: 2000 } })).toBe("sed -n '1,2000p' -- '/w/a'"); + const grep = shellCommandFor({ id: 'g', tool: 'grep', args: { pattern: 'x' }, effect: { absRoot: '/w', pattern: 'x', glob: '*.ts', ignoreCase: false, maxResults: 5 } }); + expect(grep).toBe("rg -n --hidden --no-ignore -g '*.ts' -e 'x' -- '/w' | head -n 5"); + expect(shellCommandFor({ id: 'h', tool: 'glob', args: { pattern: '!x' }, effect: { absRoot: '/w', pattern: '!x', maxResults: 5 } })).toBeUndefined(); + }); + + it('shows write and edit as an apply_patch that reproduces the after content', async () => { + const file = `${WS}/src/app.ts`; + const before = 'const a = 1;\nconst b = 2;\nconst c = 3;\n'; + const after = 'const a = 1;\nconst b = 20;\nconst c = 3;\nexport { a };\n'; + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.record }] }]), { current: { [file]: before } }); + for (const call of [write(file, before, after), edit(file, before, after), write(`${WS}/new.txt`, null, 'fresh\n')]) { + expect(await authorize(a, call)).toEqual({ kind: 'allow' }); + const input = recorded(); + expect(input['tool_name']).toBe('apply_patch'); + const toolInput = input['tool_input']; + if (typeof toolInput !== 'object' || toolInput === null || !('command' in toolInput) || typeof toolInput.command !== 'string') throw new Error('no command'); + const { hunks } = parsePatch(toolInput.command); + const hunk = hunks[0]; + if (hunk === undefined || call.tool === 'bash' || call.tool === 'read' || call.tool === 'grep' || call.tool === 'glob') throw new Error('bad'); + expect(path.posix.resolve(WS, hunk.path)).toBe(call.effect.absPath); + const current = call.effect.beforeHash === null ? null : before; + expect(applyHunk(hunk.kind === 'add' ? null : current, hunk)).toBe(call.effect.afterContent); + } + }); + + it('shows read as the sed command Codex would run', async () => { + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.record }] }])); + await authorize(a, read(`${WS}/it's.txt`)); + expect(recorded()['tool_input']).toEqual({ command: `sed -n '3,12p' -- '${WS}/it'\\''s.txt'` }); + }); + + it('denies a change the Codex patch format cannot show exactly when a hook would see it', async () => { + const withHook = adapter(managed([{ matcher: 'Write', hooks: [{ type: 'command', command: hooks.record }] }]), { current: { [`${WS}/a.txt`]: 'a\n' } }); + for (const call of [write(`${WS}/crlf.txt`, null, 'hello\r\n'), write(`${WS}/nonl.txt`, null, 'hello'), write(`${WS}/a.txt`, 'a\n', 'a\nb')]) { + expect(await authorize(withHook, call)).toMatchObject({ kind: 'deny', source: 'unsupported-config' }); + } + expect(await authorize(withHook, write(`${WS}/ok.txt`, null, 'hello\n'))).toEqual({ kind: 'allow' }); + // No hook sees apply_patch: nothing inexact is shown, nothing to deny. + const bashOnly = adapter(managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.record }] }])); + expect(await authorize(bashOnly, write(`${WS}/crlf.txt`, null, 'hello\r\n'))).toEqual({ kind: 'allow' }); + }); + + it('maps a rewritten apply_patch back to a write', async () => { + const file = `${WS}/hello.txt`; + const a = adapter(managed([{ hooks: [{ type: 'command', command: hooks.patchRewrite }] }]), { current: { [file]: 'hello\n' } }); + // The patch was applied to the version the hook saw, so the rewrite is bound to it. + expect(await authorize(a, write(file, 'hello\n', 'hello\nworld\n'))).toMatchObject({ + kind: 'allow', + updatedArgs: { path: 'hello.txt', content: 'hello\nWORLD\n' }, + bindsPreparedFile: true, + }); + expect(await authorize(a, edit(file, 'hello\n', 'hello\nworld\n'))).toMatchObject({ + kind: 'allow', + updatedArgs: { path: 'hello.txt', oldString: 'hello\n', newString: 'hello\nWORLD\n' }, + bindsPreparedFile: true, + }); + }); + + it('denies when the file changed after prepare', async () => { + const file = `${WS}/a.txt`; + const a = new CodexHostAdapter({ io: () => memoryIo({ files: managed([{ hooks: [{ type: 'command', command: hooks.record }] }]), argv: ['codex'] }), stateDir: '/state' }); + const real = path.join(tmp, 'changed.txt'); + writeFileSync(real, 'now\n'); + expect(await authorize(a, write(real, 'before\n', 'after\n'))).toMatchObject({ kind: 'deny', source: 'hook-error' }); + void file; + }); +}); + +describe.runIf(posix)('sandbox mode × tool', () => { + const rules = { '/home/u/.codex/rules/default.rules': 'prefix_rule(pattern=["rm"], decision="forbidden")\nprefix_rule(pattern=["git", "push"], decision="prompt")\n' }; + + async function decide(mode: string, prepared: PreparedCall, files: Record = {}, argv: string[] = ['codex']) { + // The session runs in `mode`; the turn metadata reports the same mode. + const a = adapter(files, { argv: [...argv, '-s', mode] }); + const c = ctx({ sandboxMode: mode }); + const p = await policyOf(a, c); + return { decision: a.checkStatic(prepared, c, p), containment: p.bashContainment }; + } + + it('returns the containment of each mode', async () => { + expect((await decide('read-only', bash('ls'))).containment).toEqual({ mode: 'sandbox', readOnly: true, writableRoots: [], network: false }); + expect((await decide('workspace-write', bash('ls'), { '/home/u/.codex/config.toml': '[sandbox_workspace_write]\nwritable_roots = ["/data"]\nnetwork_access = true\n' })).containment).toEqual({ + mode: 'sandbox', + readOnly: false, + writableRoots: [WS, '/data', '/tmp'], + network: true, + }); + expect((await decide('danger-full-access', bash('ls'))).containment).toEqual({ mode: 'none' }); + }); + + it('decides write/edit per mode', async () => { + const inside = write(`${WS}/a.txt`, null, 'x'); + const outside = write('/etc/x.conf', null, 'x'); + const git = write(`${WS}/.git/config`, null, 'x'); + expect((await decide('read-only', inside)).decision.kind).toBe('ask'); + expect((await decide('workspace-write', inside)).decision.kind).toBe('allow'); + expect((await decide('workspace-write', write('/tmp/scratch', null, 'x'))).decision.kind).toBe('allow'); + expect((await decide('workspace-write', outside)).decision.kind).toBe('ask'); + expect((await decide('workspace-write', git)).decision.kind).toBe('ask'); + expect((await decide('danger-full-access', outside)).decision.kind).toBe('allow'); + // Whole path segments: a child named `..name` is inside the workspace. + expect((await decide('workspace-write', write(`${WS}/..name/a.txt`, null, 'x'))).decision.kind).toBe('allow'); + // With approval never, what Codex would ask is rejected. + expect((await decide('read-only', inside, {}, ['codex', 'exec'])).decision).toMatchObject({ kind: 'deny', source: 'rule' }); + }); + + it('applies exec policy rules to bash and to shell-shaped reads in every mode', async () => { + for (const mode of ['read-only', 'workspace-write', 'danger-full-access']) { + expect((await decide(mode, bash('ls'), rules)).decision.kind).toBe('allow'); + expect((await decide(mode, bash('ls && rm -rf x'), rules)).decision).toMatchObject({ kind: 'deny', source: 'rule' }); + expect((await decide(mode, bash('git push origin'), rules)).decision.kind).toBe('ask'); + expect((await decide(mode, read(`${WS}/a.txt`), rules)).decision.kind).toBe('allow'); + } + const sedRule = { '/home/u/.codex/rules/default.rules': 'prefix_rule(pattern=["sed"], decision="forbidden")\n' }; + expect((await decide('read-only', read(`${WS}/a.txt`), sedRule)).decision.kind).toBe('deny'); + expect((await decide('read-only', bash('rm -rf build'))).decision.kind).toBe('ask'); + expect((await decide('read-only', bash('ls'), {}, ['codex', '-a', 'untrusted'])).decision.kind).toBe('ask'); + expect((await decide('read-only', bash("echo 'x"))).decision).toMatchObject({ kind: 'deny', source: 'rule' }); + }); + + it('falls back to bash -lc for scripts that are not plain, like Codex', async () => { + const bashRule = { '/home/u/.codex/rules/default.rules': 'prefix_rule(pattern=["bash"], decision="forbidden")\n' }; + for (const cmd of ['echo ok # comment', 'echo {1..3}', 'echo a\\ b', 'echo ok &&', '"echo" ok', 'echo "$HOME"']) { + expect((await decide('danger-full-access', bash(cmd), bashRule)).decision, cmd).toMatchObject({ kind: 'deny', source: 'rule' }); + } + for (const cmd of ['echo ok', "echo 'a b' | wc -l", 'a && b\nc']) { + expect((await decide('danger-full-access', bash(cmd), bashRule)).decision, cmd).toEqual({ kind: 'allow' }); + } + }); + + it('evaluates commands behind wrappers and trap actions', async () => { + const blocked = { '/home/u/.codex/rules/default.rules': 'prefix_rule(pattern=["blocked"], decision="forbidden")\n' }; + const wrapped = [ + 'command blocked', + "trap 'blocked' EXIT", + 'trap -- "blocked x" INT', + 'env X=1 blocked', + 'env -i -u HOME blocked', + 'env -S "blocked now"', + 'sudo -u root blocked', + 'exec blocked', + 'builtin blocked', + 'nohup blocked', + 'nice -n 5 blocked', + 'timeout -s KILL 5 blocked', + 'time -p blocked', + 'stdbuf -oL blocked', + 'xargs -n 1 blocked', + 'find . -name x -exec blocked {} ;', + "eval 'blocked x'", + 'sudo env A=1 command blocked', + ]; + for (const cmd of wrapped) expect((await decide('danger-full-access', bash(cmd), blocked)).decision, cmd).toMatchObject({ kind: 'deny', source: 'rule' }); + // A forced rm in a trap action needs approval, like Codex's dangerous-command check. + expect((await decide('danger-full-access', bash("trap 'rm -rf /tmp/example' EXIT"))).decision.kind).toBe('ask'); + // Unknown wrapper options: cannot tell what runs, so ask. + expect((await decide('danger-full-access', bash('env --mystery blocked'), blocked)).decision.kind).toBe('ask'); + expect((await decide('danger-full-access', bash('timeout 5 echo blocked'), blocked)).decision).toEqual({ kind: 'allow' }); + // `command -v` only looks the name up. + expect((await decide('danger-full-access', bash('command -v blocked'), blocked)).decision).toEqual({ kind: 'allow' }); + // env -S splits only its value; later words stay separate argv words. + expect((await decide('danger-full-access', bash("env -S rm '#' -rf x"))).decision.kind).toBe('ask'); + expect((await decide('danger-full-access', bash("env -S 'ls $X'"), blocked)).decision.kind).toBe('ask'); + // GNU env also splits on vertical tab and form feed, which are not reproduced. + expect((await decide('danger-full-access', bash("env -S 'blocked\vnow'"), blocked)).decision.kind).toBe('ask'); + }); + + it('asks when run-time expansion could reach a rule or the forced-rm check', async () => { + for (const cmd of ['rm $FLAGS x', 'rm -* x', '$CMD -rf x', 'git $SUB', 'git ~/x', '~/bin/git push']) { + expect((await decide('danger-full-access', bash(cmd), { '/home/u/.codex/rules/default.rules': 'prefix_rule(pattern=["git", "push"], decision="prompt")\n' })).decision.kind, cmd).toBe('ask'); + } + expect((await decide('danger-full-access', bash('echo $HOME'))).decision).toEqual({ kind: 'allow' }); + }); + + it('fails the load on bad rules and unknown sandbox modes', async () => { + const bad = adapter({ '/home/u/.codex/rules/x.rules': 'network_rule(host="a", protocol="https", decision="allow")' }); + expect(await bad.loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('outside the supported rules subset') }); + expect(await adapter({}).loadPolicy(ctx({ sandboxMode: 'mystery' }))).toMatchObject({ error: expect.stringContaining('mystery') }); + }); + + it('protects Codex policy files and the state dir', async () => { + const p = await policyOf(adapter({})); + expect(p.protectedPaths).toEqual(expect.arrayContaining(['**/.codex/**', '/home/u/.codex/**', '/etc/codex/**', '/state/**', `${WS}/.mcp.json`])); + // Also by canonical destination, for a state dir not created yet under a linked parent. + const linked = new CodexHostAdapter({ io: () => ({ ...memoryIo({ dirs: ['/link'], argv: ['codex'] }), realpath: (x: string) => (x === '/link' ? '/real' : x) }), stateDir: '/link/state' }); + expect((await policyOf(linked)).protectedPaths).toEqual(expect.arrayContaining(['/link/state/**', '/real/state/**'])); + }); + + it('lets the turn metadata narrow the sandbox mode, never widen it', async () => { + expect((await policyOf(adapter({}), ctx({ sandboxMode: 'danger-full-access' }))).bashContainment).toMatchObject({ mode: 'sandbox', readOnly: true }); + expect((await policyOf(adapter({}, { argv: ['codex', '-s', 'danger-full-access'] }), ctx({ sandboxMode: 'read-only' }))).bashContainment).toMatchObject({ readOnly: true }); + // A narrowed mode the requirements do not allow falls to an allowed one below it. + const req = adapter({ '/etc/codex/requirements.toml': 'allowed_sandbox_modes = ["read-only", "danger-full-access"]\n' }, { argv: ['codex', '-s', 'danger-full-access'] }); + expect((await policyOf(req, ctx({ sandboxMode: 'workspace-write' }))).bashContainment).toMatchObject({ mode: 'sandbox', readOnly: true }); + }); + + it('fails the load when a listed rule file disappears', async () => { + const a = new CodexHostAdapter({ io: () => ({ ...memoryIo({ argv: ['codex'] }), listFiles: (d: string) => (d === '/home/u/.codex/rules' ? ['gone.rules'] : []) }), stateDir: '/state' }); + expect(await a.loadPolicy(ctx())).toMatchObject({ error: expect.stringContaining('disappeared') }); + }); +}); + +describe.runIf(posix)('dispatcher integration', () => { + it('re-prepares a hook rewrite and commits exactly the rewritten command', async () => { + const tools = new MemoryToolRuntime({ root: WS }); + const a = adapter(managed([{ matcher: 'Bash', hooks: [{ type: 'command', command: hooks.rewrite }] }]), { argv: ['codex', '-s', 'danger-full-access'] }); + const c = ctx({ sandboxMode: 'danger-full-access' }); + const policy = await a.loadPolicy(c); + const d = new Dispatcher({ adapter: a, tools, ctx: c, policy }); + const reply = await d.dispatch('bash', { command: 'echo original' }); + expect(reply.ok).toBe(true); + expect(tools.commits.map((x) => x.target)).toEqual(['echo rewritten']); + }); + + /** A Codex adapter over the memory runtime's files; `afterHook` runs once the hook has decided. */ + function patchRewriteSetup(initial: string, afterHook: (tools: MemoryToolRuntime) => void = () => undefined) { + const tools = new MemoryToolRuntime({ root: WS, files: { 'hello.txt': initial } }); + class Racing extends CodexHostAdapter { + override async authorize(...args: Parameters) { + const decision = await super.authorize(...args); + afterHook(tools); + return decision; + } + } + const a = new Racing({ + io: () => memoryIo({ files: managed([{ hooks: [{ type: 'command', command: hooks.patchRewrite }] }]), argv: ['codex', '-s', 'danger-full-access'] }), + hookEnv: { ...process.env, SHELL: '/bin/sh' }, + stateDir: '/state', + tmpDirs: { slashTmp: '/tmp', tmpdir: null }, + readCurrent: async (abs) => tools.files.get(abs) ?? null, + }); + return { tools, a }; + } + + it('commits a patch rewrite against the version the hook evaluated', async () => { + const { tools, a } = patchRewriteSetup('hello\n'); + const c = ctx({ sandboxMode: 'danger-full-access' }); + const d = new Dispatcher({ adapter: a, tools, ctx: c, policy: await a.loadPolicy(c) }); + expect((await d.dispatch('write', { path: 'hello.txt', content: 'hello\nworld\n' })).ok).toBe(true); + expect(tools.read('hello.txt')).toBe('hello\nWORLD\n'); + }); + + it('denies a patch rewrite when the file changed after the hook evaluated it', async () => { + const { tools, a } = patchRewriteSetup('hello\n', (t) => t.externalWrite('hello.txt', 'changed meanwhile\n')); + const c = ctx({ sandboxMode: 'danger-full-access' }); + const d = new Dispatcher({ adapter: a, tools, ctx: c, policy: await a.loadPolicy(c) }); + const reply = await d.dispatch('write', { path: 'hello.txt', content: 'hello\nworld\n' }); + expect(reply).toMatchObject({ ok: false, error: { code: 'denied', source: 'hook' } }); + expect(tools.read('hello.txt')).toBe('changed meanwhile\n'); + expect(tools.commits).toHaveLength(0); + }); + + it('denies every call when the config cannot be loaded', async () => { + const tools = new MemoryToolRuntime({ root: WS }); + const a = adapter({ '/home/u/.codex/config.toml': 'not = = toml' }); + const c = ctx(); + const d = new Dispatcher({ adapter: a, tools, ctx: c, policy: await a.loadPolicy(c) }); + const reply = await d.dispatch('bash', { command: 'ls' }); + expect(reply).toMatchObject({ ok: false, error: { code: 'denied', source: 'unsupported-config' } }); + }); +}); + +describe('CodexContextProvider', () => { + it('reads _meta and the server cwd, never tool args', async () => { + const cwd = path.resolve(tmp); + const c = await new CodexContextProvider().resolve({ + env: {}, + roots: [], + serverCwd: cwd, + meta: { + callId: 'exec-1', + sessionId: 'ses', + threadId: 'thr', + 'x-codex-turn-metadata': { session_id: 'ses', turn_id: 'turn', model: 'gpt', sandbox: 'seccomp', sandbox_mode: 'workspace-write', extra: 1 }, + _ctx: { cwd: '/evil' }, + }, + }); + expect(c).toMatchObject({ host: 'codex', cwd, sessionId: 'ses', turnId: 'turn', model: 'gpt', sandboxMode: 'workspace-write', toolUseId: 'exec-1' }); + const junk = await new CodexContextProvider().resolve({ env: {}, roots: [], serverCwd: cwd, meta: { callId: 5 } }); + expect(junk.toolUseId).toBeUndefined(); + // Turn metadata or a sandbox mode that is present but invalid is an error. + for (const turn of ['nope', { sandbox_mode: 'mystery' }]) { + await expect(new CodexContextProvider().resolve({ env: {}, roots: [], serverCwd: cwd, meta: { 'x-codex-turn-metadata': turn } })).rejects.toThrow(/turn metadata/); + } + }); +}); diff --git a/src/hosts/codex/adapter.ts b/src/hosts/codex/adapter.ts new file mode 100644 index 0000000..0fe9d3a --- /dev/null +++ b/src/hosts/codex/adapter.ts @@ -0,0 +1,335 @@ +/** + * Codex CLI host adapter: authorizes every binding call the way Codex 0.169 + * authorizes the equivalent native action. + * + * Reference: openai/codex rust-v0.169.0 (commit d32063f96c2d). See config.ts, + * exec-policy.ts, hooks.ts and apply-patch.ts for the parts of the source + * each piece follows. + * + * checkStatic (no I/O): + * - Shell-shaped calls (bash, and read/grep/glob shown as the shell command + * Codex would run) go through the exec policy rules on every simple + * command: forbidden → deny, prompt → ask, allow → allow; strictest wins. + * Unmatched commands follow Codex's heuristics: a forced `rm` asks, and the + * `untrusted` approval policy asks for everything not allowed by a rule. + * With approval `never`, Codex rejects what it would ask: deny. + * - write/edit follow the sandbox mode: `read-only` asks, `workspace-write` + * allows inside the writable roots (except `.git`, `.agents`, `.codex`, + * `.aws` below them) and asks elsewhere, `danger-full-access` allows. + * + * Deviation (stricter than Codex): an exec-policy `allow` does not lift bash + * containment; the containment is always the sandbox mode's. + */ + +import { readFileSync } from 'node:fs'; +import path from 'node:path'; +import { stateDirPath } from '../../core/state-dir.js'; +import type { BashContainment, Decision, HostAdapter, PolicyLoadError, PolicySnapshot, PreparedCall, SessionContext } from '../../core/types.js'; +import { ConfigError, loadCodexConfig, nodeConfigIo, ruleFiles, type ApprovalPolicy, type ConfigIo, type SandboxMode } from './config.js'; +import { isDangerousCommand, matchRules, parseRulesFile, RulesParseError, strictest, type ExecPolicy, type PrefixRule } from './exec-policy.js'; +import { discoverHooks, matcherMatches, runHooks, type HookHandler } from './hooks.js'; +import { APPLY_PATCH_NAMES, BASH_NAMES, mapUpdatedInput, nativeCall, NativeShapeError, shellCommandFor, type NativeCall } from './native.js'; +import { ShellParseError, splitShellCommands } from './shell.js'; + +/** Adapter-specific part of the policy snapshot. */ +export interface CodexPolicy { + readonly sandboxMode: SandboxMode; + readonly approvalPolicy: ApprovalPolicy; + /** Roots write/edit may change without asking (workspace-write only). */ + readonly writableRoots: readonly string[]; + readonly rules: ExecPolicy; + readonly hooks: readonly HookHandler[]; + readonly hooksEnabled: boolean; + /** Hook `permission_mode`: `bypassPermissions` when approval is `never`, else `default`. */ + readonly permissionMode: string; + readonly codexHome: string; + readonly notes: readonly string[]; +} + +export interface CodexHostAdapterOptions { + /** Filesystem and process access (tests). Defaults to the real ones. */ + readonly io?: (ctx: SessionContext) => ConfigIo; + /** Environment of hook processes. Defaults to `process.env`. */ + readonly hookEnv?: Readonly>; + /** Server state directory, protected from writes. */ + readonly stateDir?: string; + /** Temp directories writable in workspace-write. Defaults to `/tmp` and `$TMPDIR`. */ + readonly tmpDirs?: { readonly slashTmp: string | null; readonly tmpdir: string | null }; + /** Replaces how the current file is read for write/edit (tests). */ + readonly readCurrent?: (absPath: string, beforeHash: string | null) => Promise; +} + +const READ_ONLY_SUBPATHS = ['.git', '.agents', '.codex', '.aws']; +/** Sandbox modes, least to most permissive. */ +const SANDBOX_MODES: readonly SandboxMode[] = ['read-only', 'workspace-write', 'danger-full-access']; + +function isInside(child: string, parent: string): boolean { + const rel = path.relative(parent, child); + // Compare whole segments: a child named `..name` is inside. + return rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel)); +} + +function unique(xs: readonly string[]): string[] { + return [...new Set(xs)]; +} + +/** Codex PreToolUse hook input (hooks/src/schema.rs `PreToolUseCommandInput`). */ +export function hookInput(prepared: PreparedCall, native: NativeCall, ctx: SessionContext, policy: CodexPolicy): Record { + return { + session_id: ctx.sessionId ?? '', + turn_id: ctx.turnId ?? '', + transcript_path: ctx.transcriptPath ?? null, + cwd: native.cwd, + hook_event_name: 'PreToolUse', + model: ctx.model ?? '', + permission_mode: policy.permissionMode, + tool_name: native.toolName, + tool_input: native.toolInput, + tool_use_id: ctx.toolUseId === undefined ? prepared.id : `${ctx.toolUseId}/${prepared.id}`, + }; +} + +/** Builds the bash containment of a sandbox mode. */ +export function containmentFor(mode: SandboxMode, writableRoots: readonly string[], network: boolean): BashContainment { + switch (mode) { + case 'read-only': + return { mode: 'sandbox', readOnly: true, writableRoots: [], network: false }; + case 'workspace-write': + return { mode: 'sandbox', readOnly: false, writableRoots: [...writableRoots], network }; + case 'danger-full-access': + return { mode: 'none' }; + } +} + +export class CodexHostAdapter implements HostAdapter { + readonly host = 'codex' as const; + readonly #opts: CodexHostAdapterOptions; + + constructor(opts: CodexHostAdapterOptions = {}) { + this.#opts = opts; + } + + async loadPolicy(ctx: SessionContext): Promise | PolicyLoadError> { + try { + return this.#load(ctx); + } catch (err) { + if (err instanceof ConfigError || err instanceof RulesParseError) return { error: err.message }; + return { error: `cannot load the Codex configuration: ${err instanceof Error ? err.message : String(err)}` }; + } + } + + #load(ctx: SessionContext): PolicySnapshot { + const io = this.#opts.io ? this.#opts.io(ctx) : nodeConfigIo(parentAwareEnv()); + const config = loadCodexConfig(ctx.cwd, io); + + const rules: PrefixRule[] = []; + for (const file of ruleFiles(config, io)) { + const text = io.readFile(file); + if (text === undefined) throw new ConfigError(`rule file ${file} disappeared while the rules were read`); + rules.push(...parseRulesFile(text, file)); + } + const { hooks, notes: hookNotes } = discoverHooks(config, io); + + // The turn metadata can narrow the sandbox mode, never widen it past the reconstructed policy. + let sandboxMode = config.sandboxMode; + if (ctx.sandboxMode !== undefined) { + const turn = SANDBOX_MODES.find((m) => m === ctx.sandboxMode); + if (turn === undefined) throw new ConfigError(`unknown Codex sandbox mode ${JSON.stringify(ctx.sandboxMode)}`); + if (SANDBOX_MODES.indexOf(turn) < SANDBOX_MODES.indexOf(sandboxMode)) sandboxMode = turn; + } + // The narrowed mode must also be one the requirements allow: else the most permissive allowed mode below it. + const allowed = config.requirements?.allowedSandboxModes; + if (allowed !== undefined && !allowed.includes(sandboxMode)) { + const below = SANDBOX_MODES.slice(0, SANDBOX_MODES.indexOf(sandboxMode)).reverse().find((m) => allowed.includes(m)); + if (below === undefined) throw new ConfigError(`the requirements allow no sandbox mode at most ${sandboxMode}`); + sandboxMode = below; + } + + const tmp = this.#opts.tmpDirs ?? { slashTmp: process.platform === 'win32' ? null : '/tmp', tmpdir: io.env['TMPDIR'] ?? null }; + const tmpRoots = [ + ...(config.excludeSlashTmp || tmp.slashTmp === null ? [] : [tmp.slashTmp]), + ...(config.excludeTmpdirEnvVar || tmp.tmpdir === null || !path.isAbsolute(tmp.tmpdir) ? [] : [tmp.tmpdir]), + ]; + const writableRoots = unique([config.cwd, ...config.writableRoots, ...tmpRoots].map((p) => path.resolve(p))); + const bashContainment = containmentFor(sandboxMode, writableRoots, config.networkAccess); + + const stateDir = this.#opts.stateDir ?? stateDirPath(io.env, io.home); + const homeCodex = path.join(io.home, '.codex'); + // Each protected path also by its canonical destination; a missing one through its nearest existing parent. + const canonical = (p: string): string => { + if (io.exists(p)) return io.realpath(p); + const parent = path.dirname(p); + return parent === p ? p : path.join(canonical(parent), path.basename(p)); + }; + const both = (p: string): string[] => [p, canonical(p)]; + const protectedPaths = unique([ + '**/.codex/**', + ...[config.codexHome, homeCodex, io.systemDir, stateDir].flatMap(both).map((d) => `${d}/**`), + ...[path.join(config.cwd, '.mcp.json'), path.join(config.projectRoot, '.mcp.json')].flatMap(both), + ]); + + return { + host: 'codex', + bashContainment, + protectedPaths, + payload: { + sandboxMode, + approvalPolicy: config.approvalPolicy, + writableRoots: sandboxMode === 'workspace-write' ? writableRoots : [], + rules: { rules }, + hooks, + hooksEnabled: config.hooksEnabled, + permissionMode: config.approvalPolicy === 'never' ? 'bypassPermissions' : 'default', + codexHome: config.codexHome, + notes: [...config.notes, ...hookNotes], + }, + }; + } + + checkStatic(prepared: PreparedCall, _ctx: SessionContext, policy: PolicySnapshot): Decision { + const p = policy.payload; + if (prepared.tool === 'write' || prepared.tool === 'edit') return checkFileWrite(prepared.effect.absPath, p); + const command = shellCommandFor(prepared); + if (command === undefined) return { kind: 'deny', source: 'rule', reason: 'no shell form for this call' }; + return checkShellCommand(command, p); + } + + async authorize(prepared: PreparedCall, ctx: SessionContext, policy: PolicySnapshot, signal: AbortSignal): Promise { + const p = policy.payload; + if (!p.hooksEnabled || p.hooks.length === 0) return { kind: 'allow' }; + // Filter by the tool's names first: no file is read or patch built for a call no hook matches. + const names = prepared.tool === 'write' || prepared.tool === 'edit' ? APPLY_PATCH_NAMES : BASH_NAMES; + if (!p.hooks.some((h) => matcherMatches(h.matcher, names))) return { kind: 'allow' }; + let native: NativeCall; + try { + native = await nativeCall(prepared, ctx, this.#opts.readCurrent); + } catch (err) { + const reason = err instanceof NativeShapeError ? err.message : `cannot build the Codex tool input: ${err instanceof Error ? err.message : String(err)}`; + return { kind: 'deny', source: 'hook-error', reason }; + } + // The patch grammar cannot express every byte sequence (a missing final + // newline, line endings other than the file's first). A hook must not + // approve a change different from the one that would be applied. + if (native.exact === false) { + return { + kind: 'deny', + source: 'unsupported-config', + reason: 'this change cannot be shown to Codex apply_patch hooks exactly (missing final newline or mixed/CRLF line endings the patch format cannot express); write the content with a trailing newline and the file\'s line endings', + }; + } + const result = await runHooks({ + hooks: p.hooks, + names: native.names, + stdin: JSON.stringify(hookInput(prepared, native, ctx, p)), + // Codex starts hooks in the session cwd; the tool's cwd is only in the input. + cwd: ctx.cwd, + env: this.#opts.hookEnv ?? process.env, + platform: process.platform, + signal, + }); + if (result.kind === 'deny') return { kind: 'deny', source: result.source, reason: result.reason }; + if (result.updatedInput === undefined) return { kind: 'allow' }; + const mapped = mapUpdatedInput(prepared, native, result.updatedInput, ctx); + switch (mapped.kind) { + case 'unchanged': + return { kind: 'allow' }; + case 'updated': + return { + kind: 'allow', + updatedArgs: mapped.args, + ...(mapped.bindsPreparedFile ? { bindsPreparedFile: true } : {}), + reason: 'rewritten by a Codex PreToolUse hook', + }; + case 'invalid': + return { kind: 'deny', source: 'hook-error', reason: mapped.reason }; + case 'unsupported': + return { kind: 'deny', source: 'unsupported-config', reason: mapped.reason }; + } + } +} + +/** Static decision for a shell command (exec policy rules plus Codex heuristics). */ +export function checkShellCommand(command: string, p: CodexPolicy): Decision { + let split; + try { + split = splitShellCommands(command); + } catch (err) { + const why = err instanceof ShellParseError ? err.message : String(err); + return { kind: 'deny', source: 'rule', reason: `the command cannot be parsed for the Codex exec policy: ${why}` }; + } + const commands = [...split.commands]; + // Codex evaluates a script it cannot split as the single argv `bash -lc