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
68 changes: 68 additions & 0 deletions docs/plans/2026-11-27-proxy-resilience.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Plan: Bulletproof Claude & Codex Proxy Resilience

Fixes #1552

## Problem

Agent Code optionally routes Claude (via per-session `mitmdump`) and Codex (via local `ResponsesProxy`) through local proxies to obtain richer semantic streaming events. Today both proxy paths fail closed or misconfigure user environments in common real-world setups:

1. **Claude (`ClaudeSession`)**
- Unconditionally spawns `mitmdump` when `useProxy: true` even when the user's environment is incompatible (corporate `HTTPS_PROXY`/`HTTP_PROXY`, non-Anthropic cloud backends like Bedrock/Vertex/Foundry, or a local/plain-HTTP `ANTHROPIC_BASE_URL`).
- Overwrites user `NO_PROXY`/`no_proxy` instead of merging loopback hosts, breaking internal/corporate bypass lists.
- Overwrites user `NODE_EXTRA_CA_CERTS` instead of merging the user's CA bundle with the mitmproxy CA cert, breaking corporate TLS roots.
- Fails closed if `resolveBundledTool('mitmdump')`, `createProxyServer`, or `proxy.start()` throws, aborting Claude spawn instead of degrading to direct spawn.
2. **Codex (`CodexSession`)**
- Unconditionally starts `ResponsesProxy` when `useProxy: true` even when a corporate proxy env var is set (Node's `fetch()` in `ResponsesProxy` ignores `HTTPS_PROXY`), when `$CODEX_HOME/config.toml` sets a non-`openai` `model_provider`, or when auth mode cannot be determined (e.g. macOS Keychain / `keyring` / `auto` store or not-yet-logged-in user, where guessing `api.openai.com` causes 401s).
- Does not honor `openai_base_url` from `$CODEX_HOME/config.toml` or `OPENAI_BASE_URL` when forwarding upstream, nor preserve/merge `NO_PROXY`/`no_proxy` with loopback hosts.
- Fails closed if `allocateProxyEventsFile` or `ResponsesProxy.create` throws, aborting Codex spawn instead of spawning directly.
3. **Terminal-mode panes (`session.ts` & `rehydrate.ts`)**
- Passes `useProxy: true` even when the pane's effective view mode (`meta?.agentViewModeOverride ?? settings.agentViewMode`) is hard `'terminal'`, spinning up unnecessary proxy processes for raw-PTY panes.

## Scope & Design

All changes live in the main `agent-code` repository (`src/`) so this lands as a single PR without modifying git submodules.

### 1. Shared proxy environment hygiene (`src/providers/shared/runtime/proxyEnv.ts`)
- `hasCorporateProxyEnv(env)` — detects non-empty `HTTPS_PROXY`, `https_proxy`, `HTTP_PROXY`, or `http_proxy`.
- `mergeNoProxy(env, requiredHosts)` — merges `localhost,127.0.0.1,::1` into any existing `NO_PROXY` / `no_proxy` entries without duplicates or clobbering.

### 2. Claude fail-open & env hygiene (`src/providers/claude/runtime/claudeProxyPolicy.ts`, `claudeSession.ts`)
- `evaluateClaudeProxyCompatibility(cleanEnv)` skips local mitmproxy when:
- corporate proxy env vars are set;
- `CLAUDE_CODE_USE_BEDROCK`, `CLAUDE_CODE_USE_VERTEX`, or `CLAUDE_CODE_USE_FOUNDRY` is truthy;
- `ANTHROPIC_BASE_URL` uses `http://` or targets loopback (`localhost`, `127.0.0.1`, `::1`, `[::1]`, `*.localhost`).
- `buildClaudeProxyEnv(cleanEnv, proxyInfo)` merges `NO_PROXY`/`no_proxy` and, when `cleanEnv.NODE_EXTRA_CA_CERTS` is set, combines it with `proxyInfo.caCertPath` into `combined-extra-ca-certs.pem` inside `proxyInfo.workDir` (throwing on unreadable/unwritable paths so the fail-open wrapper falls back cleanly).
- `ClaudeSession.start()` wraps proxy resolution, creation, startup, and env construction in `try/catch`; on any failure it tears down any started proxy, logs a warning, emits a non-fatal `transcript-diagnostic`, sets `effectiveUseProxy = false`, and spawns Claude directly without the proxy.

### 3. Codex fail-open & config/auth/env hygiene (`src/providers/codex/runtime/codexProxyPolicy.ts`, `codexSession.ts`)
- `resolveCodexProxyDecision(cleanEnv)` inspects `cleanEnv`, `$CODEX_HOME/config.toml` (parsed via `@iarna/toml`), and `$CODEX_HOME/auth.json` before starting `ResponsesProxy`:
- Skips if corporate proxy env vars are set.
- Skips if `config.toml` sets `model_provider` to anything other than `"openai"`, sets `profile`, sets `chatgpt_base_url`, sets `cli_auth_credentials_store = "keyring"`, or cannot be parsed.
- Uses `config.toml`'s `openai_base_url` as `upstreamBaseUrl` after validating it as an `http:`/`https:` URL (does NOT consult `env.OPENAI_BASE_URL`, which Codex CLI TUI ignores).
- Otherwise inspects `$CODEX_HOME/auth.json` only (does NOT infer `apikey` from `env.OPENAI_API_KEY`, which Codex CLI TUI ignores and which would misroute Keychain ChatGPT users):
- ChatGPT-family `auth_mode` (`chatgpt`, `chatgptAuthTokens`, `headers`, `agentIdentity`, `personalAccessToken`) or `tokens` without `OPENAI_API_KEY` → `authMode: 'chatgpt'`.
- `auth_mode === 'apikey'` or `OPENAI_API_KEY` present in `auth.json` → `authMode: 'apikey'`.
- Otherwise (missing/indeterminate auth, e.g., Keychain/keyring or not logged in) → skip proxy.
- When `ResponsesProxy` is used, merges `localhost,127.0.0.1,::1` into `cleanEnv.NO_PROXY` and `cleanEnv.no_proxy`.
- Wraps `resolveCodexProxyDecision`, `allocateProxyEventsFile`, and `ResponsesProxy.create` in `try/catch`; on any failure stops any locally created proxy, re-checks `isStartAttemptActive(attempt)` before mutating shared fields or falling through to `ptySpawn`, logs a warning, emits a non-fatal `transcript-diagnostic`, omits `--config openai_base_url=...`, and spawns Codex directly.

### 4. Skip proxy for Terminal-mode panes (`agentDisplayMode.ts`, `session.ts`, `rehydrate.ts`)
- Add `shouldUseProxyForSession({ kind, useProxyStreaming, globalMode, override })` in `src/renderer/src/workspace/agentDisplayMode.ts`: returns `false` when `resolveConfiguredAgentViewMode(globalMode, override) === 'terminal'`.
- Wire it into `spawn`, `ensureSessionLive`, `reloadAgentSessions` in `src/renderer/src/workspace/hook/actions/session.ts` and `rehydrateWorkspace` in `src/renderer/src/workspace/hook/persistence/rehydrate.ts`.

### 5. Verification
- Fail-first unit tests for:
- `proxyEnv.ts` (`hasCorporateProxyEnv`, `mergeNoProxy`)
- `claudeProxyPolicy.ts` (env compatibility, CA cert merging, unreadable CA fallback) and `ClaudeSession` fail-open direct spawn
- `codexProxyPolicy.ts` (corporate proxy, `config.toml` `model_provider` & `openai_base_url`, `OPENAI_BASE_URL`, `auth.json` modes, indeterminate auth skip) and `CodexSession` fail-open direct spawn
- `shouldUseProxyForSession` and terminal-mode proxy suppression in renderer session actions / rehydrate
- `npm run typecheck` and targeted vitest suites.

## Review Disposition

| Finding | Severity | Disposition | Resolution |
| --- | --- | --- | --- |
| Cancelled `CodexSession` start attempt could clear a newer generation's `proxyServer` or fall through to `ptySpawn` in the proxy `catch` block | Blocking | Fixed | Stop any locally created proxy, return early when `!this.isStartAttemptActive(attempt)` before touching `this.proxyServer` / emitting `codex-proxy-fallback` / spawning PTY, and clear `this.proxyServer` only by identity match (`codexSession.ts`). Added regression test. |
| `codexProxyPolicy` consulted `env.OPENAI_BASE_URL` and `env.OPENAI_API_KEY`, which Codex CLI TUI ignores (risking 401s for Keychain ChatGPT users who export `OPENAI_API_KEY` for other tools) | Blocking | Fixed | Removed `env.OPENAI_BASE_URL` and `env.OPENAI_API_KEY` inference from `resolveCodexProxyDecision` (`codexProxyPolicy.ts`). Updated unit tests. |
| Validate `config.toml` `openai_base_url` and skip proxy on `profile`, `chatgpt_base_url`, or `cli_auth_credentials_store = "keyring"` | Non-blocking | Fixed | Added `http:`/`https:` URL validation and conservative skips for `profile`, `chatgpt_base_url`, and `keyring` store (`codexProxyPolicy.ts`). Added unit tests. |
| Stale comment on `ClaudeSessionEvents['transcript-diagnostic']` claiming Claude never emits diagnostics | Non-blocking | Fixed | Updated comment in `claudeSession.ts` to document non-fatal proxy skip/fallback diagnostics. |
306 changes: 306 additions & 0 deletions src/providers/claude/runtime/claudeProxyPolicy.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,306 @@
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { hasCorporateProxyEnv, mergeNoProxy } from '@providers/shared/runtime/proxyEnv.js'
import {
buildClaudeProxyEnv,
evaluateClaudeProxyCompatibility,
} from './claudeProxyPolicy.js'
import { ClaudeSession } from './claudeSession.js'

const harness = vi.hoisted(() => ({
ptySpawns: [] as Array<{ binary: string; args: string[]; env: Record<string, string> }>,
headlessOptions: [] as Array<Record<string, unknown>>,
proxyCreateCalls: 0,
proxyCreateBehavior: 'ok' as 'ok' | 'throw-create' | 'throw-start',
proxyStopped: 0,
proxyWorkDir: '',
proxyCaCertPath: '',
}))

vi.mock('node-pty', () => ({
spawn: (binary: string, args: string[], opts: { env: Record<string, string> }) => {
harness.ptySpawns.push({ binary, args, env: { ...opts.env } })
return {
pid: 4242,
process: binary,
write: () => undefined,
resize: () => undefined,
kill: () => undefined,
onData: () => ({ dispose: () => undefined }),
onExit: () => ({ dispose: () => undefined }),
}
},
}))

vi.mock('@main/setup/runtimeTools.js', () => ({
resolveBundledTool: async () => '/fake/mitmdump',
}))

vi.mock('@main/setup/toolchain.js', () => ({
getToolPath: () => null,
}))

vi.mock('@main/proxy/mitmproxyReaper.js', () => ({
MITMPROXY_SHARED_CONF_DIR: '/fake/mitmproxy-conf',
stopProxyServerWithDeadline: async (proxy: { stop: () => Promise<void> }) => {
await proxy.stop()
return { outcome: 'stopped', processes: [] }
},
}))

vi.mock('claude-code-headless', async () => {
const { EventEmitter } = await import('node:events')
const { join: pathJoin } = await import('node:path')
class FakeClaudeCodeHeadless extends EventEmitter {
semantic = new EventEmitter()
committed = new EventEmitter()

constructor(options: Record<string, unknown>) {
super()
harness.headlessOptions.push(options)
}

async start() {
return { projectDir: '/fake/project-dir' }
}
async stop() {}
getSlashPickerState() { return { visible: false, items: [] } }
getConditionSnapshot() { return { provider: 'claude', conditions: {}, ts: 0 } }
getComposerState() { return { kind: 'empty' } }
getScreen() { return '' }
getScreenMarkdown() { return '' }
getComposerAttributes() { return null }
ingestProxyEvent() {}
noteProxyTransportGap() {}
}

return {
ClaudeCodeHeadless: FakeClaudeCodeHeadless,
createProxyServer: async () => {
harness.proxyCreateCalls += 1
if (harness.proxyCreateBehavior === 'throw-create') {
throw new Error('mitmdump binary missing')
}
const emitter = new EventEmitter()
return Object.assign(emitter, {
info: {
workDir: harness.proxyWorkDir,
confDir: '/fake/mitmproxy-conf',
mitmDumpPath: '/fake/mitmdump',
proxyPort: 18080,
proxyUrl: 'http://127.0.0.1:18080',
addonPath: '/fake/addon.py',
eventsFile: pathJoin(harness.proxyWorkDir, 'proxy-events.jsonl'),
caCertPath: harness.proxyCaCertPath,
},
start: async () => {
if (harness.proxyCreateBehavior === 'throw-start') {
throw new Error('mitmdump failed to bind port')
}
},
stop: async () => {
harness.proxyStopped += 1
},
})
},
}
})

describe('shared proxy env hygiene', () => {
it('detects corporate proxy env vars across upper and lower case', () => {
expect(hasCorporateProxyEnv({})).toBe(false)
expect(hasCorporateProxyEnv({ HTTPS_PROXY: ' ' })).toBe(false)
expect(hasCorporateProxyEnv({ HTTPS_PROXY: 'http://corp:8080' })).toBe(true)
expect(hasCorporateProxyEnv({ https_proxy: 'http://corp:8080' })).toBe(true)
expect(hasCorporateProxyEnv({ HTTP_PROXY: 'http://corp:8080' })).toBe(true)
expect(hasCorporateProxyEnv({ http_proxy: 'http://corp:8080' })).toBe(true)
})

it('merges loopback hosts into existing NO_PROXY and no_proxy without clobbering or duplicating', () => {
expect(mergeNoProxy({})).toBe('localhost,127.0.0.1,::1')
expect(
mergeNoProxy({
NO_PROXY: 'internal.corp, 10.0.0.0/8, LOCALHOST',
no_proxy: 'internal.corp, .svc.local',
}),
).toBe('internal.corp,10.0.0.0/8,LOCALHOST,.svc.local,127.0.0.1,::1')
})
})

describe('evaluateClaudeProxyCompatibility', () => {
it('allows default clean environments', () => {
expect(evaluateClaudeProxyCompatibility({ PATH: '/usr/bin' })).toEqual({ allow: true })
})

it.each(['HTTPS_PROXY', 'https_proxy', 'HTTP_PROXY', 'http_proxy'])(
'skips proxy when %s is set',
key => {
const decision = evaluateClaudeProxyCompatibility({ [key]: 'http://proxy.corp:8080' })
expect(decision.allow).toBe(false)
if (!decision.allow) expect(decision.reason).toBe('corporate-proxy-env')
},
)

it.each(['CLAUDE_CODE_USE_BEDROCK', 'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY'])(
'skips proxy when %s is truthy and allows when explicitly falsy',
key => {
const truthy = evaluateClaudeProxyCompatibility({ [key]: '1' })
expect(truthy.allow).toBe(false)
if (!truthy.allow) expect(truthy.reason).toBe('non-anthropic-backend')

expect(evaluateClaudeProxyCompatibility({ [key]: '0' })).toEqual({ allow: true })
expect(evaluateClaudeProxyCompatibility({ [key]: 'false' })).toEqual({ allow: true })
},
)

it('skips proxy for plain-HTTP or loopback ANTHROPIC_BASE_URL', () => {
for (const url of [
'http://litellm.internal:4000',
'https://localhost:8443/v1',
'https://127.0.0.1:8443',
'https://[::1]:8443',
]) {
const decision = evaluateClaudeProxyCompatibility({ ANTHROPIC_BASE_URL: url })
expect(decision.allow).toBe(false)
if (!decision.allow) expect(decision.reason).toBe('local-or-http-base-url')
}
expect(
evaluateClaudeProxyCompatibility({ ANTHROPIC_BASE_URL: 'https://api.anthropic.com' }),
).toEqual({ allow: true })
})
})

describe('buildClaudeProxyEnv', () => {
let tempDir: string

beforeEach(async () => {
tempDir = await mkdtemp(join(tmpdir(), 'claude-proxy-env-'))
})

afterEach(async () => {
await rm(tempDir, { recursive: true, force: true })
})

it('merges user NODE_EXTRA_CA_CERTS with mitmproxy CA into workDir and preserves NO_PROXY', async () => {
const userCa = join(tempDir, 'corp-ca.pem')
const mitmCa = join(tempDir, 'mitm-ca.pem')
await writeFile(userCa, '-----BEGIN CERTIFICATE-----\nCORP\n-----END CERTIFICATE-----', 'utf8')
await writeFile(mitmCa, '-----BEGIN CERTIFICATE-----\nMITM\n-----END CERTIFICATE-----\n', 'utf8')

const env = await buildClaudeProxyEnv(
{
NO_PROXY: 'corp.local',
NODE_EXTRA_CA_CERTS: userCa,
},
{
proxyUrl: 'http://127.0.0.1:18080',
caCertPath: mitmCa,
workDir: tempDir,
},
)

expect(env.NO_PROXY).toBe('corp.local,localhost,127.0.0.1,::1')
expect(env.no_proxy).toBe('corp.local,localhost,127.0.0.1,::1')
expect(env.NODE_EXTRA_CA_CERTS).toBe(join(tempDir, 'combined-extra-ca-certs.pem'))
const merged = await readFile(env.NODE_EXTRA_CA_CERTS, 'utf8')
expect(merged).toContain('CORP')
expect(merged).toContain('MITM')
})

it('throws when user NODE_EXTRA_CA_CERTS is unreadable so caller can fail open', async () => {
const mitmCa = join(tempDir, 'mitm-ca.pem')
await writeFile(mitmCa, '-----BEGIN CERTIFICATE-----\nMITM\n-----END CERTIFICATE-----\n', 'utf8')

await expect(
buildClaudeProxyEnv(
{ NODE_EXTRA_CA_CERTS: join(tempDir, 'does-not-exist.pem') },
{ proxyUrl: 'http://127.0.0.1:18080', caCertPath: mitmCa, workDir: tempDir },
),
).rejects.toThrow()
})
})

describe('ClaudeSession proxy fail-open', () => {
let tempDir: string

beforeEach(async () => {
tempDir = await mkdtemp(join(tmpdir(), 'claude-session-proxy-'))
harness.ptySpawns = []
harness.headlessOptions = []
harness.proxyCreateCalls = 0
harness.proxyCreateBehavior = 'ok'
harness.proxyStopped = 0
harness.proxyWorkDir = tempDir
harness.proxyCaCertPath = join(tempDir, 'mitm-ca.pem')
await writeFile(harness.proxyCaCertPath, '-----BEGIN CERTIFICATE-----\nMITM\n-----END CERTIFICATE-----\n', 'utf8')
})

afterEach(async () => {
await rm(tempDir, { recursive: true, force: true })
})

it('falls back to direct spawn without aborting when proxy.start() throws', async () => {
harness.proxyCreateBehavior = 'throw-start'
const session = new ClaudeSession({
cwd: tempDir,
useProxy: true,
env: { HTTPS_PROXY: undefined, https_proxy: undefined, HTTP_PROXY: undefined, http_proxy: undefined },
})
const diagnostics: unknown[] = []
const started: Array<{ projectDir: string; proxyUrl?: string }> = []
session.on('transcript-diagnostic', d => diagnostics.push(d))
session.on('started', s => started.push(s))

await session.start()

expect(harness.proxyCreateCalls).toBe(1)
expect(harness.proxyStopped).toBe(1)
expect(harness.ptySpawns).toHaveLength(1)
expect(harness.ptySpawns[0].env.HTTPS_PROXY).toBeUndefined()
expect(harness.headlessOptions[0].proxy).toBeUndefined()
expect(started).toEqual([{ projectDir: '/fake/project-dir', proxyUrl: undefined }])
expect(diagnostics.length).toBeGreaterThan(0)
})

it('tears down proxy and falls back to direct spawn when user NODE_EXTRA_CA_CERTS is unreadable', async () => {
const session = new ClaudeSession({
cwd: tempDir,
useProxy: true,
env: {
HTTPS_PROXY: undefined,
https_proxy: undefined,
HTTP_PROXY: undefined,
http_proxy: undefined,
NODE_EXTRA_CA_CERTS: join(tempDir, 'missing.pem'),
},
})

await session.start()

expect(harness.proxyCreateCalls).toBe(1)
expect(harness.proxyStopped).toBe(1)
expect(harness.ptySpawns).toHaveLength(1)
expect(harness.ptySpawns[0].env.HTTPS_PROXY).toBeUndefined()
expect(harness.ptySpawns[0].env.NODE_EXTRA_CA_CERTS).toBe(join(tempDir, 'missing.pem'))
expect(harness.headlessOptions[0].proxy).toBeUndefined()
})

it('skips creating mitmproxy altogether when corporate HTTPS_PROXY is already set', async () => {
const session = new ClaudeSession({
cwd: tempDir,
useProxy: true,
env: { HTTPS_PROXY: 'http://corp-proxy:8080' },
})

await session.start()

expect(harness.proxyCreateCalls).toBe(0)
expect(harness.ptySpawns).toHaveLength(1)
expect(harness.ptySpawns[0].env.HTTPS_PROXY).toBe('http://corp-proxy:8080')
expect(harness.headlessOptions[0].proxy).toBeUndefined()
})
})
Loading
Loading