Repository navigation
[codex] fix(auth): harden OAuth refresh and Codex CLI bootstrap flows - #68396
Conversation
- 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
There was a problem hiding this comment.
💡 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".
Greptile SummaryThis PR hardens the OpenAI Codex OAuth and Confidence Score: 5/5Safe 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 AIThis 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 |
🔒 Aisle Security AnalysisWe found 1 potential security issue(s) in this PR:
1. 🟡 External CLI OAuth bootstrap identity gate trusts spoofable account_id field
DescriptionThe new identity-matching gate for adopting OAuth credentials from external CLI sources (Codex CLI / keychain) prioritizes As a result:
Vulnerable logic (accountId takes precedence over other identity signals): if (existingAccountId !== undefined && importedAccountId !== undefined) {
return existingAccountId === importedAccountId;
}And the imported 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 RecommendationDo not treat Recommended fixes (choose one):
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 Last updated on: 2026-04-18T06:04:47Z |
There was a problem hiding this comment.
💡 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".
|
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 What was security- or priority-relevant, and where it was fixed:
Proof of the fixes:
Verification run for the review follow-ups:
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. |
There was a problem hiding this comment.
💡 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".
|
I found three issues worth addressing before merge:
|
|
Replying point-by-point:
Thanks for calling these out @ngutman. These are all worth addressing before merge.
|
There was a problem hiding this comment.
💡 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".
|
Follow-up to #68396 (comment) Implemented on 1 | Cross-account
2 | TLS prerequisite failures now fail fast
3 | Local manual fallback behavior
Validation run locally:
|
…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
…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
…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
…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
…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
…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
…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
Summary
Describe the problem and fix in 2–5 bullets:
.codex/auth.json, and local Codex callback/refresh paths could fail or hang in ways that looked like "slow OAuth".openai-codex:defaultis now the canonical owner,.codexis 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..codexauthoritative again, and it does not attempt to fix the upstream@mariozechner/pi-ailoopback behavior beyond adding local guardrails.Change Type (select all)
Scope (select all touched areas)
Linked Issue/PR
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, writeUnknown..codexstate, 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..codexcollisions, 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.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.codex, near-expiry auth refreshes before hard expiry, stale.codexnever overwrites the better canonical refresh token, callback timeout/validation failures surface deterministically, and refresh waiters do not fail before a real owner can finish.User-visible / Behavior Changes
List user-visible changes (including defaults/config).
If none, write
None..codexis only used to bootstrap/runtime-fill missing or stale local state.Diagram (if applicable)
For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write
N/A.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]Security Impact (required)
Yes/No) NoYes/No) YesYes/No) NoYes/No) NoYes/No) NoYes, 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
v24.13.0, pnpm10.11.1.codexopenai-codex:defaultauth profile with local.codex/auth.jsonpresentSteps
openai-codex:defaultcredential in OpenClaw while.codex/auth.jsoncontains a different credential, or start a local OAuth login and never deliver the callback.Expected
.codexoverwriting canonical state.Actual
Evidence
Attach at least one:
Human Verification (required)
What you personally verified (not just CI), and how:
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, andpnpm check..codexcollisions, stale imported refresh state, callback timeout/manual fallback, callback validation failure classification, and refresh contention retry timing.@mariozechner/pi-aifix.Review Conversations
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
Yes/No) YesYes/No) NoYes/No) NoRisks and Mitigations
List only real risks for this PR. Add/remove entries as needed. If none, write
None..codexcan become stale after a canonical refresh because it is no longer authoritative.