Skip to content

fix: protect provider and MCP credentials from concurrent CLI writes - #168135

Merged
steipete merged 3 commits into
mainfrom
dbasync/ow1
Oct 10, 2026
Merged

steipete merged 3 commits into
mainfrom
dbasync/ow1

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Related: #167965

What Problem This Solves

Separate CLI processes could write provider and MCP credentials while the Gateway retained older in-process state. Removing foreign-commit probes requires those operations to respect the Gateway's ownership.

User Impact

System/agent models auth commands now require the local Gateway to be stopped, including listing and order inspection whose loaders can admit writable state. MCP login/logout, probes, and saved-server writes refuse live ownership with stop-and-retry guidance. Supported Control UI auth/settings operations remain available online; MCP list/show/status and static doctor remain available.

No schema, stored-byte, retention, durability, permission, or released SDK contract changes. Updates need no migration. The published-driver × candidate update cell passed at the final head; details are below.

Why This Change Was Made

CLI entry points reuse runWithLocalStateOwner and its exclusive offline resource lifetime. Existing Gateway auth RPCs serve UI/browser contracts and cannot preserve CLI profile IDs, partial order lists, imports, or manual-code/loopback flows without a separate API expansion. Accepted worker work and cleanup retain custody. Provider prompt cancellation and MCP error paths unwind through the normal CLI exit owner; callback cancellation closes the loopback listener before release.

MCP configuration mutations share a narrow CLI ownership facade because replacing/removing definitions can clear OAuth credentials and write lifecycle state. The OAuth CLI flow is extracted to keep the existing command registration module within its size ratchet.

Known P2 follow-up: pre-save probes in mcp add and mcp configure --probe can contact/launch a non-OAuth server before the subsequent save refuses live Gateway ownership. Database writes remain fenced. After three P2 review rounds, this is recorded rather than expanded under the requested review-convergence rule. The third round's separate index-only raw-exit finding is fixed in the final tree. No accepted P0/P1 findings remain.

Evidence

  • Baseline regressions: all 13 models-auth command cases entered their domains instead of refusing; MCP OAuth integration entered auth handling instead of returning OWNER_UNAVAILABLE.
  • Focused proof: 98 grouped cases passed (82 infra + 3 MCP import-boundary + 13 models-auth entry points); the offline credential regression passes after moving from the threaded CLI lane to the existing host-process command lane. The existing model CLI suite also passed all 37 cases in the earlier compatibility run. The initial offline fixture failure was the real host-broker guard, not a product defect.
  • Real held Gateway lock + socket + spawned CLI refusal proof: 5 cases passed, including MCP and models-auth commands. Vitest 80.72 s; wrapper 182.22 s (55 unrelated cases filtered).
  • Ran check:changed; repaired the own wrapper-name collision and explicit TypeScript failure flow, then completed its remaining planned commands. Core and core-test types, formatting, all ratchets, import cycles, scripts lint, schema/deprecation-owner checks except the inherited issue below, and the remaining guards passed. The offline fixture was moved to the existing host-process command lane after the worker-thread broker correctly refused it.
  • Madge passed; database-worker ratchet passes with no T1 increase.
  • Knip reports two inherited unused exports (isTelegramReadOnlyControlLaneText, resolveContextTokens), reproduced on the pinned baseline with identical affected blobs on origin/main at confirmation. Both are subsequently fixed on main by afb4f0ff366b (fix(ci): retired exports break main checks #168048); this branch does not touch those exports. No changed-file finding.
  • Plugin SDK API comparison passed: no API changes, acknowledgement digest ff7b090f (427f926e7c2d → 8de0d4b4ccae). Later CLI-only control-flow/naming and fixture corrections do not change the SDK surface.
  • The deprecated-config-writer guard reports untouched src/gateway/server-methods/agents.ts, fixed on main by 959197ba0923.
  • Full core lint reports 13 untouched line-limit violations. Twelve were reproduced against exact current-main source/config at a285e8ba5841; src/plugins/registry-runtime.ts was already fixed on main by 7008414e344e (refactor: consolidate plugin runtime ownership and facades #168006). There are no changed-file lint findings. These inherited failures are reported rather than patched into this scope.
  • Three fresh Codex P2 review rounds: first two scoped-clean; final disposition above. Review is complete under the requested convergence limit.

Statement and worker-request measurements

Three strict alternating pairs compare baseline 427f926e7c2d with provider/MCP candidate 8de0d4b4ccae in separate clean, installed measurement worktrees, on Node 24.21.0 / SQLite 3.53.4 / macOS. The shared workload and native counting logic are unchanged. The private invocation disables evidence archives and adds the campaign transport census. All successful statements on Gateway MAIN, worker threads, and helper processes are included.

The observed warmed median rose by 6.5 statements/turn (+0.57%); worker requests fell by 4.0/turn. This exceeds the generic strict warmed-statement tolerance; no such gate pass is claimed. This follows the lane-specific instruction to report turn SQL for outside-writer routing. This ownership-routing lane claims zero removed chat statements or requests. Its admin commands are absent from the synthetic chat workload, and no changed production file appears in the retained candidate native SQL stacks. The count differences occur in unchanged schema/index admission, freshness, transaction, session, and maintenance owners.

Phase Base ALL Candidate ALL Δ ALL Base MAIN Candidate MAIN Base requests Candidate requests Duration ratio
01.boot 3350 [3348–3354] 3349 [3324–3358] -1 1988 [1984–1988] 1988 [1986–1988] 70 [69–70] 70 [67–72] 0.959
01.connect 293 [274–593] 340 [316–822] +47 61 [35–89] 61 [61–97] 40 [36–65] 41 [36–86] 1.016
02.first-turn 2561 [1823–2587] 1991 [1561–2229] -570 108 [46–129] 70 [46–73] 354 [287–358] 295 [261–313] 0.500
03.warmed 1140.2 [1025.9–1198.8] 1146.7 [1037.9–1198.2] +6.5 17.4 [6.9–18.2] 14.2 [7.8–19.5] 210.6 [196.3–213.1] 206.6 [196.1–211.2] 0.782
04.second-session 4210 [4206–4490] 4512 [4066–4650] +302 136 [130–137] 142 [136–169] 733 [692–740] 722 [710–796] 0.853
05.control-plane 36 [35–213] 36 [33–38] +0 0 [0–16] 0 [0–0] 5 [5–34] 5 [5–7] 1.034
06.cron 1216 [1212–1258] 1418 [1336–1771] +202 37 [26–44] 76 [53–273] 179 [178–185] 212 [197–245] 0.771
07.compaction 425 [403–496] 402 [402–494] -23 29 [25–50] 25 [25–50] 85 [83–98] 83 [83–98] 0.878
08.shutdown 204 [204–208] 204 [200–204] +0 133 [133–136] 133 [133–133] 15 [15–15] 15 [15–15] 2.208

Values are per-phase medians [min–max] across three strict alternating pairs. Warmed counts/requests are per turn; warmed duration is the ten-turn window. All threads and helper processes are included; MAIN is Gateway thread 0.

Phase Base seconds Candidate seconds Candidate/base
01.boot 41.093 [19.371–48.629] 39.422 [13.227–105.500] 0.959
01.connect 2.171 [1.406–3.031] 2.205 [1.898–9.925] 1.016
02.first-turn 23.738 [19.777–34.061] 11.863 [6.105–18.490] 0.500
03.warmed 30.745 [18.839–35.548] 24.036 [17.497–32.466] 0.782
04.second-session 12.024 [7.818–12.179] 10.253 [10.124–18.732] 0.853
05.control-plane 1.191 [1.087–1.291] 1.231 [1.083–1.348] 1.034
06.cron 8.909 [5.398–10.835] 6.866 [5.333–18.337] 0.771
07.compaction 1.503 [1.325–2.133] 1.320 [1.285–1.949] 0.878
08.shutdown 2.712 [1.218–2.823] 5.989 [0.830–6.303] 2.208

All turn and non-shutdown median duration ratios are at most 1.034. Shutdown is an explicit duration-skew gap: 2.712→5.989 seconds (2.208×), while its statement median is unchanged at 204. Candidate runs 1 and 3 logged the unchanged restart.close.skills-watcher taking 4043 ms and 5911 ms. No generic duration-gated shutdown verdict is claimed. All processes exited cleanly. This lane reports observational SQL under the outside-writer instruction; it claims no performance gain and does not infer that every unattributed statement is background.

Additive decomposition compares the actual run supplying each side’s total median (it is not the median of each class). Classes conserve every successful statement. No reduction is claimed as caused by this lane.

02.first-turn: base run 3, candidate run 2.

Statement class Base Candidate Δ
Connection and WAL pragmas 159 91 -68
Foreign-commit version observations 414 352 -62
Other 2 2 +0
Other DDL and temporary staging 175 167 -8
Other row reads 803 691 -112
Row writes 168 145 -23
Schema, table, index, and ownership statements 492 237 -255
Transaction and savepoint envelopes 348 306 -42

03.warmed: base run 1, candidate run 2.

Statement class Base Candidate Δ
Connection and WAL pragmas 44.6 40.3 -4.3
Foreign-commit version observations 235.2 233.5 -1.7
Other DDL and temporary staging 8.4 9.8 +1.4
Other row reads 447.9 440.8 -7.1
Row writes 82.7 80.8 -1.9
Schema, table, index, and ownership statements 103.2 124.9 +21.7
Transaction and savepoint envelopes 218.2 216.6 -1.6

Every one of the six runs completed all 13 top-level turns, the native child, RPCs, cron, compaction, and graceful shutdown. Calibration observed 7 successful statements independently on MAIN and a worker. Native/census conservation was exact for every phase, thread, and SQL. Failed BEGIN IMMEDIATE attempts were base [1,0,0] (shutdown), candidate [0,2,0] (first-turn), all lock contention; none occurred in warmed turns. They are reported separately and excluded from successful-statement totals.

The isolated measurement checkout stayed exactly at 8de0d4b. Later parent-branch changes give offline wrappers explicit names, preserve MCP CLI error unwinding, make existing never-return failure branches explicit for TypeScript, and adjust tests/docs/tooling. Reuse to the final candidate is on the explicitly unchanged measured chat/SQL path basis; these numbers must not be labeled an exact final-head runtime run.

Raw SQL/census traces and fixture databases were removed after aggregation. No evidence archive was created. The final-head published-driver × candidate update cell passed; details are below.

This PR claims zero chat-turn SQL savings and zero removed worker requests. Its changed execution paths are CLI-only. Offline domain SQL remains with the existing store owners, and live refusal prevents those outside-process writes. Any observed harness delta must be attributed to unchanged chat/background stacks; moving work to another thread is not counted as a saving.

Scope and cost

production: +331/−221 (net +110); tests/support: +269/−43 (net +226); docs: +25/−8 (net +17); tooling: +0/−2 (net -2)

All proof commands used --maxWorkers=1. Grouped focused wrapper: 812.02 s on the loaded host, including the now-corrected wrong-lane fixture failure. Existing integration fixtures were reused; real persistence, cleanup, and subprocess ownership account for the longer contract tests. Cold compiled-worker preparation is included in wrapper times.

File Passed cases Test time (grouped run)
src/cli/mcp-cli.import-boundary.test.ts 3 33.649 s
src/cli/mcp-cli.login-loopback.test.ts 3 28.837 s
src/cli/mcp-cli.oauth-integration.test.ts 3 35.910 s
src/cli/mcp-cli.oauth.test.ts 7 83.790 s
src/cli/mcp-cli.test.ts 30 238.950 s
src/cli/models-cli.state-owner.test.ts 13 0.519 s
src/commands/models/auth.test.ts 39 26.297 s
src/commands/models/auth-cli-offline.integration.test.ts 1 20.274 s (standalone wrapper 159.77 s)

Exact-head CI passed in run 38019244555; no CI rerun was used as local proof. Synthetic isolated fixtures only; no operator Gateway or real credentials were modified.

Final-head landing proof

At 65042bd5f6dced25c1d3a1b8591f43ce291bb5ee, one alternating baseline/candidate whole-workload pair on the same Hetzner VM completed successfully. Baseline 427f926e7c2d763e362f59678c6486b6f2f4aec4 executed 22,962 successful statements; candidate executed 22,688 (−274). Warmed statements per turn were 1,095.6 → 1,134.9. The coordinator's whole-workload total gate passed; no chat-turn SQL savings are attributed to this CLI-only change. Each side completed all 13 turns and the existing child, RPC, cron, compaction, and shutdown assertions.

The published 2026.9.9 driver updated to the package built from that exact candidate with legacy SQLite enabled. The cell finished with readiness HTTP 200 and the candidate commit confirmed in its summary. Docker was installed only on the disposable remote proof VM; no local Docker or operator Gateway was used.

@clawsweeper

clawsweeper Bot commented Oct 10, 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 size: L labels Oct 10, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR requires exclusive offline state ownership for provider-auth and MCP credential-writing CLI operations.

Example: Run openclaw models auth logout synthetic:manual --yes while the local Gateway owns the same state directory.

  • Before: The CLI enters the credential-removal domain independently of the Gateway.
  • After: The CLI refuses before credential admission and explains how to stop the Gateway and retry.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful and coherent ownership fencing with meaningful harness coverage; supplied evidence does not establish a separate shipped-entry-point run.
Proof confidence 🦐 gold shrimp (3/6) The task identifies this as maintainer-authored, outside the ordinary contributor proof gate; supplied results exercise registered commands, real locks, HTTP fixtures, SQLite persistence, and cleanup through test harnesses rather than a separately recorded shipped CLI run.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Independent CLI credential writes can leave a running Gateway using older in-process credential state.
Reason: The established area owner explicitly chooses offline custody, preserves supported online UI paths, and explains the CLI contract constraints.

Merge readiness

⛔ Needs changes before merge - 1 item remains

Keep open: this PR provides useful, owner-directed credential fencing that current main lacks, with no definite introduced correctness defect found.

Priority: P2
Reviewed head: 65042bd5f6dced25c1d3a1b8591f43ce291bb5ee

Before merge

  • Complete next step - Complete the pending published-driver × candidate update check with existing provider profiles and MCP credentials preserved before landing.

Findings

None.

Agent review details

How this fits together

CLI registrations select the existing local-state owner before entering credential or configuration domains; that owner either refuses a live Gateway or retains exclusive custody through database settlement and cleanup.

flowchart TD
  A[Provider and MCP CLI commands] --> B[Local state owner]
  B --> C[Live Gateway ownership]
  C --> D[Refusal with recovery guidance]
  B --> E[Exclusive offline custody]
  E --> F[Existing credential and config owners]
  F --> G[Resource cleanup and lock release]
Loading

Technical review

Best possible solution:

Use the existing exclusive ownership lifecycle while preserving online Control UI operations and existing credential formats.

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

Current-main registrations enter mutation-capable auth and MCP domains without this ownership fence; reported baseline regressions demonstrate missing refusal, although this review did not independently reproduce stale credential loss.

Is this the best way to solve the issue?

Reusing the established lock and resource-settlement owner is a coherent fix, and the PR explains why routing the full CLI contract through existing browser RPCs would require separate API work.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 22bca7d84ddc.

Provenance checked

  • Provider-auth CLI ownership changes intended behavior with a stated reason (fix: preserve model login settings and refresh gateway auth #144181: CLI login, logout, and ordering requested acknowledged Gateway auth publication while preserving concurrent settings.)
  • MCP authorization flow keeps the original intent (bf5ce3d: Centralize OAuth identity and expose resumable authorization without changing operator credential keys.)
  • Provider prompt cancellation changes intended behavior with a stated reason (2ada1b7: Available blame traces successful cancellation and immediate process exit to this commit; the PR explains why cancellation must now unwind retained offline resources.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Pinned introduction and current-main comparison: The introduced diff adds ownership fencing to provider-auth registrations and MCP operations. Comparing the merge base with fetched main shows no intervening changes in the three existing production modules central to this PR. (src/cli/models-cli.ts:47, 22bca7d84ddc)
  • Existing ownership lifecycle reused: The MCP facade delegates to runWithLocalStateOwner and existing mutation APIs. The unchanged owner retains its physical lock until maintenance resources finish closing. (src/cli/local-state-owner.ts:229, 65042bd5f6dc)
  • Recorded product direction and accepted tradeoff: The full PR body explicitly chooses offline CLI custody, explains why existing browser-oriented RPCs cannot preserve CLI semantics, and records the non-OAuth pre-save probe limitation as an accepted follow-up. It also assigns the pending published-driver update cell to the lander. (65042bd5f6dc)
  • Production-path harness coverage: Added process cases exercise registered MCP and provider-auth commands against held Gateway ownership; integration coverage checks real credential persistence, cancellation cleanup, OAuth HTTP exchanges, refusal, and unchanged credentials. The body reports passing runs; this review executed no tests. (src/cli/local-state-owner.process.test.ts:805, 65042bd5f6dc)
  • Feature history: Merged refactor(mcp): single OAuth identity owner + resumable authorization session #122115 established resumable MCP authorization with unchanged operator store keys; fix: preserve model login settings and refresh gateway auth #144181 established acknowledged auth publication and preservation of concurrent settings. This PR preserves their credential identities and domain writers while explaining the change to CLI ownership. (src/cli/mcp-cli.ts, bf5ce3d55a9d)
  • Related ownership prerequisite: Open improve: reduce SQLite work during chat turns #167965 removes foreign-commit observations and explicitly lists outside-process credential writers as follow-up work; this PR supplies a distinct provider/MCP ownership lane rather than duplicating that broader change. (b89aab34cfc1)

Likely related people:

  • Peter Steinberger: Raw commit 5b2da46 adds src/commands/models/auth.ts:682 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 5b2da462060a; files: src/commands/models/auth.ts)

PR surface

Source +110, Tests +226, Docs +17, Other -2. Total +351 across 18 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 5 331 221 +110
Tests 10 269 43 +226
Docs 2 25 8 +17
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 2 -2
Total 18 625 274 +351

Review metrics

Metric Value Why it matters
Production versus test growth Production +331/−221; tests/support +269/−43 Production growth connects existing commands to one ownership lifecycle and extracts OAuth control flow; test growth exercises refusal, persistence, and cleanup boundaries.

Labels

Label changes:

  • add P2: Focused credential-concurrency hardening with useful ownership coverage and no demonstrated urgent runtime regression.
  • add merge-risk: 🚨 compatibility: Existing scripts invoking system models-auth or MCP mutation/probe commands beside a running Gateway will now refuse; the owner explicitly accepts and documents this offline requirement.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: Focused credential-concurrency hardening with useful ownership coverage and no demonstrated urgent runtime regression.
  • merge-risk: 🚨 compatibility: Existing scripts invoking system models-auth or MCP mutation/probe commands beside a running Gateway will now refuse; the owner explicitly accepts and documents this offline requirement.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

Reviewed October 9, 2026, 11:11 PM ET / October 10, 2026, 03:11 UTC.

@steipete
steipete merged commit 510255d into main Oct 10, 2026
150 of 152 checks passed
@steipete
steipete deleted the dbasync/ow1 branch October 10, 2026 05:22
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…penclaw#168135)

* fix: protect provider and MCP credentials with offline ownership

* fix: unwind MCP errors before releasing offline ownership

* fix: make MCP refusals explicit and use host-owned auth proof
obviyus added a commit that referenced this pull request Oct 11, 2026
Related: #168135, #168108, #168471

## What Problem This Solves

Fixes API-key setup from the CLI when a running Gateway owns local state.

## User Impact

Users can run `openclaw models auth paste-api-key --provider <id>` without stopping the Gateway. The Gateway saves the key and refreshes its model catalog. Offline behavior is unchanged. An explicit, non-empty `--profile-id` still requires offline use.

## Why This Change Was Made

#168135 correctly stopped CLI processes from writing credentials around a live Gateway. It also kept CLI flows offline where the existing Gateway APIs could not preserve their behavior. Manual API-key setup already uses the same credential writer as `models.authSetApiKey`, so that subset can use the owner instead of refusing.

This change uses the canonical `local-state-owner.ts` route, as in #168108 and #168471. It binds the request to the discovered local owner and port, sends `expectedOwnerId`, requires `operator.admin`, rechecks ownership before dispatch, and never retries a possibly accepted write locally. API-key input is collected only after owner selection. The RPC checks the expected owner at credential and config writes; calls without that field retain their existing behavior. Owner-bound requests preserve the CLI's agent-selection rules.

Update behavior: an older Gateway that lacks `models-auth-set-api-key-owner-v1` is refused before the API-key request; update and restart it, or stop it and retry offline.

No request/response schema, new RPC method, config option, database schema, or paired-device fallback is added.

### Command-to-RPC mapping

| CLI command or option | Existing RPC | Result in this change |
| --- | --- | --- |
| `paste-api-key --provider <id> [--agent <id>]` | `models.authSetApiKey` | Delegate provider, key, and agent; print saved profile and any application warning. |
| `paste-api-key --profile-id <id>` | No profile-id field in `models.authSetApiKey` | Refuse this option with offline guidance. |
| `paste-token [--expires-in <duration>]` | No equivalent API-key write | Stay offline: token type and expiry must not become an API key. |
| `login`, including API-key plugin methods | `models.authLogin` and `wizard.*` | Stay offline: CLI method/profile/default/force semantics are not an exact manual-key mapping. |
| `login-github-copilot` | `models.authLogin` and `wizard.*` | Stay offline; device flow is outside this change. |
| `add` / `setup-token` | No exact generic mapping | Stay offline; these can run local provider CLI or import flows. |
| `list` | `models.authStatus` | Stay offline: the status projection lacks the CLI list's state-path, cooldown, disabled-state, and recovery fields. |
| `logout <profileId> [--yes]` | `models.authLogout` | Deferred; retain current offline behavior. |
| `order get` | `models.authStatus` | Deferred; retain the existing owner-aware read. |
| `order set <profileIds...>` | `models.authOrderSet` | Stay offline: the RPC requires the full profile order; the CLI allows partial lists. |
| `order clear` | `models.authOrderSet` | Deferred; retain offline reset behavior. |
| `activate <profileId>` | No exact test-and-activate mapping | Stay offline. |

## Evidence


ACP CI comparison: `src/gateway/server.chat.acp-completion.test.ts` passed all 12 cases when run directly on PR head `4f32198a3a8f5446e1c24b783d624884415553e6` and on clean main at its exact merge parent `4f3eb4f254664cd0ed1a4b31678e9e4957348d20`. The CI failure in `completes persistence failure after explicit abort once` expected `[start, end]` but received `[end]`; that case passed on both local runs. This does not establish an inherited failure or a PR-caused failure—it records that neither isolated run reproduced it. No code or test assertion was changed.


Latest review repair: removed only the stale `prepareDispatchCurrent` test expectation after #168882 retired that callback. Owner binding, capabilities, authentication, `assertDispatchCurrent`, and no-local-write assertions remain. The requested direct command `node scripts/run-vitest.mjs run src/cli/models-cli.state-owner.test.ts` passed all 16 tests (24.22 seconds total). No retired production callback was restored.

- The new CLI regression fails with the original main-branch auth router: 12 existing refusal cases pass, and API-key delegation fails with `OWNER_UNAVAILABLE`.
- The initial candidate passed 153 targeted tests across CLI ownership, the real API-key writer, Gateway transport, and the real API-key RPC.
- Tests cover cancelled input, no local fallback, old-Gateway capability refusal before request dispatch, and rejected owner changes without credential/config writes.
- Existing unbound API-key RPC requests still pass the real credential-writer test.
- `pnpm build` passed.
- Isolated live profile: piped a real OpenAI key into `pnpm openclaw --profile <profile> models auth paste-api-key --provider openai`. The Gateway picker changed from zero available OpenAI models to one. A real `openclaw agent` turn returned `AUTH_OWNER_OK`, using the saved auth profile. The listener PID stayed the same; no restart was needed.
- The Gateway token was supplied only at runtime and was not in config. The same CLI path worked when it received that token. Without the token, it refused without a local write and named `OPENCLAW_GATEWAY_TOKEN` / `OPENCLAW_GATEWAY_PASSWORD` as the next step.
- An earlier `node scripts/check-changed.mjs --staged` run passed the format, ownership, dependency, and other early guards, then stopped at main's UI-e2e test-root budget (722 versus 720). That result predates the empty-input regression below; no UI files are changed here.

### Review repair: authority at the final write

- The captured requester guard now reaches the auth store's existing SQLite worker admission, not only the updater callback. It also reaches config `beforeCommit` and the config writer's effect-time authority check.
- Credential observation: revoke after the real updater returns, before commit; the operation rejects, the original stored key remains, and config bytes do not change. The permitted control stores the replacement key.
- Config observation: revoke after the transform returns; the operation rejects and the source config remains byte-for-byte unchanged. The already saved, unchanged credential remains intact. The permitted control publishes the auth-profile config.
- The four allowed/revoked controls and 17 auth-store update tests pass. These tests use real credential/config persistence; only the revocation instant is controlled.
- Fixed the two `curly` lint errors in the CLI input adapter. Targeted production lint passes for the adapter, API-key writer, and auth-profile upsert owner.
- After merging main, the changed-file gate passed core typechecking and all 28 core test graphs. It stopped at unrelated unused exports in `extensions/codex/src/app-server/managed-binary.ts`, `tools/solid-lint/index.mjs`, and `ui/src/test-helpers/solid-application-context.tsx`; those files are unchanged by this PR.

### Review repair: configured loopback auth-none

- Owner-bound shared-auth requests now enable the transport's existing bounded auth-none path. A Gateway explicitly configured with `gateway.auth.mode: "none"` uses the backend client identity without creating or reading device credentials. Remote targets and URL overrides retain the existing refusal rules.
- A registered `paste-api-key` regression invokes the real `resolveGatewayCallDeviceAuth` with the owner route's options. It failed before the fix with `GatewayLocalBackendSharedAuthUnavailableError` and passes after the fix. All 105 transport tests and 16 CLI ownership tests pass.
- The latest main was merged after these focused checks. Clean-main export-name collision checking passed at `76a282c7a1c6ca958517ce15f13e17371c14be11`; the channel collision was fixed upstream by `13296b17cd0`. The same clean main reproduced the three lint errors in the untouched plugin-state observation cache and SQLite comparison test. Remaining baseline runs were stopped at maintainer request while upstream CI repairs were being merged.

### Review repair: empty API-key input

- Empty or whitespace-only stdin now reports: `No API key was supplied. Rerun this command and paste a non-empty API key, or pipe one to stdin.`
- Two short tests read real streams and cover both inputs. Both failed with the old `Required` message and pass after this change.
- The changed-file gate passed formatting, core typechecking, and all six selected test graphs. It stopped at the unrelated `GatewayApprovalEventPublisherV2` unused export in `src/gateway/server-instance-runtime.types.ts`, which this repair does not modify.

### Existing CI failures checked on main

- On clean main `aec6e7a56eb03eaba1a648310876d2d6d4811745`, the UI cloud-startup toast-recovery case fails with the same `Control UI readiness hook is unavailable` error as this branch (two cases pass, one fails).
- The same clean main also reproduces the FIFO assertions missing `QUEUED_STEER_A` and `ORDINARY_MESSAGE_B`. Neither test nor its steer behavior is changed by this PR.
- The document-steer case also fails on clean main, but earlier: the initial turn does not reach the mock provider (zero requests). On this branch it reaches the later missing-document assertion. The baseline failure prevents an exact comparison of that later assertion; it is not claimed as an identical local reproduction.
- On the repaired head, [the Node shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301617040) reports the same FIFO failures. A [separate cron shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301616913) reports `hydrates runtime metadata for a reasoning-capable fallback candidate` (expected two calls, received four); its main-branch investigation is separate and no auth change is claimed to fix it.
- `src/cli/plugin-local-state-owner.test.ts` has the same result on this branch (`5033eb75ade`) and clean main (`9a165c492058ddf6fc3468cde27b201514c954f1`): 33 pass, one fails. The failed case is `routes memory search limits and JSON output through the discovered owner`; both report `The memory runtime does not support CLI search` inside `OUTCOME_UNKNOWN`. The fixture supplies a manager but not the `searchForCli` callback now required by the Memory Core handler. This is a main-branch fixture mismatch, not an auth routing regression; no test or routing behavior was changed to hide it.

### CI 38113017692: pinned per-file comparison

Compared PR head `f062e5069509128680db873fa6643d262b034b0b` with its exact main parent `9e444e1078169a5bd1117eaf8b5c50cdca2fde15`. Each file ran through the repository test runner under pueue.

| File | PR result | Main result | Verdict |
| --- | --- | --- | --- |
| `src/gateway/server-methods/models-auth-api-key.integration.test.ts` | 1 failed: corrupt config revision key during startup | Same | Inherited; failure occurs before the auth RPC or acknowledgment |
| `src/gateway/gateway-cli-plugin-routing.test.ts` | 1 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/server-methods/sessions-mutations.sticky-model.test.ts` | 3 failed, 66 passed: two undefined-error assertions and an invalid transcript frame | Same | Inherited |
| `src/gateway/server.sessions.create-worktree-spawn.test.ts` | 1 failed, 18 passed: invalid transcript frame | Same | Inherited |
| `src/gateway/server/ws-connection/connect-device-pairing.test.ts` | 12 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/session-message-events.test.ts` | Setup failed: corrupt config revision key; 30 skipped | Same | Inherited |
| `src/gateway/session-message-events.exec-completion.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/session-message-events.history-worker.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/sessions-history-http.physical-source.test.ts` | 4 failed: corrupt config revision key | Same | Inherited |
| `ui/src/pages/workboard/workboard-native-bundle.e2e.test.ts` | 2 passed (Chromium and WebKit) | Same | CI failure not reproduced on either revision |

The config-revision owner unit file also passes both tests on both revisions. The Gateway integration failures therefore do not establish an auth-specific `configRevisionHash`/`appliedConfigHash` regression: they stop while loading the installation revision key. No corruption check was weakened and no test was changed to bypass startup. Workboard's initial missing dependencies/browser artifact were repaired before the successful comparison runs.

No overlap with protected maintainer changes.

Two-way code change: a revert restores offline-only CLI setup. Keys saved through the Gateway remain saved. The affected paths are local CLI API-key setup and the existing Gateway API-key save handler.

Co-authored-by: Ayaan Zaidi <[email protected]>
obviyus added a commit that referenced this pull request Oct 12, 2026
…168671)

Related: #168588, #168135

## What Problem This Solves

Fixes provider sign-in being refused by `models auth login` and `models auth login-github-copilot` while the local Gateway owns the selected state directory.

## User Impact

Supported OAuth, device-code, and plugin API-key methods use the running local Gateway. The terminal renders the Gateway's URLs, device codes, protected inputs, and model-access choices. Credentials stay with the Gateway; the CLI never writes around it or retries a failed login locally.

Options the existing login RPC cannot represent fail explicitly before sign-in starts. The current default model remains unchanged.

## Why This Change Was Made

The old CLI router treated every interactive login as an offline mutation. The Gateway already owns provider login and wizard sessions, but its start request lacked local-owner binding and the one-shot CLI transport closed the connection immediately after the start response.

Bind login to the discovered owner with an optional `expectedOwnerId` and `models-auth-login-owner-v1`. Retain one authenticated connection for the entire wizard, recheck the local owner before follow-up requests, and cancel/settle that session before releasing terminal resources. A disconnect closes the Gateway-owned login rather than reconnecting or replaying it. OAuth loopback callbacks run on the Gateway host, which is the same machine for this local-owner route.

The Gateway revalidates authority at credential, profile-order, and config publication boundaries. Requests without owner binding retain the Control UI behavior. Declared API-key methods run credential-only for the bound CLI request; this does not change administrator requirements or UI discovery.

| CLI input | Gateway mapping |
| --- | --- |
| `--provider`, `--method` | Select the exact declared plugin login choice; send its `authChoice` to `models.authLogin`. |
| Omitted provider/method | Choose the declared login method in the terminal. |
| `--agent` | Preserve inherited/leaf selection in `agentId`. |
| `--device-code` | Select method `device-code`; conflicting `--method` still refuses. |
| `login-github-copilot` | Select provider `github-copilot`, method `device`. |
| URLs, device codes, manual code, selections | Render wizard steps and send answers through `wizard.next` on the same connection. |
| `--profile-id`, `--force`, `--set-default`, Copilot `--yes` | Refuse before starting: the existing login RPC has no corresponding fields. Offline behavior remains available after stopping the Gateway. |

Methods requiring local provider-CLI import/setup or lacking a supported login declaration remain offline. The wizard result confirms saved/applied outcome; it does not return a per-login profile identifier.

**Update behavior:** no stored-data migration or protocol-version bump. An older Gateway without the method-specific capability receives no login request. Update/restart that Gateway, or stop it and rerun offline. Ambiguous transport outcomes remain `OUTCOME_UNKNOWN`; no local fallback is attempted.

Explicitly configured loopback Gateways with `gateway.auth.mode: "none"` also
support delegated login without a token or device identity. This uses the
existing bounded local-backend resolver, not an arbitrary-URL or remote bypass.

## Evidence

- Review repair at `d0b9c83a53d6e785c1dae0f97ea315718b1e1016`: 208 focused tests passed in 91.6 seconds with one worker. Scoped type-aware lint, production types, and the command/Gateway-method test type shards passed.
- A real `plugins.load.paths` fixture is discovered from the selected read-only config; disabling it or excluding it from the allowlist removes it. The discovery read creates no state database.
- Real Gateway/SQLite/config controls prove: an owner-bound login saves its credential and provider config; a non-admin caller is rejected without starting the provider; revoking the actual requester after asynchronous persistence-lock preparation leaves both credentials and config unchanged. Instrumentation calls the original handler and persistence function; no writer result is mocked.
- Discriminating negative controls fail when the selected config is omitted (provider disappears) or the pre-write authority callback is omitted (the real store receives the synthetic credential after revocation). Both controls were restored before the passing run.
- The unrelated transcript-library CI timeout also reproduces on clean main `4e3818bab0febf3ce265aafab07b0c98b7cf7f16`: two cases pass and the same `Loading meetings…` assertion at line 252 fails. No UI workaround or assertion change is included.

- On the latest input-guidance base, 26 focused tests pass, including real-stream empty/whitespace input checks and registered auth-none login through the real resolver.

- The two new CLI delegation regressions fail against the base CLI with `OWNER_UNAVAILABLE`, then pass with the owner route.
- Focused CLI, Gateway, transport, terminal-wizard, and auth tests pass, including wrong-owner refusal, old-Gateway capability rejection without a request, browser/manual-input races, disconnect cleanup, cancellation, and saved-versus-applied reporting.
- Late-effect negative controls demonstrate that removing config `beforeCommit` or profile-order worker authority allows the forbidden write. The guarded cases preserve the prior state.
- Production TypeScript and the touched command/CLI/Gateway/agent test type shards pass.
- `pnpm build` passed on the auth-behavior revision `b7468f2f035f147351ad0595266c5ace3f90264b` and the import-wiring verification revision `84774791a74683b65cb351ec615a9f1ad6cf5946`. Live commands used the shipped `node openclaw.mjs` launcher against those frozen builds.
- On an isolated local Gateway, `models auth login-github-copilot` rendered `https://github.com/login/device` and a one-time code in the terminal. Repeating this on the final build exercised both lazy imports. Each flow was cancelled without authorizing an account; no Copilot credential was saved, and the Gateway PID remained unchanged.
- `models auth login --provider openai --method api-key`, with a real key supplied only on stdin, changed the isolated Gateway's available OpenAI models from 0 to 16. A real turn returned `AUTH_OWNER_OK` using a saved credential profile. The configured default and listener PID were unchanged; no restart was used.
- At the import-wiring verification revision, 20 focused CLI import/owner tests and the production typecheck passed. The production dead-export scan had no new findings; its remaining `InstalledCodexAppServer` finding also occurred on the repaired #168588 base. No baseline suppressions were added.
- After integrating the updated auth-none base, all 94 focused login tests pass. The new login case drives the registered command through the real auth resolver and verifies backend identity with `deviceIdentity: null`.

No overlap with protected maintainer changes was found on the touched paths.

**Merge danger:** reversible code change; credentials intentionally saved by users remain saved after a revert. The affected surface is system/agent provider login with a running local Gateway and the optional multi-request CLI transport lifetime.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
)

Related: openclaw#168135, openclaw#168108, openclaw#168471

## What Problem This Solves

Fixes API-key setup from the CLI when a running Gateway owns local state.

## User Impact

Users can run `openclaw models auth paste-api-key --provider <id>` without stopping the Gateway. The Gateway saves the key and refreshes its model catalog. Offline behavior is unchanged. An explicit, non-empty `--profile-id` still requires offline use.

## Why This Change Was Made

openclaw#168135 correctly stopped CLI processes from writing credentials around a live Gateway. It also kept CLI flows offline where the existing Gateway APIs could not preserve their behavior. Manual API-key setup already uses the same credential writer as `models.authSetApiKey`, so that subset can use the owner instead of refusing.

This change uses the canonical `local-state-owner.ts` route, as in openclaw#168108 and openclaw#168471. It binds the request to the discovered local owner and port, sends `expectedOwnerId`, requires `operator.admin`, rechecks ownership before dispatch, and never retries a possibly accepted write locally. API-key input is collected only after owner selection. The RPC checks the expected owner at credential and config writes; calls without that field retain their existing behavior. Owner-bound requests preserve the CLI's agent-selection rules.

Update behavior: an older Gateway that lacks `models-auth-set-api-key-owner-v1` is refused before the API-key request; update and restart it, or stop it and retry offline.

No request/response schema, new RPC method, config option, database schema, or paired-device fallback is added.

### Command-to-RPC mapping

| CLI command or option | Existing RPC | Result in this change |
| --- | --- | --- |
| `paste-api-key --provider <id> [--agent <id>]` | `models.authSetApiKey` | Delegate provider, key, and agent; print saved profile and any application warning. |
| `paste-api-key --profile-id <id>` | No profile-id field in `models.authSetApiKey` | Refuse this option with offline guidance. |
| `paste-token [--expires-in <duration>]` | No equivalent API-key write | Stay offline: token type and expiry must not become an API key. |
| `login`, including API-key plugin methods | `models.authLogin` and `wizard.*` | Stay offline: CLI method/profile/default/force semantics are not an exact manual-key mapping. |
| `login-github-copilot` | `models.authLogin` and `wizard.*` | Stay offline; device flow is outside this change. |
| `add` / `setup-token` | No exact generic mapping | Stay offline; these can run local provider CLI or import flows. |
| `list` | `models.authStatus` | Stay offline: the status projection lacks the CLI list's state-path, cooldown, disabled-state, and recovery fields. |
| `logout <profileId> [--yes]` | `models.authLogout` | Deferred; retain current offline behavior. |
| `order get` | `models.authStatus` | Deferred; retain the existing owner-aware read. |
| `order set <profileIds...>` | `models.authOrderSet` | Stay offline: the RPC requires the full profile order; the CLI allows partial lists. |
| `order clear` | `models.authOrderSet` | Deferred; retain offline reset behavior. |
| `activate <profileId>` | No exact test-and-activate mapping | Stay offline. |

## Evidence


ACP CI comparison: `src/gateway/server.chat.acp-completion.test.ts` passed all 12 cases when run directly on PR head `4f32198a3a8f5446e1c24b783d624884415553e6` and on clean main at its exact merge parent `e1b944d4a80ef3b4e0df75f1e324cb4a5ffc08dd`. The CI failure in `completes persistence failure after explicit abort once` expected `[start, end]` but received `[end]`; that case passed on both local runs. This does not establish an inherited failure or a PR-caused failure—it records that neither isolated run reproduced it. No code or test assertion was changed.


Latest review repair: removed only the stale `prepareDispatchCurrent` test expectation after openclaw#168882 retired that callback. Owner binding, capabilities, authentication, `assertDispatchCurrent`, and no-local-write assertions remain. The requested direct command `node scripts/run-vitest.mjs run src/cli/models-cli.state-owner.test.ts` passed all 16 tests (24.22 seconds total). No retired production callback was restored.

- The new CLI regression fails with the original main-branch auth router: 12 existing refusal cases pass, and API-key delegation fails with `OWNER_UNAVAILABLE`.
- The initial candidate passed 153 targeted tests across CLI ownership, the real API-key writer, Gateway transport, and the real API-key RPC.
- Tests cover cancelled input, no local fallback, old-Gateway capability refusal before request dispatch, and rejected owner changes without credential/config writes.
- Existing unbound API-key RPC requests still pass the real credential-writer test.
- `pnpm build` passed.
- Isolated live profile: piped a real OpenAI key into `pnpm openclaw --profile <profile> models auth paste-api-key --provider openai`. The Gateway picker changed from zero available OpenAI models to one. A real `openclaw agent` turn returned `AUTH_OWNER_OK`, using the saved auth profile. The listener PID stayed the same; no restart was needed.
- The Gateway token was supplied only at runtime and was not in config. The same CLI path worked when it received that token. Without the token, it refused without a local write and named `OPENCLAW_GATEWAY_TOKEN` / `OPENCLAW_GATEWAY_PASSWORD` as the next step.
- An earlier `node scripts/check-changed.mjs --staged` run passed the format, ownership, dependency, and other early guards, then stopped at main's UI-e2e test-root budget (722 versus 720). That result predates the empty-input regression below; no UI files are changed here.

### Review repair: authority at the final write

- The captured requester guard now reaches the auth store's existing SQLite worker admission, not only the updater callback. It also reaches config `beforeCommit` and the config writer's effect-time authority check.
- Credential observation: revoke after the real updater returns, before commit; the operation rejects, the original stored key remains, and config bytes do not change. The permitted control stores the replacement key.
- Config observation: revoke after the transform returns; the operation rejects and the source config remains byte-for-byte unchanged. The already saved, unchanged credential remains intact. The permitted control publishes the auth-profile config.
- The four allowed/revoked controls and 17 auth-store update tests pass. These tests use real credential/config persistence; only the revocation instant is controlled.
- Fixed the two `curly` lint errors in the CLI input adapter. Targeted production lint passes for the adapter, API-key writer, and auth-profile upsert owner.
- After merging main, the changed-file gate passed core typechecking and all 28 core test graphs. It stopped at unrelated unused exports in `extensions/codex/src/app-server/managed-binary.ts`, `tools/solid-lint/index.mjs`, and `ui/src/test-helpers/solid-application-context.tsx`; those files are unchanged by this PR.

### Review repair: configured loopback auth-none

- Owner-bound shared-auth requests now enable the transport's existing bounded auth-none path. A Gateway explicitly configured with `gateway.auth.mode: "none"` uses the backend client identity without creating or reading device credentials. Remote targets and URL overrides retain the existing refusal rules.
- A registered `paste-api-key` regression invokes the real `resolveGatewayCallDeviceAuth` with the owner route's options. It failed before the fix with `GatewayLocalBackendSharedAuthUnavailableError` and passes after the fix. All 105 transport tests and 16 CLI ownership tests pass.
- The latest main was merged after these focused checks. Clean-main export-name collision checking passed at `25b2400af13218f379b306a2e4cc504288f320eb`; the channel collision was fixed upstream by `2f395451b88`. The same clean main reproduced the three lint errors in the untouched plugin-state observation cache and SQLite comparison test. Remaining baseline runs were stopped at maintainer request while upstream CI repairs were being merged.

### Review repair: empty API-key input

- Empty or whitespace-only stdin now reports: `No API key was supplied. Rerun this command and paste a non-empty API key, or pipe one to stdin.`
- Two short tests read real streams and cover both inputs. Both failed with the old `Required` message and pass after this change.
- The changed-file gate passed formatting, core typechecking, and all six selected test graphs. It stopped at the unrelated `GatewayApprovalEventPublisherV2` unused export in `src/gateway/server-instance-runtime.types.ts`, which this repair does not modify.

### Existing CI failures checked on main

- On clean main `e99d1a8c933639bea9961f7731624eb1ef3f3615`, the UI cloud-startup toast-recovery case fails with the same `Control UI readiness hook is unavailable` error as this branch (two cases pass, one fails).
- The same clean main also reproduces the FIFO assertions missing `QUEUED_STEER_A` and `ORDINARY_MESSAGE_B`. Neither test nor its steer behavior is changed by this PR.
- The document-steer case also fails on clean main, but earlier: the initial turn does not reach the mock provider (zero requests). On this branch it reaches the later missing-document assertion. The baseline failure prevents an exact comparison of that later assertion; it is not claimed as an identical local reproduction.
- On the repaired head, [the Node shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301617040) reports the same FIFO failures. A [separate cron shard](https://github.com/openclaw/openclaw/actions/runs/38082252267/job/114301616913) reports `hydrates runtime metadata for a reasoning-capable fallback candidate` (expected two calls, received four); its main-branch investigation is separate and no auth change is claimed to fix it.
- `src/cli/plugin-local-state-owner.test.ts` has the same result on this branch (`5033eb75ade`) and clean main (`45943833ee81802976d1e7ef0650d668b13b6f5a`): 33 pass, one fails. The failed case is `routes memory search limits and JSON output through the discovered owner`; both report `The memory runtime does not support CLI search` inside `OUTCOME_UNKNOWN`. The fixture supplies a manager but not the `searchForCli` callback now required by the Memory Core handler. This is a main-branch fixture mismatch, not an auth routing regression; no test or routing behavior was changed to hide it.

### CI 38113017692: pinned per-file comparison

Compared PR head `f062e5069509128680db873fa6643d262b034b0b` with its exact main parent `fece4b1cfc8b5778c0e8f69a8c9899f548038819`. Each file ran through the repository test runner under pueue.

| File | PR result | Main result | Verdict |
| --- | --- | --- | --- |
| `src/gateway/server-methods/models-auth-api-key.integration.test.ts` | 1 failed: corrupt config revision key during startup | Same | Inherited; failure occurs before the auth RPC or acknowledgment |
| `src/gateway/gateway-cli-plugin-routing.test.ts` | 1 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/server-methods/sessions-mutations.sticky-model.test.ts` | 3 failed, 66 passed: two undefined-error assertions and an invalid transcript frame | Same | Inherited |
| `src/gateway/server.sessions.create-worktree-spawn.test.ts` | 1 failed, 18 passed: invalid transcript frame | Same | Inherited |
| `src/gateway/server/ws-connection/connect-device-pairing.test.ts` | 12 failed: corrupt config revision key | Same | Inherited |
| `src/gateway/session-message-events.test.ts` | Setup failed: corrupt config revision key; 30 skipped | Same | Inherited |
| `src/gateway/session-message-events.exec-completion.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/session-message-events.history-worker.test.ts` | Setup failed: corrupt config revision key; 2 skipped | Same | Inherited |
| `src/gateway/sessions-history-http.physical-source.test.ts` | 4 failed: corrupt config revision key | Same | Inherited |
| `ui/src/pages/workboard/workboard-native-bundle.e2e.test.ts` | 2 passed (Chromium and WebKit) | Same | CI failure not reproduced on either revision |

The config-revision owner unit file also passes both tests on both revisions. The Gateway integration failures therefore do not establish an auth-specific `configRevisionHash`/`appliedConfigHash` regression: they stop while loading the installation revision key. No corruption check was weakened and no test was changed to bypass startup. Workboard's initial missing dependencies/browser artifact were repaired before the successful comparison runs.

No overlap with protected maintainer changes.

Two-way code change: a revert restores offline-only CLI setup. Keys saved through the Gateway remain saved. The affected paths are local CLI API-key setup and the existing Gateway API-key save handler.

Co-authored-by: Ayaan Zaidi <[email protected]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 12, 2026
…penclaw#168671)

Related: openclaw#168588, openclaw#168135

## What Problem This Solves

Fixes provider sign-in being refused by `models auth login` and `models auth login-github-copilot` while the local Gateway owns the selected state directory.

## User Impact

Supported OAuth, device-code, and plugin API-key methods use the running local Gateway. The terminal renders the Gateway's URLs, device codes, protected inputs, and model-access choices. Credentials stay with the Gateway; the CLI never writes around it or retries a failed login locally.

Options the existing login RPC cannot represent fail explicitly before sign-in starts. The current default model remains unchanged.

## Why This Change Was Made

The old CLI router treated every interactive login as an offline mutation. The Gateway already owns provider login and wizard sessions, but its start request lacked local-owner binding and the one-shot CLI transport closed the connection immediately after the start response.

Bind login to the discovered owner with an optional `expectedOwnerId` and `models-auth-login-owner-v1`. Retain one authenticated connection for the entire wizard, recheck the local owner before follow-up requests, and cancel/settle that session before releasing terminal resources. A disconnect closes the Gateway-owned login rather than reconnecting or replaying it. OAuth loopback callbacks run on the Gateway host, which is the same machine for this local-owner route.

The Gateway revalidates authority at credential, profile-order, and config publication boundaries. Requests without owner binding retain the Control UI behavior. Declared API-key methods run credential-only for the bound CLI request; this does not change administrator requirements or UI discovery.

| CLI input | Gateway mapping |
| --- | --- |
| `--provider`, `--method` | Select the exact declared plugin login choice; send its `authChoice` to `models.authLogin`. |
| Omitted provider/method | Choose the declared login method in the terminal. |
| `--agent` | Preserve inherited/leaf selection in `agentId`. |
| `--device-code` | Select method `device-code`; conflicting `--method` still refuses. |
| `login-github-copilot` | Select provider `github-copilot`, method `device`. |
| URLs, device codes, manual code, selections | Render wizard steps and send answers through `wizard.next` on the same connection. |
| `--profile-id`, `--force`, `--set-default`, Copilot `--yes` | Refuse before starting: the existing login RPC has no corresponding fields. Offline behavior remains available after stopping the Gateway. |

Methods requiring local provider-CLI import/setup or lacking a supported login declaration remain offline. The wizard result confirms saved/applied outcome; it does not return a per-login profile identifier.

**Update behavior:** no stored-data migration or protocol-version bump. An older Gateway without the method-specific capability receives no login request. Update/restart that Gateway, or stop it and rerun offline. Ambiguous transport outcomes remain `OUTCOME_UNKNOWN`; no local fallback is attempted.

Explicitly configured loopback Gateways with `gateway.auth.mode: "none"` also
support delegated login without a token or device identity. This uses the
existing bounded local-backend resolver, not an arbitrary-URL or remote bypass.

## Evidence

- Review repair at `d0b9c83a53d6e785c1dae0f97ea315718b1e1016`: 208 focused tests passed in 91.6 seconds with one worker. Scoped type-aware lint, production types, and the command/Gateway-method test type shards passed.
- A real `plugins.load.paths` fixture is discovered from the selected read-only config; disabling it or excluding it from the allowlist removes it. The discovery read creates no state database.
- Real Gateway/SQLite/config controls prove: an owner-bound login saves its credential and provider config; a non-admin caller is rejected without starting the provider; revoking the actual requester after asynchronous persistence-lock preparation leaves both credentials and config unchanged. Instrumentation calls the original handler and persistence function; no writer result is mocked.
- Discriminating negative controls fail when the selected config is omitted (provider disappears) or the pre-write authority callback is omitted (the real store receives the synthetic credential after revocation). Both controls were restored before the passing run.
- The unrelated transcript-library CI timeout also reproduces on clean main `c5029c5631d37c72df8c96007ccc29bc7db006f9`: two cases pass and the same `Loading meetings…` assertion at line 252 fails. No UI workaround or assertion change is included.

- On the latest input-guidance base, 26 focused tests pass, including real-stream empty/whitespace input checks and registered auth-none login through the real resolver.

- The two new CLI delegation regressions fail against the base CLI with `OWNER_UNAVAILABLE`, then pass with the owner route.
- Focused CLI, Gateway, transport, terminal-wizard, and auth tests pass, including wrong-owner refusal, old-Gateway capability rejection without a request, browser/manual-input races, disconnect cleanup, cancellation, and saved-versus-applied reporting.
- Late-effect negative controls demonstrate that removing config `beforeCommit` or profile-order worker authority allows the forbidden write. The guarded cases preserve the prior state.
- Production TypeScript and the touched command/CLI/Gateway/agent test type shards pass.
- `pnpm build` passed on the auth-behavior revision `b7468f2f035f147351ad0595266c5ace3f90264b` and the import-wiring verification revision `84774791a74683b65cb351ec615a9f1ad6cf5946`. Live commands used the shipped `node openclaw.mjs` launcher against those frozen builds.
- On an isolated local Gateway, `models auth login-github-copilot` rendered `https://github.com/login/device` and a one-time code in the terminal. Repeating this on the final build exercised both lazy imports. Each flow was cancelled without authorizing an account; no Copilot credential was saved, and the Gateway PID remained unchanged.
- `models auth login --provider openai --method api-key`, with a real key supplied only on stdin, changed the isolated Gateway's available OpenAI models from 0 to 16. A real turn returned `AUTH_OWNER_OK` using a saved credential profile. The configured default and listener PID were unchanged; no restart was used.
- At the import-wiring verification revision, 20 focused CLI import/owner tests and the production typecheck passed. The production dead-export scan had no new findings; its remaining `InstalledCodexAppServer` finding also occurred on the repaired openclaw#168588 base. No baseline suppressions were added.
- After integrating the updated auth-none base, all 94 focused login tests pass. The new login case drives the registered command through the real auth resolver and verifies backend identity with `deviceIdentity: null`.

No overlap with protected maintainer changes was found on the touched paths.

**Merge danger:** reversible code change; credentials intentionally saved by users remain saved after a revert. The affected surface is system/agent provider login with a running local Gateway and the optional multi-request CLI transport lifetime.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cli CLI command changes commands Command implementations docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: L status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant