Skip to content

Keep Codex subscription runs from inheriting API keys - #73063

Merged
steipete merged 7 commits into
mainfrom
codex/codex-app-server-clear-env
Apr 27, 2026
Merged

steipete merged 7 commits into
mainfrom
codex/codex-app-server-clear-env

Conversation

@pashpashpash

@pashpashpash pashpashpash commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Some OpenClaw installs need OPENAI_API_KEY in the Gateway environment for embeddings, PI, or direct OpenAI model calls, while native Codex app-server turns should use the user's Codex or ChatGPT subscription login. Before this, the stdio Codex child inherited the Gateway environment by default, so a shared key could silently steer Codex runs onto Platform API billing.

This keeps the public appServer.clearEnv knob, but makes the common switch automatic. OpenClaw now selects Codex app-server auth in the same shape users expect from /models: an explicit OpenClaw Codex auth profile first, then the app-server's existing account such as a local Codex CLI ChatGPT sign-in, then CODEX_API_KEY and OPENAI_API_KEY only for local stdio app-server fallback when no account is available and the app-server still needs OpenAI auth.

When the selected Codex auth is subscription-style OAuth or token auth, OpenClaw removes both CODEX_API_KEY and OPENAI_API_KEY from the spawned Codex child process. Explicit Codex API-key profiles and local no-account env fallback still use app-server login, so users who intentionally want Codex on API-key auth can choose that path without relying on accidental env inheritance. WebSocket app-server connections do not receive Gateway env API-key fallback, and local fallback reads the same effective stdio environment after appServer.env and appServer.clearEnv have been applied.

The shared-client key uses a process-local HMAC for app-server environment values and auth tokens, so internal env overrides still produce distinct clients without putting raw values or reusable secret fingerprints into the key string. The stdio env merge now uses a null-prototype map and ignores prototype-polluting keys. The auth bridge and stdio transport coverage now exercise local/default subscription auth, explicit OAuth and token profiles, explicit API-key profiles, local stdio env fallback, effective env clearing, existing app-server accounts, websocket connections, and child-process env clearing.

The user story this needs to protect is simple: a user keeps a real OPENAI_API_KEY in the OpenClaw Gateway environment because some features should use Platform billing, then switches their OpenAI model runtime to Codex because they expect ChatGPT or Codex subscription auth. Their Codex turns should not silently start spending through the inherited Gateway key. At the same time, a user who explicitly chooses PI or an API-key Codex profile should still get API-key behavior.

I proved that story with a live end-to-end smoke on this branch. I used real OpenClaw agent turns, not just unit tests or source inspection, and shaped the smoke as a positive control, a negative control, and then the Codex target case.

First, PI with a validated OpenAI Platform key succeeded:

OPENAI_API_KEY=<valid> OPENCLAW_AGENT_RUNTIME=pi node scripts/run-node.mjs agent --agent main --session-id smoke-pi-20260427193445-69302 --model openai/gpt-5.4 --thinking low --message "Reply with exactly OPENCLAW_PI_SMOKE_20260427193445-69302 and nothing else." --local --json

The result was a successful agent turn. The JSON metadata reported agentHarnessId: "pi", provider openai, model gpt-5.4, and the assistant returned exactly OPENCLAW_PI_SMOKE_20260427193445-69302.

Second, PI with a deliberately bogus API key failed the way it should:

OPENAI_API_KEY=sk-invalid-openclaw-smoke-... OPENCLAW_AGENT_RUNTIME=pi node scripts/run-node.mjs agent --agent main --session-id smoke-pi-invalid-20260427193647-70546 --model openai/gpt-5.4 --thinking low ... --local --json

That run exited with 401 Incorrect API key provided. This is the control that proves PI was genuinely using the env API-key route, not some already-authenticated local subscription path.

Third, Codex with the same kind of bogus env keys succeeded:

OPENAI_API_KEY=sk-invalid-openclaw-smoke-... CODEX_API_KEY=sk-invalid-openclaw-smoke-... OPENCLAW_AGENT_RUNTIME=codex node scripts/run-node.mjs agent --agent main --session-id smoke-codex-20260427193718-70903 --model openai/gpt-5.4 --thinking low --message "Reply with exactly OPENCLAW_CODEX_SMOKE_20260427193718-70903 and nothing else." --local --json

The result was a successful Codex agent turn. The JSON metadata reported agentHarnessId: "codex", provider openai, model gpt-5.4, and the assistant returned exactly OPENCLAW_CODEX_SMOKE_20260427193718-70903. The Codex sidecar recorded a real Codex thread id, 019dd14e-1df2-72e0-a494-7b1565d13412. The harness auth home reported auth_mode: "chatgpt" with no stored OpenAI API key, and codex login status for that same harness auth home reported Logged in using ChatGPT.

That is the important falsifiable proof: the same bogus env key that breaks PI does not break Codex on this branch. PI still uses API-key auth when told to, while Codex subscription auth no longer inherits Gateway API-key billing by accident.

I am confident this covers the user story because the smoke first proves the parent env key can make a real OpenAI turn succeed or fail through PI, then proves Codex survives the same poisoned parent env while using ChatGPT subscription auth. The current PR head has the same Codex runtime and auth codepaths as the live-smoked implementation; the later rebase only changed docs/changelog wording and added the boundary test fix that made the refreshed CI lane green.

Fixes #73057.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: codex size: S maintainer Maintainer-authored PR labels Apr 27, 2026
@greptile-apps

greptile-apps Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR exposes the previously internal env and clearEnv fields on appServer through the public Codex plugin config schema, Zod validator, and plugin manifest, enabling users to supply per-process environment overrides and strip inherited secrets (e.g. OPENAI_API_KEY) from the spawned stdio app-server child.

  • P1 — credential leak in cache key: codexAppServerStartOptionsKey embeds env values verbatim in the deduplication string. authToken is already SHA-256-hashed in the same function for exactly this reason; the same treatment is needed for env values, which the PR's own documented use-case fills with sensitive API keys.

Confidence Score: 3/5

Not safe to merge until env values are hashed in codexAppServerStartOptionsKey the same way authToken is.

A single P1 security finding — sensitive env values (like the advertised OPENAI_API_KEY) appear in plaintext in a string that may be logged or surfaced in diagnostics — prevents a clean merge. The rest of the implementation (schema, normalization, tests, docs) is solid.

extensions/codex/src/app-server/config.ts — specifically codexAppServerStartOptionsKey

Security Review

  • Credential leakage via cache key (config.ts, codexAppServerStartOptionsKey): env values are embedded in plaintext in the deduplication key. The advertised use-case (OPENAI_API_KEY in appServer.env) means a real secret would appear verbatim in the stringified key, matching the risk pattern already guarded against for authToken (which is SHA-256-hashed). If the key reaches logs or diagnostics the secret leaks.

Comments Outside Diff (1)

  1. extensions/codex/src/app-server/config.ts, line 312-313 (link)

    P1 security Env values appear in plaintext in the cache key

    authToken is SHA-256-hashed before being embedded in the start-options key (see hashSecretForKey), but env values are included verbatim. The PR's own use-case — and the docs example — is storing a sensitive OPENAI_API_KEY inside appServer.env. If codexAppServerStartOptionsKey is ever written to logs, telemetry, or diagnostic output, that secret is exposed in cleartext.

    The values should be hashed with the same helper, or the entire env record should be hashed as a unit:

    env: Object.entries(options.env ?? {})
      .toSorted(([left], [right]) => left.localeCompare(right))
      .map(([k, v]) => [k, hashSecretForKey(v)]),
    clearEnv: [...(options.clearEnv ?? [])].toSorted(),
    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: extensions/codex/src/app-server/config.ts
    Line: 312-313
    
    Comment:
    **Env values appear in plaintext in the cache key**
    
    `authToken` is SHA-256-hashed before being embedded in the start-options key (see `hashSecretForKey`), but `env` values are included verbatim. The PR's own use-case — and the docs example — is storing a sensitive `OPENAI_API_KEY` inside `appServer.env`. If `codexAppServerStartOptionsKey` is ever written to logs, telemetry, or diagnostic output, that secret is exposed in cleartext.
    
    The values should be hashed with the same helper, or the entire `env` record should be hashed as a unit:
    
    ```typescript
    env: Object.entries(options.env ?? {})
      .toSorted(([left], [right]) => left.localeCompare(right))
      .map(([k, v]) => [k, hashSecretForKey(v)]),
    clearEnv: [...(options.clearEnv ?? [])].toSorted(),
    ```
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/codex/src/app-server/config.ts
Line: 312-313

Comment:
**Env values appear in plaintext in the cache key**

`authToken` is SHA-256-hashed before being embedded in the start-options key (see `hashSecretForKey`), but `env` values are included verbatim. The PR's own use-case — and the docs example — is storing a sensitive `OPENAI_API_KEY` inside `appServer.env`. If `codexAppServerStartOptionsKey` is ever written to logs, telemetry, or diagnostic output, that secret is exposed in cleartext.

The values should be hashed with the same helper, or the entire `env` record should be hashed as a unit:

```typescript
env: Object.entries(options.env ?? {})
  .toSorted(([left], [right]) => left.localeCompare(right))
  .map(([k, v]) => [k, hashSecretForKey(v)]),
clearEnv: [...(options.clearEnv ?? [])].toSorted(),
```

How can I resolve this? If you propose a fix, please make it concise.

---

This is a comment left during a code review.
Path: docs/plugins/codex-harness.md
Line: 543-544

Comment:
**`env`/`clearEnv` only take effect for stdio transport**

Both fields are part of `CodexAppServerStartOptions`, which is used when spawning the child process. For WebSocket transport there is no child process, so these overrides are silently ignored. A brief note ("these fields are only effective when using stdio transport") would prevent user confusion when someone sets `clearEnv` on a WebSocket-backed deployment and wonders why the variable still appears.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (1): Last reviewed commit: "fix(codex): expose app-server env contro..." | Re-trigger Greptile

Comment thread docs/plugins/codex-harness.md Resolved
@pashpashpash
pashpashpash force-pushed the codex/codex-app-server-clear-env branch from e6792b3 to 8c9db4e Compare April 27, 2026 22:32
@pashpashpash
pashpashpash force-pushed the codex/codex-app-server-clear-env branch from 8c9db4e to 3be14ca Compare April 27, 2026 22:35
@pashpashpash pashpashpash changed the title Let Codex app-server launches clear inherited env vars Keep Codex subscription runs from inheriting OpenAI API keys Apr 27, 2026
@steipete

Copy link
Copy Markdown
Contributor

Pushed follow-up 5fe2b2701b.

What changed:

  • Codex app-server auth now resolves in the intended order: explicit OpenClaw Codex auth profile, existing app-server account, then env API-key fallback.
  • Env fallback uses CODEX_API_KEY first, then OPENAI_API_KEY, and only after account/read reports no account while OpenAI auth is still required.
  • Subscription-style Codex profiles now keep both CODEX_API_KEY and OPENAI_API_KEY out of the spawned stdio child; API-key profile/fallback auth goes through app-server login RPC instead of inherited child env.
  • appServer.clearEnv is stdio-only, since websocket transports do not spawn a child process whose environment OpenClaw can sanitize.
  • Updated the Codex harness docs and OpenAI provider docs with the auth order and the API-key fallback behavior.

Verification:

  • pnpm test extensions/codex/src/app-server/auth-bridge.test.ts extensions/codex/src/app-server/config.test.ts extensions/codex/src/app-server/transport-stdio.test.ts -- --reporter=verbose
  • pnpm check:changed
  • Post-rebase: pnpm test extensions/codex/src/app-server/auth-bridge.test.ts extensions/codex/src/app-server/config.test.ts extensions/codex/src/app-server/transport-stdio.test.ts -- --reporter=dot

@pashpashpash
pashpashpash force-pushed the codex/codex-app-server-clear-env branch from 5fe2b27 to d890283 Compare April 27, 2026 23:01
@pashpashpash pashpashpash changed the title Keep Codex subscription runs from inheriting OpenAI API keys Keep Codex subscription runs from inheriting API keys Apr 27, 2026
@pashpashpash
pashpashpash force-pushed the codex/codex-app-server-clear-env branch from 80a1023 to dec5906 Compare April 27, 2026 23:22
@steipete
steipete force-pushed the codex/codex-app-server-clear-env branch from dec5906 to 06fdff1 Compare April 27, 2026 23:35
@pashpashpash

Copy link
Copy Markdown
Contributor Author

Live smoke proof for the Codex auth isolation change:

I ran three fresh local embedded agent sessions from this PR branch.

  1. PI with a validated OpenAI Platform API key

Command shape: OPENAI_API_KEY=<valid> OPENCLAW_AGENT_RUNTIME=pi node scripts/run-node.mjs agent --agent main --session-id smoke-pi-... --model openai/gpt-5.4 --thinking low --message "Reply with exactly ..." --local --json

Result: success. The JSON metadata reported agentHarnessId: "pi", provider openai, model gpt-5.4, and the assistant returned the exact smoke token OPENCLAW_PI_SMOKE_20260427193445-69302.

  1. PI with a deliberately bogus API key

Command shape: OPENAI_API_KEY=sk-invalid-openclaw-smoke-... OPENCLAW_AGENT_RUNTIME=pi ... --model openai/gpt-5.4 ...

Result: expected failure. The run exited 1 with 401 Incorrect API key provided, proving the bogus env key is actually observed by PI when the OpenAI API route uses env auth.

  1. Codex harness with the same kind of bogus API-key env in the parent process

Command shape: OPENAI_API_KEY=sk-invalid-openclaw-smoke-... CODEX_API_KEY=sk-invalid-openclaw-smoke-... OPENCLAW_AGENT_RUNTIME=codex node scripts/run-node.mjs agent --agent main --session-id smoke-codex-... --model openai/gpt-5.4 --thinking low --message "Reply with exactly ..." --local --json

Result: success. The JSON metadata reported agentHarnessId: "codex", provider openai, model gpt-5.4, and the assistant returned the exact smoke token OPENCLAW_CODEX_SMOKE_20260427193718-70903. The Codex sidecar metadata recorded a real Codex thread id, and the harness auth home reports auth_mode: "chatgpt" with no OPENAI_API_KEY stored. codex login status for that harness auth home reports Logged in using ChatGPT.

That gives us the falsifiable end-to-end proof: the same bogus env key that breaks PI does not break Codex on this branch, because Codex is running through subscription auth instead of inherited API-key auth.

@steipete
steipete force-pushed the codex/codex-app-server-clear-env branch from 06fdff1 to d72da2a Compare April 27, 2026 23:40
@steipete
steipete force-pushed the codex/codex-app-server-clear-env branch from d72da2a to 52fef79 Compare April 27, 2026 23:42
@aisle-research-bot

aisle-research-bot Bot commented Apr 27, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Case-variant environment variables can bypass clearEnv on Windows (OPENAI_API_KEY/CODEX_API_KEY leak)
1. 🟡 Case-variant environment variables can bypass clearEnv on Windows (OPENAI_API_KEY/CODEX_API_KEY leak)
Property Value
Severity Medium
CWE CWE-178
Location extensions/codex/src/app-server/transport-stdio.ts:46-56

Description

resolveCodexAppServerSpawnEnv builds the child-process environment as a plain JS object and then clears variables using exact-key deletion.

On Windows, environment variables are case-insensitive, and Node's process.env access is also case-insensitive. This means a value provided/inherited under a different casing (e.g., OpenAI_Api_Key) may still be visible to the spawned process as process.env.OPENAI_API_KEY, even after the code deletes only the exact OPENAI_API_KEY key.

This undermines the security intent introduced in bridgeCodexAppServerStartOptions to prevent inheriting user API keys when using Codex subscription/OAuth credentials.

Vulnerable code:

for (const key of options.clearEnv ?? []) {
  delete env[key];
}

Impact (Windows):

  • inputs: inherited baseEnv (or options.env) may contain OpenAI_Api_Key/Codex_Api_Key (or other casing)
  • clearing: clearEnv contains only OPENAI_API_KEY/CODEX_API_KEY
  • sink: resulting env is passed to spawn(..., { env }), so the child may still receive/use the API key

Recommendation

Perform platform-aware, case-insensitive clearing on Windows (and optionally normalize keys).

Example fix:

function deleteEnvKey(env: NodeJS.ProcessEnv, key: string, platform: NodeJS.Platform) {
  if (platform === "win32") {
    const needle = key.toLowerCase();
    for (const k of Object.keys(env)) {
      if (k.toLowerCase() === needle) {
        delete env[k];
      }
    }
  } else {
    delete env[key];
  }
}

​// ...
for (const key of options.clearEnv ?? []) {
  deleteEnvKey(env, key.trim(), process.platform);
}

Also consider normalizing/validating clearEnv entries (trim, reject empty) for all call paths, not only plugin config parsing.


Analyzed PR: #73063 at commit 52fef79

Last updated on: 2026-04-27T23:50:52Z

@steipete
steipete merged commit 3f94f25 into main Apr 27, 2026
69 checks passed
@steipete
steipete deleted the codex/codex-app-server-clear-env branch April 27, 2026 23:46
@steipete

Copy link
Copy Markdown
Contributor

Landed via temp rebase onto main.

  • Gate: GitHub CI on exact head SHA 52fef79e65c9f85bd011e4484bbc6df1b7082b5d completed with 69 checks, 0 failures.
  • Testbox: pnpm check:changed passed before the final base rebase.
  • Testbox after final rebase: pnpm test src/config/schema.help.quality.test.ts && pnpm test:contracts:plugins passed.
  • Source SHA: 52fef79
  • Merge commit: 3f94f25

Thanks @pashpashpash!

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

Labels

docs Improvements or additions to documentation extensions: codex maintainer Maintainer-authored PR size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Codex app-server inherits OPENAI_API_KEY from gateway and switches to API key mode

2 participants