Skip to content

fix(auth): keep session account selection after OAuth re-login - #149591

Merged
obviyus merged 17 commits into
openclaw:mainfrom
zachisfine:fix/session-auth-profile-replacement
Sep 27, 2026
Merged

obviyus merged 17 commits into
openclaw:mainfrom
zachisfine:fix/session-auth-profile-replacement

Conversation

@zachisfine

@zachisfine zachisfine commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

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@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. 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 ea3c488f4fb6: 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 32dcd02906ef, 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: 9ae6e1853062 and ea3c488f4fb6 fail their supported runtime wrapper on the known INEFFECTIVE_DYNAMIC_IMPORT guard for transcript-visible-record.ts. The full network baseline is a4656d4eea79, 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.

@zachisfine
zachisfine requested a review from a team as a code owner September 16, 2026 02:04
Copilot AI lite review requested due to automatic review settings September 16, 2026 02:04
@clawsweeper

clawsweeper Bot commented Sep 16, 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 app: web-ui App: web-ui gateway Gateway runtime commands Command implementations agents Agent runtime and tooling size: M labels Sep 16, 2026
@clawsweeper clawsweeper Bot added P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Sep 16, 2026
@clawsweeper

clawsweeper Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed September 27, 2026, 8:35 AM ET / 12:35 UTC (Revision 17).

ClawSweeper review

What this changes

The 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 provenance

Possible 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
Reviewed head: d69620a27208bb25325753a4fae7ee5f25b6c1c4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The patch has focused identity and persistence guards plus convincing real-flow evidence; the approved compatibility tradeoff remains visible in the review record.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The PR body ties the changed login and credential writer to a production CLI device-code flow, Gateway turns, and restart: same-account re-login resumed the pinned session, while a different account did not claim it. The reported existing-state and schema comparisons support upgrade compatibility without a migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The PR body ties the changed login and credential writer to a production CLI device-code flow, Gateway turns, and restart: same-account re-login resumed the pinned session, while a different account did not claim it. The reported existing-state and schema comparisons support upgrade compatibility without a migration.
Evidence reviewed 8 items Current-main behavior: The fetched main revision still sends returned login profiles through the older profile-ID selection path; it has no same-account snapshot or re-login identity resolution.
Account-boundary implementation: The introduced resolver requires one matching prior account and rechecks the selected credential before persistence; a changed identity aborts the write.
Final write boundary: The credential recheck runs inside the auth-profile write transaction before replacing the stored credential.
Findings None None.
Security None None.

How this fits together

Provider 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +134, Tests +374, Docs +2. Total +510 across 10 files.

View PR surface stats
Area Files Added Removed Net
Source 6 178 44 +134
Tests 3 375 1 +374
Docs 1 2 0 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 10 555 45 +510

Review metrics

Metric Value Why it matters
Code and test growth production +134 net lines; tests +374 net lines The production growth implements account matching and a transactional guard; the tests cover identity, persistence, and session selection.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #149502
Summary: The open issue describes the explicit session-pin failure that this PR is intended to repair.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P0: The linked bug can leave a user-selected conversation unable to run after re-login, with technical recovery required for a credential already lost.
  • merge-risk: 🚨 auth-provider: Reusing a credential profile ID changes which stored credential a session selects; the same-account behavior has explicit maintainer acceptance and real-flow proof.
  • merge-risk: 🚨 security-boundary: Account identity controls whether an existing profile ID may be reused; the transaction guard, different-account proof, and exact-head security approval cover the reviewed change.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The PR body ties the changed login and credential writer to a production CLI device-code flow, Gateway turns, and restart: same-account re-login resumed the pinned session, while a different account did not claim it. The reported existing-state and schema comparisons support upgrade compatibility without a migration.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body ties the changed login and credential writer to a production CLI device-code flow, Gateway turns, and restart: same-account re-login resumed the pinned session, while a different account did not claim it. The reported existing-state and schema comparisons support upgrade compatibility without a migration.

Evidence

What I checked:

  • Current-main behavior: The fetched main revision still sends returned login profiles through the older profile-ID selection path; it has no same-account snapshot or re-login identity resolution. (src/commands/models/auth.ts:675, 9ca49c5ac159)
  • Account-boundary implementation: The introduced resolver requires one matching prior account and rechecks the selected credential before persistence; a changed identity aborts the write. (src/commands/models/auth-relogin-identity.ts:64, d69620a27208)
  • Final write boundary: The credential recheck runs inside the auth-profile write transaction before replacing the stored credential. (src/agents/auth-profiles/upsert-with-lock.ts:213, d69620a27208)
  • Provider identity contract: The documented matcher must prove the same provider account; the OpenAI implementation checks provider, account, and user identity. Public docs: docs/plugins/manifest/setup-and-auth.md. (docs/plugins/manifest/setup-and-auth.md:188, d69620a27208)
  • Real behavior proof: The PR body records CLI device-code sign-in and Gateway turns against a loopback provider: the candidate resumed the same explicitly pinned session after same-account re-login, while the baseline rejected it. It also reports rejection after a different-account sign-in, automatic-pin recovery, unchanged session rows, and unchanged application schema. (d69620a27208)
  • Accepted behavior and exact-head approval: The maintainer approved restoring an ID only for a verified same-account sign-in and explicitly accepted strict failure for other identities and deliberate recovery of already-missing pins. The exact-head security approval comment was posted afterward. (d69620a27208)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Jason O'Neal: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (16 earlier review cycles; latest 8 shown)
  • reviewed 2026-09-17T13:39:10.856Z sha 171c1d43c7a848b9a954060472af431f9e02f8e3 :: blocked before merge. :: none
  • reviewed 2026-09-18T18:12:36.929Z sha 2829e2a954bc96f455bbe556d05cfe4a093444c1 :: blocked before merge. :: none
  • reviewed 2026-09-18T19:16:54.372Z sha bcec125 :: blocked before merge. :: none
  • reviewed 2026-09-21T05:29:39.026Z sha bcec125 :: blocked before merge. :: none
  • reviewed 2026-09-27T00:09:11.155Z sha b861d0d :: blocked before merge. :: none
  • reviewed 2026-09-27T08:08:43.548Z sha 6b25647 :: blocked before merge. :: none
  • reviewed 2026-09-27T08:50:50.855Z sha 6b25647 :: blocked before merge. :: none
  • reviewed 2026-09-27T12:15:06.807Z sha d69620a :: blocked before merge. :: none

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔵 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 runtime sessions.patchMany case proving that each target clears the profile, provenance, and compaction marker. Add a batch mutation test so the advertised patchMany contract 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/profileId would still pass while the issue's diagnosability guarantee is broken; add a focused unavailable-user-pin case that spies on authProfilesLog.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.profiles whenever 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, but tryImportProviderCredential returns before that call for methods with credentialImport (including OpenAI OAuth). The import owner selects its ID with itemProfileTarget, 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 carry authProfileId and its source independently of the persisted entry. This patch only deletes the fields from next, while the post-commit queue refresh currently runs only when agentRuntime is present, so authProfileId: null leaves queued items and lastRun pinned 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.

@zachisfine
zachisfine force-pushed the fix/session-auth-profile-replacement branch from e2bdfe9 to 6839af2 Compare September 16, 2026 07:50
@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. and removed merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. labels Sep 16, 2026
@zachisfine
zachisfine force-pushed the fix/session-auth-profile-replacement branch 2 times, most recently from 2cd5e18 to 0ebf6ec Compare September 16, 2026 09:09
@zachisfine
zachisfine force-pushed the fix/session-auth-profile-replacement branch 2 times, most recently from 5d3d6a8 to e23710b Compare September 16, 2026 14:00
@zachisfine

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper clawsweeper Bot added merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. labels Sep 27, 2026
@obviyus

obviyus commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

Maintainer decision (Ayaan): approved. After models auth login --force, a verified same-account sign-in restores the former profile ID so sessions pinned to it keep working; different, ambiguous or unverifiable accounts never reuse an ID and pinned sessions fail visibly. Proven end to end on a real Gateway with CLI device-code OAuth; no schema changes.

@obviyus

obviyus commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus

obviyus commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

/allow-security-sensitive-change

@obviyus

obviyus commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

@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.

@clawsweeper

clawsweeper Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@obviyus
obviyus merged commit 5676013 into openclaw:main Sep 27, 2026
202 of 204 checks passed
@obviyus

obviyus commented Sep 27, 2026

Copy link
Copy Markdown
Collaborator

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.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 28, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime merge-risk: 🚨 auth-provider 🚨 May break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P0 Emergency: data loss, security bypass, crash loop, or unusable core runtime. 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: L 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.

Session with user auth-profile pin is permanently unrunnable after OAuth re-auth mints a new profile id

4 participants