Skip to content

fix(auth): only the running Gateway refreshes shared OAuth sign-ins - #198294

Open
obviyus wants to merge 3 commits into
mainfrom
openclaw/credential-owner-central
Open

obviyus wants to merge 3 commits into
mainfrom
openclaw/credential-owner-central

Conversation

@obviyus

@obviyus obviyus commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

What Problem This Solves

Fixes: Gateway turns fail with No credentials found for profile "<provider>:<account>" after a local CLI command (for example infer audio transcribe, infer tts convert or infer model auth login) refreshes or stores a shared OAuth sign-in while the Gateway runs.

User Impact

  • While a Gateway runs, it is the only process that refreshes or stores shared OAuth sign-ins. Gateway turns keep working after local CLI commands.

  • A local command beside a running Gateway uses a still-valid token as is. If the token has expired, the command refuses before it changes anything, and it tells you to run the command through the Gateway or stop the Gateway first:

    The <provider> sign-in "<profile>" needs a refresh, but the Gateway (pid N, port P) owns the shared credentials and only it may refresh them. No credential was changed. Run this through the Gateway, retry after its next turn refreshes the sign-in, or stop the Gateway through its service owner and rerun this command.
    
  • infer model auth login now runs the models auth login path (routed through the Gateway when one runs). infer model auth logout refuses while a Gateway runs, the same as models auth logout.

  • agent --local, agent exec --state-dir, tui --local and models status --probe show one shared offline-only refusal instead of four different ones.

  • With no Gateway running, nothing changes.

Why This Change Was Made

The rule "outside writers route through the Gateway or hold exclusive offline custody" (worker access) was enforced separately in each command, and each command that missed it broke the Gateway's sign-in. A read-only command can write credentials only by refreshing an OAuth sign-in, so this PR enforces ownership once, in the OAuth manager, before the refresh queue, claim or any write. Explicit credential edits reuse the existing models auth owner. Embedded runs use runWithLocalStateOwner, and the duplicate acquireEmbeddedStateLock owner is removed. There is no Gateway method, protocol, config or schema change, and nothing changes on the Gateway side.

Production diff (without tests and docs): +251 / −324, net −73. This includes moving settleOAuthRefreshPeerClaimsUnderLock unchanged from oauth-manager.ts to oauth-store.ts to respect the file line cap.

Caller map, deleted code, accepted edge cases

Caller map

CLI path Writes while a Gateway runs Covered by
infer model run (default / --local) refresh #198141 routing / refusal (unchanged)
infer image/audio/video/web/embedding, local tts convert refresh refresh owner
infer model auth login sign-in models auth login owner (routes)
infer model auth logout profile removal models auth owner (refuses)
agent --local, agent exec --state-dir, tui --local, models status --probe refresh + all state runWithLocalStateOwner (refuses)
models auth *, mcp credential commands, memory as before runWithLocalStateOwner (unchanged)
any other local refresh (plugins, tools) refresh refresh owner

Deleted

  • src/infra/embedded-state-lock.ts: acquireEmbeddedStateLock. The signal bridge moved to process-signal-bridge.ts.
  • The four per-command refusal formatters (formatActiveGatewayLocalRefusal, formatActiveGatewayExecRefusal, formatActiveGatewayTuiRefusal, formatActiveGatewayModelsProbeRefusal).
  • The private infer model auth logout implementation (runModelAuthLogout) and the direct login call.

Production diff (excluding tests and docs): +251 / −324, net −73 (includes moving settleOAuthRefreshPeerClaimsUnderLock unchanged from oauth-manager.ts to oauth-store.ts to respect the line cap).

Accepted edge cases

  • A failed models status --probe batch now reports after its in-flight probes settle, because ownership must outlive them.
  • Usage bookkeeping (cooldown and last-used stats) from a local command is not a credential refresh and is not gated here.

Evidence

Regression tests (red on main, green here)

  • src/agents/auth-profiles/oauth-manager.test.ts › credentials owned by a running Gateway › uses a still-valid sign-in without refreshing it. On main the CLI refreshes the in-window token.
  • … › refuses to refresh an expired sign-in before any write. On main the refresh runs and stores.
  • … › refuses for the retained credential scope of a redirected run. Without the scope fix, owner discovery reads the process env and the refresh runs.
  • src/cli/capability-cli/model.state-owner.test.ts › refuses infer model auth logout while the Gateway owns the shared credentials. On main logout enters local agent admission.

Updated: agent-via-gateway, agent-exec.state-lock, agent-exec.auth, tui, list.probe, list.probe.cleanup, database-port-admission (ownership assertions now use the shared owner; tests that duplicated runWithLocalStateOwner's own suite were removed).

E2E. Each case uses its own isolated scratch Gateway (one at a time, with its own state dir and port) and real agent turns. Two OAuth sign-ins: a stand-in OAuth provider (local mock token endpoint) and a real hosted OAuth provider. main = 8ebe740 build. fix = PR build a1045f3. The later commit 31e76d5 changes only the redirected-scope lookup; the stand-in infer image describe cases were run again on the final head 31e76d5 (same tree as the a5935f0 build) and gave the same results. "Writer" = the process that stored a refreshed credential (from the credential row's writer record). "upvalid" = token valid for ~4.5 min; "upexpired" = token expired, Gateway up; "down" = no Gateway. Each up case runs 8–10 Gateway turns around the command.

Case main: command main: writer main: later turns fix: command fix: writer fix: later turns
infer model run up valid / expired via Gateway, OK Gateway 10/10, 8/8 via Gateway, OK Gateway 10/10, 8/8
infer image describe up valid local, OK Gateway 10/10 local, OK, no refresh Gateway 10/10
infer image describe up expired No API key found Gateway 8/8 ownership refusal, nothing written Gateway 8/8
infer audio transcribe up valid local, OK, refreshed a valid token CLI 9/10 (No credentials found for profile) local, OK, no refresh Gateway 10/10
infer audio transcribe up expired local, OK, refreshed CLI 8/8 refused, nothing written (see note) Gateway 8/8
infer tts convert up valid local, OK, refreshed a valid token CLI 9/10 (No credentials found for profile) local, OK, no refresh Gateway 10/10
infer tts convert up expired local, OK, refreshed CLI 8/8 ownership refusal, nothing written Gateway 8/8
infer model auth login up local sign-in, stored CLI 10/10 routed to models auth login (refuses a non-Gateway method) Gateway 10/10
infer model auth logout up removed beside the Gateway – 10/10 (Gateway re-stored the profile) models auth refusal, nothing removed Gateway 10/10
agent --local + models status --probe up 2 separate refusals Gateway 10/10 shared runWithLocalStateOwner refusal Gateway 10/10
every command with no Gateway (model run, image, audio, tts, login, logout, agent --local, probe) OK, refreshes locally CLI – OK, refreshes locally CLI –

Summary: on main, the CLI is a second credential writer beside a running Gateway in audio, tts and login, and the next Gateway turn fails with No credentials found for profile. On this branch the Gateway is the only writer whenever it runs, and no Gateway turn fails. Offline behavior is unchanged.

Final head, stand-in provider, infer image describe:

  • up valid: CLI OK with no refresh, Gateway is the only writer, 5/5 turns OK.
  • up expired: ownership refusal, nothing written, 5/5 turns OK.
  • down: CLI refreshes locally and succeeds.

Notes:

  • infer audio transcribe with an expired, Gateway-owned sign-in reports No audio transcription provider is configured or ready instead of the ownership message, because the shared hasAvailableAuthForProvider probe maps every auth error to "not available". Nothing is written. Follow-up, not in this PR (the probe has six other callers).
  • auth-triggered model runtime refresh failed: Plugin invocation scope is closed shows in Gateway logs on both main and this branch. It is not caused by this change and did not fail any turn.

Data compatibility: no schema, stored credential shape, config or protocol change. The same stored sign-ins (copied from a real install) load and work before and after.

obviyus and others added 3 commits November 13, 2026 15:33
A local CLI command beside a running Gateway could refresh a shared OAuth
token and store it. The Gateway kept reading its stale copy, and every later
turn failed with "No credentials found for profile". Each command had to
opt in to the state-owner check, and several did not (`infer image/audio/
video/web/embedding`, local `tts convert`, `infer model auth login/logout`).

Enforce ownership once, at the OAuth refresh: a process that does not own
the state uses a still-valid token as is and refuses an expired one before
any write, naming the Gateway. With no Gateway, refresh runs locally as
before.

`infer model auth login/logout` now use the `models auth` state owner and
credential removal. `agent --local`, `agent exec --state-dir`, `tui --local`
and `models status --probe` take state ownership through
`runWithLocalStateOwner`; the duplicate embedded state lock and its four
refusal messages are removed.

Co-authored-by: obviyus <[email protected]>
An exec run redirects its own state directory while it keeps the original
credential scope. Discover the state owner from that scope, so a refresh of
credentials a running Gateway owns is still refused.

Co-authored-by: obviyus <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation cli CLI command changes commands Command implementations agents Agent runtime and tooling size: XL labels Nov 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 31e76d5439495d33087555da73da58a01b801b92
  • Maintainer: @obviyus
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/oauth-manager.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-refresh-failure.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-store.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 13, 2026
@clawsweeper

clawsweeper Bot commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR prevents foreign-owned OAuth refreshes and moves affected credential edits and embedded commands onto existing state owners.

Example: Run openclaw infer audio transcribe beside a Gateway with an OAuth token valid for another 4.5 minutes.

  • Before: The CLI refreshes the token, and a later Gateway turn can fail with No credentials found for profile.
  • After: The CLI uses the valid token without refreshing it, preserving the Gateway's credential ownership.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A useful ownership repair with production-entry-point evidence and focused regressions; no actionable introduced defect was found.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied built-CLI and isolated-Gateway results exercise near-expiry reuse, expired-token refusal, offline refresh, credential-edit ownership, and successful subsequent agent turns; final-head image cases also pass.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A local inference command can leave a running Gateway unable to use a valid OAuth sign-in until restart.
Reason: The maintainer-selected repair restores documented credential ownership with a bounded, explicitly accepted refusal behavior.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR repairs a confirmed shared-credential ownership bug, and review found no actionable introduced defect.

Priority: P1
Reviewed head: 31e76d5439495d33087555da73da58a01b801b92

Before merge

None.

Findings

None.

Agent review details

How this fits together

CLI inference and embedded commands resolve OAuth credentials through the auth-profile manager, which supplies access tokens and coordinates refresh persistence with canonical state ownership.

flowchart TD
  A[Local CLI command] --> B[OAuth manager]
  B --> C[Credential scope and state owner]
  C --> D[Use valid token]
  C --> E[Refuse foreign owned refresh]
  C --> F[Refresh under existing owner]
  D --> G[Provider request]
  F --> G
Loading

Technical review

Best possible solution:

Keep refresh admission in the OAuth manager and reuse the existing state and credential-removal owners for affected commands.

Do we have a high-confidence way to reproduce the issue?

Fetched-main source permits the reported outside refresh, and the supplied CLI/Gateway comparisons demonstrate matching failures; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch repairs the writer boundary, preserves intentional Gateway cache behavior, and replaces competing command-specific custody paths with the existing owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 64fd44bdaae8.

Provenance checked

  • OAuth refresh and peer settlement keeps the original intent (b824b72: Prevent replay or restoration of consumed shared refresh generations through durable claims and exact settlement.)
  • Embedded command custody keeps the original intent (0850790: Prevent embedded CLI writers from mutating canonical state beside a running Gateway and retain custody through cleanup.)
  • Native process signals keeps the original intent (2cd23b6: Use native process signals and state ownership while preserving cancellation and cleanup.)
  • Inference authentication commands changes intended behavior with a stated reason (97c031a: Expose provider authentication through the inference CLI; the PR explains replacing private credential mutations with coordinated models-auth operations. The deeper logout symbol search stopped at an unavailable historical blob.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 1b08795 adds src/cli/local-state-owner.ts:36 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 1b08795ae494; files: src/cli/local-state-owner.ts)
  • Ayaan Zaidi: Raw commit 81daea9 adds src/cli/capability-cli/model.ts:327 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 81daea994d80; files: src/cli/capability-cli/model.ts)

PR surface

Source -73, Tests -365, Docs +5. Total -433 across 30 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 15 251 324 -73
Tests 12 125 490 -365
Docs 3 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 30 381 814 -433

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P1: A local OAuth refresh can leave subsequent Gateway agent turns failing until restart.
  • merge-risk: 🚨 auth-provider: Refresh admission and credential-edit routing change; the maintainer explicitly accepts refusing expired credentials owned by another process.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 13, 2026, 9:02 AM ET / 14:02 UTC.

This branch has not been deployed

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

Labels

agents Agent runtime and tooling cli CLI command changes commands Command implementations docs Improvements or additions to documentation merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant