Skip to content

fix(codex): materialise API-key auth.json, or every turn 401s (#2208) - #2333

Merged
vybe merged 3 commits into
devfrom
feature/2208-codex-auth-json
Aug 21, 2026
Merged

vybe merged 3 commits into
devfrom
feature/2208-codex-auth-json

Conversation

@obasilakis

Copy link
Copy Markdown
Contributor

Closes #2208

The bug

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 / ..._v2 are listed as removed in codex features list). 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.

The fix

_materialize_api_key_auth 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:

The second defect, created by the first fix

_has_subscription_auth was an existence test. Once Trinity writes an auth.json of 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 .env keep running on the stale file it left behind: silent failure of credential revocation, the #1999 class. It is now keyed on auth_mode.

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.

Verification

Live OpenAI key, rebuilt base image (codex 0.147.0), key present only in ~/.env and absent from the container env — i.e. AC #1's setup:

module POST /api/chat POST /api/task 401s auth.json
patched "PONG" "TASKPONG" 0 auth_mode=apikey, cost recorded
origin/dev (unpatched) 503 Codex authentication failure … 401 Unauthorized — present absent

Same 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.json differing — reproduced on both pinned versions, matching the issue's own table:

codex 0.139.0, gpt-5.3-codex   A) no auth.json → exit=1, 401s=18   B) after login → exit=0, PONG
codex 0.147.0, gpt-5.6-sol     A) no auth.json → exit=1, 401s=19   B) after login → exit=0, PONG

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 skipped across the codex / agent_server / vendor-parity selection.

Notes for review

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.
@obasilakis

Copy link
Copy Markdown
Contributor Author

/review pass — findings and what changed

Ran the pre-landing review after opening this PR. It found one credential-exposure defect and four smaller items; all but one are fixed here, the remaining one is filed as #2334.

Critical — sk-svcacct- keys were not redacted

credential_sanitizer (both the backend and agent-server copies) carried three rules: sk-[a-zA-Z0-9]{20,}, sk-proj-…, sk-ant-…. An OpenAI service-account key matched none — the generic rule stops at the first hyphen, the other two are literal prefixes. Proven, not inferred:

LEAKED   sk-svcacct-AAA...
REDACTED sk-proj-BBBBBB...
REDACTED sk-CCCCCCCCCCC...
REDACTED sk-ant-DDDDDDD...

Pre-existing and independent of the auth fix, but it is precisely this issue's AC #3 ("the key never appears in argv, logs, or an error body"), and _login_with_api_key promises "sanitized, never the key". Replaced with one shape-based rule per family in both copies, 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 has to keep those readable.

Also fixed

Filed, not fixed

#2334 — a persistently failing codex login re-runs on every turn, up to the 30s timeout each time. Negative caching must not outlive a corrected .env, and the failure is already loud (ERROR per attempt), so the tradeoff is its own decision rather than a drive-by here.

Test state

11,724 passed on the branch. The failure set is identical to clean origin/dev (26 pre-existing, incl. the test_736_a2a_outbound_edges IPv6 group and the known test_subscription_auto_switch_pingpong ordering errors, #1846) — verified by diffing both runs rather than eyeballing, after two genuine regressions from this branch showed up in that diff and were fixed (the two above).

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.

@github-actions

Copy link
Copy Markdown

✅ Live-instance integration suite clean when this PR is merged into dev (head_sha: 900e5e6d26c0c6a92e62908394cb83f12efbba72).

@vybe vybe left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants