Skip to content

[codex] fix(auth): harden OAuth refresh and Codex CLI bootstrap flows - #68396

Merged
BunsDev merged 12 commits into
mainfrom
okcode/oauth-regression-analysis
Apr 18, 2026
Merged

BunsDev merged 12 commits into
mainfrom
okcode/oauth-regression-analysis

Conversation

@BunsDev

@BunsDev BunsDev commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Describe the problem and fix in 2–5 bullets:

  • Problem: OAuth authority drifted between OpenClaw auth profiles and .codex/auth.json, and local Codex callback/refresh paths could fail or hang in ways that looked like "slow OAuth".
  • Why it matters: users could see stale-token collisions, first-request refresh stalls, spurious re-auth guidance, or a login flow that never completes.
  • What changed: OpenClaw openai-codex:default is now the canonical owner, .codex is bootstrap/runtime-only, near-expiry usability is shared across core + extension bootstrap, local callback flows have bounded manual fallback, and refresh contention/error reporting are hardened.
  • Review follow-up: the longer contention wait now lives on the OAuth refresh lock policy; generic file locks still honor their configured retry budgets.
  • What did NOT change (scope boundary): this does not make .codex authoritative again, and it does not attempt to fix the upstream @mariozechner/pi-ai loopback behavior beyond adding local guardrails.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

  • Closes #
  • Related #
  • This PR fixes a bug or regression

Root Cause (if applicable)

For bug fixes or regressions, explain why this happened, not just what changed. Otherwise write N/A. If the cause is unclear, write Unknown.

  • Root cause: canonical OpenClaw auth state, external .codex state, auth health, and extension bootstrap logic were using different rules for which OAuth credential was still usable. At the same time, local callback flows could wait forever and refresh waiters could exhaust retries before a legitimate refresh owner finished.
  • Missing detection / guardrail: there was no shared "usable OAuth credential" helper, no bounded fallback for local Codex callback hangs, and no contention coverage proving the retry budget matched the lock stale window.
  • Contributing context (if known): recent Codex harness changes appear to have increased local .codex collisions, making the split-brain behavior much easier to hit.

Regression Test Plan (if applicable)

For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write N/A.

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
  • Target test or file: src/agents/auth-profiles/credential-state.test.ts, src/agents/auth-profiles.external-cli-sync.test.ts, src/agents/auth-health.test.ts, src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts, src/plugins/provider-openai-codex-oauth.test.ts, extensions/openai/openai-codex-cli-auth.test.ts, src/plugin-sdk/file-lock.test.ts
  • Scenario the test should lock in: healthy canonical local auth beats imported .codex, near-expiry auth refreshes before hard expiry, stale .codex never overwrites the better canonical refresh token, callback timeout/validation failures surface deterministically, and refresh waiters do not fail before a real owner can finish.
  • Why this is the smallest reliable guardrail: the regression spans the auth-profile core, extension bootstrap, provider-local OAuth wrapper, and file-lock retry behavior, so the smallest reliable net is one shared unit helper plus seam tests at each integration boundary.
  • Existing test that already covers this (if any): none that covered the split across all of those seams.
  • If no new test is added, why not: N/A

User-visible / Behavior Changes

List user-visible changes (including defaults/config).
If none, write None.

  • Near-expiry OAuth is treated as no longer usable and refreshes before hard expiry using a shared 5-minute margin.
  • OpenClaw local auth remains authoritative when still usable; .codex is only used to bootstrap/runtime-fill missing or stale local state.
  • Local Codex OAuth login falls back to manual code entry after timeout instead of hanging indefinitely.
  • Timeout/contention failures surface clearer internal reasons instead of generic "re-authenticate" guidance.

Diagram (if applicable)

For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write N/A.

Before:
OpenClaw auth store <-> .codex auth.json (different codepaths chose different winners)
local callback wait -> can hang forever
refresh waiter -> retry budget exhausted -> file lock timeout

After:
OpenClaw auth store -> usable? yes -> use canonical local credential
                     -> unusable? -> bootstrap from fresh .codex or refresh into canonical store
local callback wait -> timeout -> manual paste fallback
refresh owner holds lock -> waiters keep polling within stale window -> adopt fresh canonical state
flowchart TD
  A[Resolve Codex auth] --> B{Usable OpenClaw\\nopenai-codex:default?}
  B -->|Yes| C[Use canonical OpenClaw credential]
  B -->|No| D{Usable .codex/auth.json?}
  D -->|Yes| E[Bootstrap from .codex\\nruntime input only]
  D -->|No| F[Refresh canonical OpenClaw credential]
  F --> G[Persist refreshed state to OpenClaw]
  C --> H[Return auth]
  E --> H
  G --> H

  I[Start local OAuth login] --> J{Callback arrives\\nand validates?}
  J -->|Yes| K[Persist credential]
  J -->|Timeout or invalid callback| L[Manual code fallback]
Loading

Security Impact (required)

  • New permissions/capabilities? (Yes/No) No
  • Secrets/tokens handling changed? (Yes/No) Yes
  • New/changed network calls? (Yes/No) No
  • Command/tool execution surface changed? (Yes/No) No
  • Data access scope changed? (Yes/No) No
  • If any Yes, explain risk + mitigation: token precedence and refresh persistence changed so OpenClaw stays the single source of truth. The mitigation is explicit canonical-owner policy, refusing unusable imported overwrite during refresh, and added regression coverage around collision/refresh paths.

Repro + Verification

Environment

  • OS: Darwin 25.4.0
  • Runtime/container: Node v24.13.0, pnpm 10.11.1
  • Model/provider: OpenAI Codex OAuth
  • Integration/channel (if any): local Codex CLI / .codex
  • Relevant config (redacted): canonical openai-codex:default auth profile with local .codex/auth.json present

Steps

  1. Put a near-expiry or expired openai-codex:default credential in OpenClaw while .codex/auth.json contains a different credential, or start a local OAuth login and never deliver the callback.
  2. Resolve OpenAI Codex auth or run concurrent refresh callers against the same profile.
  3. Observe which credential is used, whether refresh persists canonically, and whether the login/refresh attempt terminates cleanly.

Expected

  • Healthy canonical local auth wins.
  • Near-expiry or expired local auth bootstraps/refreshes without stale .codex overwriting canonical state.
  • Local callback wait times out into manual fallback.
  • Refresh waiters do not fail early while a legitimate lock owner is still refreshing.

Actual

  • Added regression coverage now passes for those scenarios, and the full auth/plugin/build/check gates stay green.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios: ran pnpm test extensions/openai/openai-codex-cli-auth.test.ts src/plugins/provider-openai-codex-oauth.test.ts src/plugin-sdk/file-lock.test.ts src/agents/pi-embedded-helpers.isbillingerrormessage.test.ts src/agents/pi-embedded-helpers.formatassistanterrortext.test.ts src/agents/auth-profiles/credential-state.test.ts src/agents/auth-profiles.external-cli-sync.test.ts src/agents/auth-health.test.ts src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts, pnpm plugin-sdk:api:gen, pnpm build, and pnpm check.
  • Edge cases checked: near-expiry local-vs-.codex collisions, stale imported refresh state, callback timeout/manual fallback, callback validation failure classification, and refresh contention retry timing.
  • What you did not verify: a live browser-based OAuth roundtrip against the real Codex service or an upstream @mariozechner/pi-ai fix.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes/No) Yes
  • Config/env changes? (Yes/No) No
  • Migration needed? (Yes/No) No
  • If yes, exact upgrade steps:

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.

  • Risk: .codex can become stale after a canonical refresh because it is no longer authoritative.
    • Mitigation: this is deliberate to avoid split-brain; any future mirror path should stay explicitly one-way.
  • Risk: earlier refreshes increase token refresh frequency slightly.
    • Mitigation: the shared 5-minute margin avoids first-request expiry/latency spikes and is covered by regression tests.
  • Risk: the upstream local callback mismatch may still exist.
    • Mitigation: OpenClaw now bounds the wait, falls back to manual entry, and classifies the failure more clearly.

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling extensions: openai size: L maintainer Maintainer-authored PR labels Apr 18, 2026
@BunsDev
BunsDev marked this pull request as ready for review April 18, 2026 04:16
@BunsDev
BunsDev requested a review from a team as a code owner April 18, 2026 04:16

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e979e7c8ec

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/plugin-sdk/file-lock.ts Resolved
@greptile-apps

greptile-apps Bot commented Apr 18, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR hardens the OpenAI Codex OAuth and .codex bootstrap flows: near-expiry credentials (within 5 min) are now treated as unusable via a shared hasUsableOAuthCredential helper, the file-lock retry loop now waits long enough for a legitimate refresh to complete before giving up, local OAuth callback hangs now time out into a manual-paste fallback, and new error codes (refresh_contention, refresh_timeout, callback_timeout, callback_validation) replace generic re-auth guidance. All findings are P2.

Confidence Score: 5/5

Safe to merge; all remaining findings are non-blocking P2 style/robustness suggestions.

The core logic — credential usability threshold, lock retry window alignment, callback timeout fallback, and error classification — is correct and well-tested. Three P2 comments flag a silent implicit invariant (never-resolving promise), a regex-to-path-format coupling, and a zero-retries loop behavior change, none of which affect current production callers.

src/plugins/provider-openai-codex-oauth.ts (never-resolving settled branch), src/agents/pi-embedded-helpers/errors.ts (contention regex coupling), src/plugin-sdk/file-lock.ts (loop invariant documentation)

Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/plugins/provider-openai-codex-oauth.ts
Line: 59-60

Comment:
**Never-resolving promise is an implicit contract**

When `outcome === "settled"`, this returns a promise that never resolves or rejects. This is safe today only because `markLoginSettled()` lives in the `finally` block — meaning `loginOpenAICodex` has already returned before `waitForLoginToSettle` can fire. If the upstream library ever calls `onManualCodeInput` and awaits its result while independently resolving via browser callback (a race the PR description acknowledges is possible), this branch would leave `loginOpenAICodex` hung indefinitely.

A comment explaining the invariant would make the assumption explicit:

```suggestion
    if (outcome === "settled") {
      // loginOpenAICodex has already returned (markLoginSettled is in finally),
      // so this result is never awaited. Return a never-settling promise as a
      // "don't care" signal rather than prompting the user for a code that is
      // no longer needed.
      return await new Promise<string>(() => undefined);
    }
```

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

---

This is a comment left during a code review.
Path: src/agents/pi-embedded-helpers/errors.ts
Line: 456-462

Comment:
**Contention classification relies on implicit lock path content**

`isOAuthRefreshContentionMessage` requires the lock path to contain `oauth`, `auth-profile`, `auth profiles`, or `refresh`. This currently works because `resolveOAuthRefreshLockPath` embeds the literal segment `oauth-refresh` in the path, so `\boauth\b` and `\brefresh\b` will match. However, the coupling is silent: if the lock path naming ever changes (or the function is called on a timeout from a different lock), classification silently falls back to `"unknown"` rather than `"auth_refresh"`.

Consider attaching a typed `code` property to the `acquireFileLock` timeout error (similar to what `createOpenAICodexOAuthError` does) so callers can match on a stable code rather than parsing the message string.

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

---

This is a comment left during a code review.
Path: src/plugin-sdk/file-lock.ts
Line: 165-192

Comment:
**Zero-retries callers now retry for `minimumRetryWindowMs` instead of exiting immediately**

With `retries: { retries: 0, ... }` and `stale > maxTimeout`, `configuredRetries = 0` so `configuredRetriesExhausted` is `true` from attempt 0, but `minimumRetryWindowSatisfied` is `false` until `stale - maxTimeout` ms elapse. The loop keeps spinning — a silent behavior change from the old `attempt < 1` exit.

All current callers use `retries: 10` so no production impact today. A short comment on the loop invariant would prevent future callers from being surprised:

```typescript
// Loop exits when BOTH the configured retry budget is exhausted AND the
// minimum window (stale - maxTimeout) has elapsed. For callers with
// retries.retries=0, the retry budget is exhausted immediately, but the
// minimum window keeps the loop alive until a stale lock could have been
// detected.
```

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

Reviews (1): Last reviewed commit: "Harden OAuth refresh and Codex CLI boots..." | Re-trigger Greptile

Comment thread src/plugin-sdk/file-lock.ts Resolved
@aisle-research-bot

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

Copy link
Copy Markdown

🔒 Aisle Security Analysis

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

# Severity Title
1 🟡 Medium External CLI OAuth bootstrap identity gate trusts spoofable account_id field
1. 🟡 External CLI OAuth bootstrap identity gate trusts spoofable account_id field
Property Value
Severity Medium
CWE CWE-345
Location src/agents/auth-profiles/external-cli-sync.ts:65-75

Description

The new identity-matching gate for adopting OAuth credentials from external CLI sources (Codex CLI / keychain) prioritizes accountId equality when both stored and imported credentials contain it. However, accountId is read from external, user-writable credential material (auth.json / keychain JSON record) and is not cryptographically bound to the access/refresh tokens.

As a result:

  • A local attacker who can modify the external CLI credential source can set tokens.account_id to match the victim’s existing stored accountId.
  • The gate will treat the imported credential as “safe” (because existingAccountId === importedAccountId) even if the imported tokens belong to a different OpenAI/Codex account.
  • The application may then adopt/refresh and use the attacker-controlled refresh token, causing account confusion (requests made under the wrong account).

Vulnerable logic (accountId takes precedence over other identity signals):

if (existingAccountId !== undefined && importedAccountId !== undefined) {
  return existingAccountId === importedAccountId;
}

And the imported accountId comes directly from external CLI data:

const accountId = typeof tokens?.account_id === "string" ? tokens.account_id : undefined;

While JWT payload decoding is also performed without signature verification elsewhere, the more direct issue here is trusting an external, mutable account_id field as the primary binding signal for credential adoption decisions.

Recommendation

Do not treat accountId from external CLI credential sources as a trusted identity binding unless it is verified/bound to the tokens.

Recommended fixes (choose one):

  1. Bind by token-derived stable subject (preferred): derive identity from a stable claim inside the access token (e.g., sub/iss or provider-specific stable user id) and only compare that. If decoding JWTs, ensure you verify signature (e.g., via JWKS) or avoid using unverifiable fields.

  2. Ignore external account_id for gating: only use email if it comes from a trusted source, or require overlap of multiple fields rather than accepting a single mutable field.

  3. Server-side introspection: fetch the current user identity using the access token (e.g., GET /me) and compare returned identity to the stored credential before adoption.

Example adjustment (do not trust imported accountId alone):

​// Only use accountId if it is derived from a verified token/userinfo response.
if (existingAccountId && importedAccountId && imported.accountIdSource === "verified") {
  return existingAccountId === importedAccountId;
}
​// otherwise fall back to verified email or refuse
if (existingEmail && importedEmail) return existingEmail === importedEmail;
return !existingEmail && !existingAccountId;

Analyzed PR: #68396 at commit 3a83895

Last updated on: 2026-04-18T06:04:47Z

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6dacd67477

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@BunsDev

BunsDev commented Apr 18, 2026

Copy link
Copy Markdown
Contributor Author

Security / correctness follow-up summary

All review conversations on this PR are now resolved. I re-checked the thread state after the last push and the unresolved review-thread count is 0.

What was security- or priority-relevant, and where it was fixed:

  • P1 generic file-lock regression: the earlier contention change accidentally widened wait time for every file-lock user, not just OAuth refresh. That could stall fast-fail paths like persistent dedupe / webhook handling far beyond their configured retry policy. Fixed by restoring generic retry-budget semantics in src/plugin-sdk/file-lock.ts, exporting a typed timeout code via src/infra/file-lock.ts, and moving the longer wait to the OAuth-specific policy in src/agents/auth-profiles/constants.ts.
  • OAuth refresh contention classification was too message-coupled: failure handling depended on parsing lock-path text. Fixed by introducing a typed file-lock timeout surface in src/plugin-sdk/file-lock.ts, wrapping OAuth lock timeouts as refresh_contention in src/agents/auth-profiles/oauth.ts, and recognizing that stable code in src/agents/pi-embedded-helpers/errors.ts.
  • Local Codex OAuth manual fallback could keep a timer alive after browser callback settlement, which could make short-lived commands appear to hang. Fixed in src/plugins/provider-openai-codex-oauth.ts by replacing the raw race with a timeout-clearing helper and documenting the never-settling fallback invariant.
  • Split-brain refresh state still had one recoverable edge case: if local canonical state had a stale refresh token and imported .codex state had a fresher refresh token but an already-expired access token, we were not adopting the better refresh token before refresh. Fixed in src/agents/auth-profiles/oauth.ts so fresher imported refresh state is persisted and used for refresh even when the imported access token is already expired, while still refusing older stale imported state.

Proof of the fixes:

Verification run for the review follow-ups:

  • pnpm test src/plugin-sdk/file-lock.test.ts src/plugins/provider-openai-codex-oauth.test.ts src/agents/auth-profiles/oauth-refresh-timeout.test.ts src/agents/auth-profiles/oauth.concurrent-agents.test.ts src/agents/pi-embedded-helpers.isbillingerrormessage.test.ts
  • pnpm test src/agents/auth-profiles/oauth.openai-codex-refresh-fallback.test.ts
  • pnpm build
  • pnpm check

Net result: the P1 generic lock regression is removed, OAuth contention is classified by stable code instead of path text, the local callback fallback no longer leaves a live timer behind, and the canonical OpenClaw refresh path now correctly adopts fresher imported refresh state without letting stale imported state win.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5de3c058d0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/agents/auth-profiles/oauth.ts Resolved
@ngutman

ngutman commented Apr 18, 2026

Copy link
Copy Markdown
Member

I found three issues worth addressing before merge:

  1. extensions/openai/openai-codex-cli-auth.ts:113 — expired local Codex profiles can now be silently replaced by a different CLI account. The new guard only blocks bootstrap when the stored openai-codex:default credential is still usable; once it is expired or within the 5-minute margin, any ~/.codex/auth.json credential is accepted without checking accountId/email against the stored profile. In a setup where OpenClaw is logged into account A and Codex CLI is logged into account B, the next bootstrap can silently switch the default profile to account B.

  2. src/plugins/provider-openai-codex-oauth.ts:105 — TLS prerequisite failures no longer fail fast even though the OAuth exchange cannot succeed. runOpenAIOAuthTlsPreflight() probes the same Node/OpenSSL TLS path that loginOpenAICodex() later uses for the token exchange. After this change, a tls-cert failure only logs guidance and still launches the interactive OAuth flow, so users with broken CA roots can complete the browser steps and then deterministically fail at token exchange.

  3. src/plugins/provider-openai-codex-oauth.ts:72 — the new local manual fallback can leave an orphaned prompt or add a 15s stall. loginOpenAICodex() starts onManualCodeInput() immediately and upstream does not cancel it when the browser callback wins. That means a local login that completes just after the 15s timeout can still leave prompter.text(...) active in the background, and a callback-server bind failure now waits the full 15s before showing any paste prompt.

@BunsDev

BunsDev commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Replying point-by-point:

  1. Agreed. The current extensions/openai/openai-codex-cli-auth.ts guard only rejects .codex bootstrap when the stored openai-codex:default credential is still usable. Once the local credential is expired or inside the shared 5-minute refresh margin, we can currently accept a different CLI identity without re-checking accountId / email, which reintroduces a cross-account bootstrap path. I am treating that as a real auth-integrity bug and will tighten the bootstrap path to apply the same identity-safety rule we already use for canonical-store copy / mirror operations before allowing the external credential to replace the local default.

  2. Agreed. tls-cert should still be fail-fast here. The preflight is probing the same Node/OpenSSL TLS path the later token exchange uses, so continuing into the interactive browser flow after a certificate-chain failure just wastes user time and produces a deterministic failure later. I will restore the hard stop for tls-cert while keeping the current continue-on-non-cert/network behavior.

  3. Agreed. The current local manual fallback is still too eager in practice. It clears the timer if the browser callback wins before the timeout, but it does not cancel an already-started prompt, and callback-listener/bind failures can still sit behind the fixed 15s delay before manual entry becomes available. I will rework the local path so manual entry is only surfaced when we actually know we need it, and immediate local callback setup failures do not pay the fallback delay.

Thanks for calling these out @ngutman. These are all worth addressing before merge.

BRB... 🦞

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6927a31714

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@BunsDev

BunsDev commented Apr 18, 2026 •

Copy link
Copy Markdown
Contributor Author

Follow-up to #68396 (comment)

Implemented on 05a79811cb.

1 | Cross-account .codex bootstrap replacement

  • Solved in extensions/openai/openai-codex-cli-auth.ts.
  • The bootstrap path now applies an identity safety gate even when the stored openai-codex:default credential is expired or inside the near-expiry margin, so a different CLI account cannot silently replace a local default that already carries accountId/email evidence.
  • Coverage: extensions/openai/openai-codex-cli-auth.test.ts with refuses Codex CLI bootstrap when an expired local default belongs to a different account.

2 | TLS prerequisite failures now fail fast

  • Solved in src/plugins/provider-openai-codex-oauth.ts.
  • When runOpenAIOAuthTlsPreflight() returns kind === "tls-cert", we now surface the prerequisite note and stop before calling loginOpenAICodex(). That avoids sending users through the browser flow when the later token exchange is guaranteed to fail on the same TLS stack.
  • Coverage: src/plugins/provider-openai-codex-oauth.test.ts with fails fast on TLS certificate preflight failures before starting OAuth login.

3 | Local manual fallback behavior
Solved in src/plugins/provider-openai-codex-oauth.ts.

  • Two changes here:
    • If the local browser/callback path never actually starts, we now switch to manual entry immediately instead of sitting behind the fixed 15s delay.
    • If the browser callback wins just after the fallback deadline, we now give the flow a short grace window before opening the manual prompt, which suppresses the stray/orphan prompt race in that near-miss case.
  • Coverage:
    • prompts for manual input immediately when the local callback flow never starts
    • suppresses the local manual prompt when oauth settles just after the fallback deadline
    • waits briefly before prompting for manual input after the local browser flow starts

Validation run locally:

  • OPENCLAW_LOCAL_CHECK=0 pnpm test extensions/openai/openai-codex-cli-auth.test.ts src/plugins/provider-openai-codex-oauth.test.ts
  • OPENCLAW_LOCAL_CHECK=0 pnpm build
  • OPENCLAW_LOCAL_CHECK=0 pnpm check

lovewanwan pushed a commit to lovewanwan/openclaw that referenced this pull request Apr 28, 2026
…openclaw#68396)

* Harden OAuth refresh and Codex CLI bootstrap flows

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention

* fix(auth): address PR review threads

* fix(auth): adopt fresher imported refresh tokens

* test(auth): align oauth expiry fixtures with refresh margin

* fix(auth): tighten Codex OAuth bootstrap and local fallback

* Keep explicit local auth over CLI bootstrap

- Preserve existing non-OAuth local profiles during external CLI OAuth sync
- Add regression coverage for OpenAI Codex and generic external OAuth overlays

* fix(auth): distinguish oauth lock timeout sources

* fix(auth): reject cross-account external oauth bootstrap

* fix(auth): narrow refresh contention classification
ogt-redknie pushed a commit to ogt-redknie/OPENX that referenced this pull request May 2, 2026
…openclaw#68396)

* Harden OAuth refresh and Codex CLI bootstrap flows

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention

* fix(auth): address PR review threads

* fix(auth): adopt fresher imported refresh tokens

* test(auth): align oauth expiry fixtures with refresh margin

* fix(auth): tighten Codex OAuth bootstrap and local fallback

* Keep explicit local auth over CLI bootstrap

- Preserve existing non-OAuth local profiles during external CLI OAuth sync
- Add regression coverage for OpenAI Codex and generic external OAuth overlays

* fix(auth): distinguish oauth lock timeout sources

* fix(auth): reject cross-account external oauth bootstrap

* fix(auth): narrow refresh contention classification
globalcaos pushed a commit to globalcaos/tinkerclaw that referenced this pull request May 13, 2026
…openclaw#68396)

* Harden OAuth refresh and Codex CLI bootstrap flows

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention

* fix(auth): address PR review threads

* fix(auth): adopt fresher imported refresh tokens

* test(auth): align oauth expiry fixtures with refresh margin

* fix(auth): tighten Codex OAuth bootstrap and local fallback

* Keep explicit local auth over CLI bootstrap

- Preserve existing non-OAuth local profiles during external CLI OAuth sync
- Add regression coverage for OpenAI Codex and generic external OAuth overlays

* fix(auth): distinguish oauth lock timeout sources

* fix(auth): reject cross-account external oauth bootstrap

* fix(auth): narrow refresh contention classification
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request May 24, 2026
…openclaw#68396)

* Harden OAuth refresh and Codex CLI bootstrap flows

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention

* fix(auth): address PR review threads

* fix(auth): adopt fresher imported refresh tokens

* test(auth): align oauth expiry fixtures with refresh margin

* fix(auth): tighten Codex OAuth bootstrap and local fallback

* Keep explicit local auth over CLI bootstrap

- Preserve existing non-OAuth local profiles during external CLI OAuth sync
- Add regression coverage for OpenAI Codex and generic external OAuth overlays

* fix(auth): distinguish oauth lock timeout sources

* fix(auth): reject cross-account external oauth bootstrap

* fix(auth): narrow refresh contention classification
jameslcowan pushed a commit to jameslcowan/openclaw that referenced this pull request Jun 2, 2026
…openclaw#68396)

* Harden OAuth refresh and Codex CLI bootstrap flows

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention

* fix(auth): address PR review threads

* fix(auth): adopt fresher imported refresh tokens

* test(auth): align oauth expiry fixtures with refresh margin

* fix(auth): tighten Codex OAuth bootstrap and local fallback

* Keep explicit local auth over CLI bootstrap

- Preserve existing non-OAuth local profiles during external CLI OAuth sync
- Add regression coverage for OpenAI Codex and generic external OAuth overlays

* fix(auth): distinguish oauth lock timeout sources

* fix(auth): reject cross-account external oauth bootstrap

* fix(auth): narrow refresh contention classification
vixco pushed a commit to vixco/openclaw that referenced this pull request Aug 16, 2026
…openclaw#68396)

* Harden OAuth refresh and Codex CLI bootstrap flows

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention

* fix(auth): address PR review threads

* fix(auth): adopt fresher imported refresh tokens

* test(auth): align oauth expiry fixtures with refresh margin

* fix(auth): tighten Codex OAuth bootstrap and local fallback

* Keep explicit local auth over CLI bootstrap

- Preserve existing non-OAuth local profiles during external CLI OAuth sync
- Add regression coverage for OpenAI Codex and generic external OAuth overlays

* fix(auth): distinguish oauth lock timeout sources

* fix(auth): reject cross-account external oauth bootstrap

* fix(auth): narrow refresh contention classification
Heetisk pushed a commit to Heetisk/openclaw that referenced this pull request Sep 28, 2026
…openclaw#68396)

* Harden OAuth refresh and Codex CLI bootstrap flows

- Treat near-expiry OAuth credentials as unusable for bootstrap and refresh
- Add clearer timeout and callback validation handling for OpenAI Codex OAuth
- Tighten file lock retry behavior for stale OAuth refresh contention

* fix(auth): address PR review threads

* fix(auth): adopt fresher imported refresh tokens

* test(auth): align oauth expiry fixtures with refresh margin

* fix(auth): tighten Codex OAuth bootstrap and local fallback

* Keep explicit local auth over CLI bootstrap

- Preserve existing non-OAuth local profiles during external CLI OAuth sync
- Add regression coverage for OpenAI Codex and generic external OAuth overlays

* fix(auth): distinguish oauth lock timeout sources

* fix(auth): reject cross-account external oauth bootstrap

* fix(auth): narrow refresh contention classification
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation extensions: openai maintainer Maintainer-authored PR size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants