Repository navigation
fix(auth): keep session account selection after OAuth re-login - #149591
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed September 27, 2026, 8:35 AM ET / 12:35 UTC (Revision 17). ClawSweeper reviewWhat this changesThe PR preserves a session’s selected credential profile after a verified same-account OAuth re-login and logs guidance when an explicit selection remains unavailable. Regression provenancePossible regression — probable (reproduction; failure trace). No predecessor PR is attributed. Merge readiness✅ Ready for maintainer review The fix remains absent from current main and the linked issue is open. The previous review found no code defect, and its exact-head security-approval blocker is now resolved; this read-only review found no further blocker. Priority: P0 Review scores
Verification
How this fits togetherProvider login writes credentials to OpenClaw’s auth-profile store. Agent sessions keep a selected profile ID, which the Gateway uses to choose credentials for later turns. flowchart LR
A[OAuth sign-in] --> B[Provider account match]
C[Existing credentials] --> B
B --> D[Transactional credential write]
D --> E[Auth-profile store]
F[Session account selection] --> G[Gateway auth resolution]
E --> G
G --> H[Model turn or recovery warning]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +134, Tests +374, Docs +2. Total +510 across 10 files. View PR surface stats
Review metrics
Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Technical reviewBest possible solution: Keep the approved same-account check at credential persistence, preserve strict explicit pins for other accounts, and retain the documented deliberate recovery path for credentials lost before upgrade. Do we have a high-confidence way to reproduce the issue? Yes. The PR reports a baseline CLI and Gateway flow in which forced same-account re-login changes the credential ID and the explicitly pinned next turn fails; fetched main still contains that login path. I did not execute repository code in this read-only review. Is this the best way to solve the issue? Yes. Preserving the verified account’s ID at the credential writer repairs subsequent turns without guessing a missing account at runtime or changing the session protocol. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 9ca49c5ac159. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (16 earlier review cycles; latest 8 shown)
|
There was a problem hiding this comment.
🔵 Needs a closer look
Unresolved moderate review findings require fixes before approval.
Pull request overview
This PR preserves OAuth session account selections across re-login and adds explicit clearing via authProfileId: null.
Changes:
- Reuse uniquely matched local OAuth profiles.
- Add validated session account-selection reset support.
- Update diagnostics, tests, protocol documentation, and changelog.
File summaries
| File | Summary |
|---|---|
src/system-agent/setup-inference-activate.test.ts |
Tests credential preservation during setup activation. |
src/shared/session-method-scopes.test.ts |
Tests scope classification for account-reset mutations. |
src/shared/session-method-scopes-base.ts |
Authorizes session account-reset writes. |
src/gateway/sessions-patch.test.ts |
Tests reset, conflict, and restriction behavior. |
src/gateway/sessions-patch-display-metadata.ts |
Applies account-reset changes to session metadata. |
src/gateway/sessions-patch-account-selection.ts |
Clears saved account selections. Moderate (1 vote): queued follow-up work may retain stale profile data without a queue refresh. |
src/commands/models/auth.ts |
Matches existing provider account profiles. Moderate (1 vote): matcher failures must fail closed, and imported credentials must apply local-owner filtering. |
src/commands/models/auth.test.ts |
Tests profile identity matching and ambiguity. |
src/agents/auth-profiles/session-override.ts |
Reports unavailable explicit pins. Moderate (1 vote): direct operators to clear or reconnect with the same profile ID. Nit (1 vote): add focused diagnostic assertions. |
packages/gateway-protocol/src/sessions-patch-auth-profile.test.ts |
Tests protocol validation. |
packages/gateway-protocol/src/schema/sessions-patch.ts |
Defines the nullable field for both RPC shapes. Moderate (1 vote): add runtime patchMany coverage. |
packages/gateway-protocol/CHANGELOG.md |
Records the protocol addition. |
docs/gateway/protocol/rpc-session-control.md |
Documents reset behavior. |
docs/auth-credential-semantics.md |
Documents OAuth identity preservation. |
Review details
Suppressed comments (6)
packages/gateway-protocol/src/schema/sessions-patch.ts:73
- The new field is documented and validated for both RPC shapes, but the Gateway behavior test only exercises
sessions.patch; there is no runtimesessions.patchManycase proving that each target clears the profile, provenance, and compaction marker. Add a batch mutation test so the advertisedpatchManycontract is protected beyond schema validation.
/** Clear the session's saved model-account selection and return to automatic selection. */
authProfileId: Type.Optional(Type.Null()),
src/agents/auth-profiles/session-override.ts:377
- This is the new user-visible diagnostic for an unmaterialized explicit pin, but the existing session-override tests do not assert it. A regression that removes the warning or drops
sessionKey/profileIdwould still pass while the issue's diagnosability guarantee is broken; add a focused unavailable-user-pin case that spies onauthProfilesLog.warn.
authProfilesLog.warn(
"selected session auth profile is unavailable; explicit pin remains strict",
{
event: "session_auth_profile_unavailable",
sessionKey,
profileId: currentProfileId,
recovery: "reconnect this account or clear the session account selection",
tags: ["auth_profiles", "session_recovery"],
},
src/agents/auth-profiles/session-override.ts:375
- At this branch
store.profiles[currentProfileId]is already absent, and the new login matching logic only reuses an id found in the runtime-local store. A normal reconnect therefore creates another profile id and leaves this explicit pin unavailable; reconnect is only a recovery if the caller explicitly reuses the old profile id. Please make this warning direct the operator to clear the selection or reconnect with the same profile id.
recovery: "reconnect this account or clear the session account selection",
src/commands/models/auth.ts:1087
- A matcher exception is treated as if that profile simply did not match, so a thrown callback for one existing profile can still leave exactly one successful match and remap the new credential. That is not fail-closed: the uninspectable profile could represent the same account, making the reuse ambiguous. Track whether any matcher invocation failed and retain
params.result.profileswhenever it does.
.filter(([, credential]) => {
try {
return params.matchesPersonalAccount?.(profile.credential, credential) === true;
} catch {
return false;
src/commands/models/auth.ts:1230
- This local-profile snapshot is only consumed by
runProviderAuthMethod, buttryImportProviderCredentialreturns before that call for methods withcredentialImport(including OpenAI OAuth). The import owner selects its ID withitemProfileTarget, which scans the merged store and can match an inherited profile on a secondary agent, bypassing the local-only filtering added here. A same-account imported login can therefore still reuse an inherited ID, contrary to the stated inherited-profile behavior; apply the same local-owner rule in the import/migration path or route imported results through one shared resolver.
const existingProfiles = (() => {
if (!chosenMethod.matchesPersonalAccount) {
return undefined;
}
const store = loadAuthProfileStoreWithoutExternalProfiles(context.agentDir);
src/gateway/sessions-patch-account-selection.ts:26
- When a session has queued follow-up work, those
FollowupRuns carryauthProfileIdand its source independently of the persisted entry. This patch only deletes the fields fromnext, while the post-commit queue refresh currently runs only whenagentRuntimeis present, soauthProfileId: nullleaves queued items andlastRunpinned to the stale profile and they can still fail before automatic account resolution. Update the queue refresh path for this field and add a regression covering queued work.
delete next.authProfileOverride;
delete next.authProfileOverrideSource;
delete next.authProfileOverrideCompactionCount;
- Files reviewed: 14/14 changed files
- Comments generated: 0
- Review effort level: Lite
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
e2bdfe9 to
6839af2
Compare
2cd5e18 to
0ebf6ec
Compare
5d3d6a8 to
e23710b
Compare
|
@clawsweeper re-review |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
Maintainer decision (Ayaan): approved. After |
|
@clawsweeper re-review |
|
🦞👀 Re-review progress:
|
|
/allow-security-sensitive-change |
|
@clawsweeper re-review The exact-head security approval was posted after the prior review: #149591 (comment) . Security-sensitive review and CI are now green for d69620a (CI run 36317977611). No source change since your review. |
|
🦞👀 Re-review progress:
|
|
Thanks @zachisfine for reporting this and contributing the fix. Same-account OAuth re-login now preserves the selected profile ID, including after an explicit force purge, without silently switching a pinned session to another account. The narrower fix removes the reset API and unrelated import changes. Verified with real Gateway/CLI device-code flow against a local OAuth/model server, restart/resume, account-isolation and automatic-pin controls, plus unchanged schema checks; focused tests and exact-head CI passed. Ayaan approved the account-continuity tradeoff and the security-sensitive changes. |
…law#149591) Closes openclaw#149502 ## What Problem This Solves Fixes: an explicitly pinned conversation loses its credential when OAuth re-login replaces the same account's generated profile ID. ## User Impact Signing back into one unambiguously matched account preserves its existing profile ID and session selection. Different or ambiguous accounts do not take over an explicit pin. A missing pin stays strict and now logs actionable recovery guidance. There is no new session permission, protocol field, SQLite migration, schema version, or stored field. Upgrade does not rewrite credentials or session rows. If a credential was already deleted before upgrading, the operator must deliberately select a configured `model@profile` or reconnect the intended account with `models auth login --provider <provider> --profile-id <selected-profile-id>`; the missing identity is never guessed. ## Why This Change Was Made Keep only same-account continuity at the login owner, with the pre-purge snapshot, provider identity matcher, and write-transaction revalidation. Runtime fallback cannot establish the identity of a deleted credential and could silently switch accounts. A separate reset API adds protocol and permission surface without preventing the failure. The existing explicit selection/reconnect paths cover deliberate recovery, so the proposed reset API and unrelated Codex import changes were removed. The large mocked identity suite was replaced by focused ambiguity/error/override cases; the real persistence cases retain continuity and concurrent-reassignment coverage. [Maintainer decision (Ayaan): approved](openclaw#149591 (comment)). Verified same-account sign-in may restore the former profile ID after an explicit force purge; different, ambiguous, or unverifiable accounts do not reuse an ID. There is no new session-reset permission or schema change. Missing pre-upgrade identities continue to require deliberate operator recovery. No overlap with Pash/Sarah changes. ## Evidence - Reproduced on pinned main `aa004732af47`: the production `models auth login` flow (`runModelsAuthLoginFlowCore`) with an isolated scripted OAuth plugin wrote a new ID after forced re-login; the unchanged user-pinned session failed with `No credentials found for profile`. - The smaller change kept the original ID after same-account re-login and resolved OAuth for the same session written by main. Different-account forced re-login left the explicit pin unavailable, logged the recovery diagnostic, and did not select the new account. Automatic pins resolved the new profile on both main and the candidate. - The already-broken main-written row recovered through the existing explicit `--profile-id` reconnect path. The user-pinned row, including its internal session ID and timestamps, was unchanged by re-login and auth resolution. - Before/after SQLite checks were identical: shared `user_version=19`, agent `user_version=23`; ordered `sqlite_schema` SHA-256 values were `42e3cb1d5e4a44081e99a2991c43a8fa77675c6d8ebc74886a7aab38700df36a` (shared) and `d6596c675858b8fdbccced25f9626164634b772ea200830f03c99586ded62b1f` (agent). - 36 focused tests passed across identity boundaries, production persistence, and session selection after merging main. Typechecking rooted at the touched files and type-aware lint passed. The three-file test command took 46.56 seconds wall time including worker preparation; the five persistence cases took about 1.03 seconds of test execution. Hosted CI timing is pending. - After the approved main refresh to `d1366b165c52`, head `d69620a27208` passed all 36 focused tests again (33.35 seconds wall time). The ten PR files are unchanged from the fully exercised `6b25647966e4` revision, and the Pash/Sarah intent check still has no overlap. - The contributor's previously recorded real OpenAI device-code/two-turn/restart evidence applies to the retained identity-preserving login mechanism. The initial simplification proof above used synthetic OAuth credentials and auth resolution; the full network proof below additionally exercises the production CLI and real Gateway model turns without paid services. ### Full CLI/Gateway network proof On `6b25647966e4`, a separate loopback HTTP provider served real device-code, authorization, token, and OpenAI-compatible model endpoints. The same driver on both refs used `pnpm openclaw`, a real PTY for `models auth login`, isolated HOME/state/ports, Gateway-backed agent turns, and the dashboard account picker's `sessions.patch` request (`model@profile`). After forced same-account login without `--profile-id` and Gateway restart, the candidate returned the scripted account-A response in the same session (`8f7ec68c-b05f-4c0b-b12b-6d01ced4bd71`) with its explicit user pin intact. Main failed the equivalent next turn with `selected_auth_profile_unavailable`. Both refs rejected a pinned account-A turn after login as account B; the error was visible in CLI output and no account-B answer was substituted. A separate real `chat.send` control created persisted `authProfileOverrideSource: "auto"` sessions on both refs. After re-login as B and restart, the same sessions completed another turn, `chat.history` contained the account-B response, and each automatic pin rotated to the new credential while retaining source `auto`. Both schema hashes were unchanged across this control. Explicit `--profile-id` reconnect plus restart also recovered the original user-pinned conversation on both refs. The candidate's full schema hashes and versions remained unchanged throughout: shared version 19/hash `b691989fd451644ad9c0233eb04359bde42744456b1532a94ecd32e1ca429859`, agent version 23/hash `d6596c675858b8fdbccced25f9626164634b772ea200830f03c99586ded62b1f`. A separate before/after CLI re-login check found both complete session rows deeply equal as parsed JSON. Turns themselves appropriately update transcript/activity data. **Baseline/build limitations:** `d1f0e816a84a` and `aa004732af47` fail their supported runtime wrapper on the known `INEFFECTIVE_DYNAMIC_IMPORT` guard for `transcript-visible-record.ts`. The full network baseline is `666de566c4c6`, immediately before the commit introducing that import; its fresh runtime build succeeded. OAuth login, credential writer/persistence, and account-picker model-selection behavior are unchanged between that baseline and the PR merge base; intervening relevant changes factor session-selection helpers and clean up manual API-key input handling. Broader OAuth refresh-peer changes are not exercised by nonexpiring fixture credentials. The candidate's full build completed; it does not change the offending import, and the reason the warning differs with its bundle graph is not established. The older main baseline's optimizer created SQLite-owned `sqlite_stat1` during the flow, changing its full agent-schema hash; excluding that single statistics-table definition exactly recovers its initial hash. Its application schema and versions did not change. The older baseline also lacks an unrelated upstream `worktrees.gc_protection_json` column, so cross-ref shared hashes differ; the earlier current-main existing-state proof above supplies the unchanged-schema upgrade comparison. No schema changes belong to this PR. Co-authored-by: Ayaan Zaidi <[email protected]>
Closes #149502
What Problem This Solves
Fixes: an explicitly pinned conversation loses its credential when OAuth re-login replaces the same account's generated profile ID.
User Impact
Signing back into one unambiguously matched account preserves its existing profile ID and session selection. Different or ambiguous accounts do not take over an explicit pin. A missing pin stays strict and now logs actionable recovery guidance.
There is no new session permission, protocol field, SQLite migration, schema version, or stored field. Upgrade does not rewrite credentials or session rows. If a credential was already deleted before upgrading, the operator must deliberately select a configured
model@profileor reconnect the intended account withmodels auth login --provider <provider> --profile-id <selected-profile-id>; the missing identity is never guessed.Why This Change Was Made
Keep only same-account continuity at the login owner, with the pre-purge snapshot, provider identity matcher, and write-transaction revalidation. Runtime fallback cannot establish the identity of a deleted credential and could silently switch accounts. A separate reset API adds protocol and permission surface without preventing the failure. The existing explicit selection/reconnect paths cover deliberate recovery, so the proposed reset API and unrelated Codex import changes were removed. The large mocked identity suite was replaced by focused ambiguity/error/override cases; the real persistence cases retain continuity and concurrent-reassignment coverage.
Maintainer decision (Ayaan): approved. Verified same-account sign-in may restore the former profile ID after an explicit force purge; different, ambiguous, or unverifiable accounts do not reuse an ID. There is no new session-reset permission or schema change. Missing pre-upgrade identities continue to require deliberate operator recovery.
No overlap with Pash/Sarah changes.
Evidence
ea3c488f4fb6: the productionmodels auth loginflow (runModelsAuthLoginFlowCore) with an isolated scripted OAuth plugin wrote a new ID after forced re-login; the unchanged user-pinned session failed withNo credentials found for profile.--profile-idreconnect path. The user-pinned row, including its internal session ID and timestamps, was unchanged by re-login and auth resolution.user_version=19, agentuser_version=23; orderedsqlite_schemaSHA-256 values were42e3cb1d5e4a44081e99a2991c43a8fa77675c6d8ebc74886a7aab38700df36a(shared) andd6596c675858b8fdbccced25f9626164634b772ea200830f03c99586ded62b1f(agent).32dcd02906ef, headd69620a27208passed all 36 focused tests again (33.35 seconds wall time). The ten PR files are unchanged from the fully exercised6b25647966e4revision, and the Pash/Sarah intent check still has no overlap.Full CLI/Gateway network proof
On
6b25647966e4, a separate loopback HTTP provider served real device-code, authorization, token, and OpenAI-compatible model endpoints. The same driver on both refs usedpnpm openclaw, a real PTY formodels auth login, isolated HOME/state/ports, Gateway-backed agent turns, and the dashboard account picker'ssessions.patchrequest (model@profile). After forced same-account login without--profile-idand Gateway restart, the candidate returned the scripted account-A response in the same session (8f7ec68c-b05f-4c0b-b12b-6d01ced4bd71) with its explicit user pin intact. Main failed the equivalent next turn withselected_auth_profile_unavailable.Both refs rejected a pinned account-A turn after login as account B; the error was visible in CLI output and no account-B answer was substituted. A separate real
chat.sendcontrol created persistedauthProfileOverrideSource: "auto"sessions on both refs. After re-login as B and restart, the same sessions completed another turn,chat.historycontained the account-B response, and each automatic pin rotated to the new credential while retaining sourceauto. Both schema hashes were unchanged across this control. Explicit--profile-idreconnect plus restart also recovered the original user-pinned conversation on both refs.The candidate's full schema hashes and versions remained unchanged throughout: shared version 19/hash
b691989fd451644ad9c0233eb04359bde42744456b1532a94ecd32e1ca429859, agent version 23/hashd6596c675858b8fdbccced25f9626164634b772ea200830f03c99586ded62b1f. A separate before/after CLI re-login check found both complete session rows deeply equal as parsed JSON. Turns themselves appropriately update transcript/activity data.Baseline/build limitations:
9ae6e1853062andea3c488f4fb6fail their supported runtime wrapper on the knownINEFFECTIVE_DYNAMIC_IMPORTguard fortranscript-visible-record.ts. The full network baseline isa4656d4eea79, immediately before the commit introducing that import; its fresh runtime build succeeded. OAuth login, credential writer/persistence, and account-picker model-selection behavior are unchanged between that baseline and the PR merge base; intervening relevant changes factor session-selection helpers and clean up manual API-key input handling. Broader OAuth refresh-peer changes are not exercised by nonexpiring fixture credentials. The candidate's full build completed; it does not change the offending import, and the reason the warning differs with its bundle graph is not established.The older main baseline's optimizer created SQLite-owned
sqlite_stat1during the flow, changing its full agent-schema hash; excluding that single statistics-table definition exactly recovers its initial hash. Its application schema and versions did not change. The older baseline also lacks an unrelated upstreamworktrees.gc_protection_jsoncolumn, so cross-ref shared hashes differ; the earlier current-main existing-state proof above supplies the unchanged-schema upgrade comparison. No schema changes belong to this PR.