Repository navigation
fix(codex): materialise API-key auth.json, or every turn 401s (#2208) - #2333
Conversation
Trinity resolved the OpenAI API key and passed it to `codex exec` via the environment only. That is no longer sufficient: the CLI authenticates its `wss://api.openai.com/v1/responses` transport from `$CODEX_HOME/auth.json`, and that transport is no longer toggleable (`responses_websockets` and `..._v2` are listed as *removed* in `codex features list`, so there is no flag back to the HTTP path that did accept a bare env key). Nothing in `startup.sh` or `codex_runtime.py` ever ran `codex login`, so an API-key Codex agent could not complete a single turn — only subscription agents (#1971, which ship their own auth.json) worked. `_materialize_api_key_auth` now runs in `_execute_codex` before the spawn — after would still 401 — shelling out to `codex login --with-api-key` with the key on stdin, never argv. Three properties carry it: * Subscription auth wins (#1971). Only an `auth_mode: apikey` file is overwritten; a `chatgpt` file, or one that will not parse, is left alone. Classification is tri-state (absent / unreadable / parsed) so "no file" and "a file I cannot read" never collapse into "safe to write". * Rotation propagates. Since #1999 the execution env is rebuilt from `.env` per spawn, so the key can change under a live container; a stored key that no longer matches is re-logged-in. Steady state is one small file read per turn, not a subprocess. * It never raises. A login failure logs at ERROR and the turn proceeds to fail with the CLI's own auth error, rather than converting an auth problem into a Trinity 503 on the subscription path too. `_has_subscription_auth` is re-keyed from existence to `auth_mode`. Once Trinity writes an auth.json of its own, an existence test reports every API-key agent as a subscription agent, and the #1971 credential gate would then let a container whose key was REMOVED from `.env` keep running on the stale file it left behind — silent failure of credential revocation, the #1999 class. An auth.json with no `auth_mode` (older CLI) or an unreadable one still counts as a subscription credential, preserving pre-#2208 behaviour exactly: #1971's point is that a bad auth.json surfaces as the CLI's own auth error, not as a Trinity 503 claiming nothing is configured. Verified against a live key on the rebuilt base image (codex 0.147.0), key only in `~/.env` and absent from the container env: patched POST /api/chat -> "PONG" POST /api/task -> "TASKPONG" 0x 401, auth.json auth_mode=apikey, cost recorded unpatched POST /api/chat -> 503 "Codex authentication failure ... 401 Unauthorized", auth.json absent (same image, same key, same container setup; only the module differs). The key appears in no log line and in no argv. Two existing test helpers now neutralize the login spawn: `_install_fake_codex` for the same reason it neutralizes the pgid helpers, and #1971's `_captured_env` because the first Popen it captures would otherwise be the login rather than the turn — asserting credential forwarding against the wrong process. Requires a base-image rebuild; existing Codex agents adopt it on their next cold start via the image-drift predicate (#1809), not on a plain restart.
The requirement documented the exact design the bug is about: the key 'loaded into the subprocess env'. Left as-is it specifies an agent that 401s on every turn.
…ixes (#2208) Found in /review of this PR while verifying its own AC #3 ("the key never appears in argv, logs, or an error body") with a real key. `credential_sanitizer` carried three rules — `sk-[a-zA-Z0-9]{20,}`, `sk-proj-…`, `sk-ant-…`. An OpenAI SERVICE-ACCOUNT key (`sk-svcacct-…`) matched none of them: the generic rule stops at the first hyphen, and the other two are literal prefixes. So the newest key format OpenAI issues was the one format that passed through logs and error bodies in clear text — in both the backend and the agent-server copy. Nothing failed, because a sanitizer that misses returns its input. The only reason it surfaced is that the key on hand happened to be the unlisted kind. One shape-based rule per family replaces the three, so a future variant is covered on arrival rather than after someone notices. Both copies are patched and asserted in the same test (they are separate files with no parity test — a one-sided fix leaves exactly this gap on the other side), parametrized over five variants plus an over-redaction guard: `sk-` is also an ordinary prefix (`sk-SK` locale tags, `sk-42` ticket ids) and the length floor must keep those readable. Also from the same review: * `_materialize_api_key_auth` claimed "never raises" but caught only OSError/ValueError/TimeoutExpired. It runs on the turn path, so anything else escaped into `_execute_codex` and would 500 the turn — including for a subscription agent that needed nothing from the function. Now genuinely total, with a test. * The login spawn snapshotted `{**os.environ}` instead of building its env through `build_execution_env` — the #1999 rule, caught by that issue's own guard test. Re-verified live afterwards, since a dropped PATH there would make `codex` unfindable. * The rotation rationale credited #1999's per-spawn env rebuild; the actual mechanism is `_load_api_key_with_source` re-resolving per turn, and it prefers the process env over `.env`, so `.env` rotation only reaches agents with no baked key. Corrected in the docstring and the flow doc. * `harness-authoring-guide.md` §6 stated the same stale contract FR-5 did ("inject it into the subprocess env", full stop) — that is the doc a future harness author follows. Generalized: check whether the env var is enough, and materialise to disk if the CLI authenticates from its own state file. Deliberately NOT fixed, filed as #2334: a persistently failing `codex login` re-runs every turn (bounded by the 30s timeout). Negative caching must not outlive a corrected `.env`, and the failure is already loud, so the tradeoff deserves its own decision. Learning recorded in docs/memory/learnings.md — prefix-enumerated secret patterns are a blocklist, and the entry you have not heard of is the one that leaks.
|
|
✅ Live-instance integration suite clean when this PR is merged into |
vybe
left a comment
There was a problem hiding this comment.
Validated: Codex API-key auth.json materialisation. All CI green (12145 tests, regression diff clean, prod-image-smoke, non-root, schema-parity). Closing keyword present (Closes #2208). No security findings, no new backend package or env var, no host paths. Merging.
Closes #2208
The bug
Trinity resolved the OpenAI API key and passed it to
codex execvia the environment only. That is no longer sufficient: the CLI authenticates itswss://api.openai.com/v1/responsestransport from$CODEX_HOME/auth.json, and that transport is no longer toggleable (responses_websockets/..._v2are listed as removed incodex features list). Nothing instartup.shorcodex_runtime.pyever rancodex login, so an API-key Codex agent could not complete a single turn — only subscription agents (#1971, which ship their ownauth.json) worked.The fix
_materialize_api_key_authruns in_execute_codexbefore the spawn — after would still 401 — shelling out tocodex login --with-api-keywith the key on stdin, never argv.Three properties carry it:
auth_mode: apikeyfile is overwritten. Achatgptfile, or one that will not parse, is left alone. Classification is tri-state (absent/unreadable/parsed) so "no file" and "a file I cannot read" never collapse into "safe to write"..envinto the agent-server long-lived process env — a removed key keeps reaching every execution, invisible to /proc and docker exec #1999 the execution env is rebuilt from.envper spawn, so the key can change under a live container; a stored key that no longer matches is re-logged-in. Steady state is one small file read per turn, not a subprocess.The second defect, created by the first fix
_has_subscription_authwas an existence test. Once Trinity writes anauth.jsonof its own, that reports every API-key agent as a subscription agent — and the #1971 credential gate would then let a container whose key was removed from.envkeep running on the stale file it left behind: silent failure of credential revocation, the #1999 class. It is now keyed onauth_mode.An
auth.jsonwith noauth_mode(older CLI), or an unreadable one, still counts as a subscription credential — preserving pre-#2208 behaviour exactly. #1971's point is that a badauth.jsonsurfaces as the CLI's own auth error, not as a Trinity 503 claiming nothing is configured.Verification
Live OpenAI key, rebuilt base image (codex 0.147.0), key present only in
~/.envand absent from the container env — i.e. AC #1's setup:POST /api/chatPOST /api/taskauth.json"PONG""TASKPONG"auth_mode=apikey, cost recordedorigin/dev(unpatched)Codex authentication failure … 401 UnauthorizedSame image, same key, same container setup; only the module differs. The key appears in no log line and in no argv.
Isolated A/B on the CLI itself, model held constant, only
auth.jsondiffering — reproduced on both pinned versions, matching the issue's own table:Unit:
tests/unit/test_codex_runtime.py+14 tests (mode classification, subscription/unclassifiable preservation, rotation, idempotence, stdin-not-argv, failure logs without the key, and login-before-spawn ordering).695 passed, 4 skippedacross the codex / agent_server / vendor-parity selection.Notes for review
_install_fake_codex(same reason it neutralizes the pgid helpers — there is no real codex binary) and codex_runtime.py unconditionally sets CODEX_API_KEY, which makes the Codex CLI discard a valid subscription auth.json #1971's_captured_env, where the firstPopencaptured would otherwise be the login rather than the turn, asserting credential forwarding against the wrong process.auth.json: the file format is undocumented, and--api-keyis removed in current versions, so the ticket's--with-api-keystdin form is the stable seam.startup.sh. Lazy-in-runtime was chosen instead — it also covers a wipedCODEX_HOMEand key rotation, and keeps one writer rather than two.gpt-5.1-codex404s on/v1/responsesfor API-key callers — the thing bug: Codex runtime pins a retired model and mis-estimates cost for every current GPT-5.x model #2207 explicitly left unverified ("treat the pin as suspect until a real turn proves otherwise"). Already moot ondev: bug: Codex runtime pins a retired model and mis-estimates cost for every current GPT-5.x model #2207 shippedgpt-5.6-sol, andget_default_model()only feeds the context-window fallback, never-m. Recorded here so the question is closed rather than re-opened later.