Skip to content

fix(auth): normalize legacy credentials through Doctor - #162958

Merged
steipete merged 6 commits into
mainfrom
fix/auth-doctor-canonical-credentials-l1374
Oct 1, 2026
Merged

steipete merged 6 commits into
mainfrom
fix/auth-doctor-canonical-credentials-l1374

Conversation

@steipete

@steipete steipete commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes legacy credential fields remaining in SQLite after Doctor, including when a conflicting account alias would otherwise stop independent credential repairs.

Supersedes #162685. Thanks @steipete for the original migration implementation; its commit and attribution are retained.

User Impact

Doctor and update-time repair persist canonical credential fields before runtime reads, with verified private backups. Existing accounts, explicit order, rotation state, and unresolved account selections stay attached to their owners. A conflicting alias defers only that mapping, allowing safe field repairs and JSON imports to continue. Existing canonical credentials retain precedence.

The installed updater runs candidate Doctor before activation. The published-driver proof below exercises that first hop. There are no new configuration or CLI options, dependencies, SQLite schema changes, suppressions, or baseline changes. Auto-merge is off.

Why This Change Was Made

The old runtime reader converted legacy fields on every read, while Doctor returned early when no profile IDs needed renaming. The original PR moved conversion into Doctor, but review found that stale alias/receipt early returns could still bypass field normalization before JSON import. This replacement removes only rejected mappings and strengthens the existing import recovery regression.

Backups, database-generation and source-row revalidation, and original/normalized receipt fingerprints preserve recovery across independently committed owners. Existing SQLite repairs retain unknown metadata and opaque rotation bytes. JSON import retains its existing canonical projection and archives the exact original source. Repeated Doctor leaves auth rows, receipts, and backup inventory unchanged.

Production: +976/-598 (net +378). Gross totals include relocated code. Tests: +831/-29 (net +802). Docs: +37. Follow-up test changes extend existing fixtures without adding cases.

Production owner Added / removed Justification
Credential representation and canonical runtime parsing +146 / -78 Moves legacy field conversion into the migration helper and removes runtime coercion. Runtime recognizes convertible legacy rows only to reject them with the Doctor command.
Doctor migration, recovery, and sequencing +405 / -455 Makes field repair independent of ID renaming; verifies backups, live database identity and source rows; preserves interrupted-owner receipt recovery; normalizes before canonical consumers. Removals include the extracted transformations below.
Extracted alias transformations +358 / -0 Relocates existing pure alias/rotation transformations into one sibling module to satisfy the line-cap gate. Function bodies are unchanged; this is not a second migration owner.
SQLite row owner and obsolete exports +67 / -65 Consolidates exact cell reads needed to preserve malformed rotation bytes in backups. Five obsolete exported helpers/constants become private; their sole test consumer uses the production cell reader.

Config, credential storage, and commit authority retain their existing owners. There is no new credential store, state writer, schema, or runtime compatibility owner.

Runtime-reader audit: no fallback reader remains for the migrated credential-field encodings. loadPersistedAuthProfileStore and loadPersistedSharedAuthProfileStore consume the canonical parser in persisted.ts. Convertible mode, apiKey/api_key, and object-valued key/token fields produce the openclaw doctor --fix error instead of runtime conversion. Conversion helpers serve Doctor/import/receipt/session repair. The sole non-Doctor diagnostic consumer, readLegacyAuthProfileProviders, returns bounded provider names for migration-refusal reporting only; it cannot publish or resolve credential material.

Canonical gateway.auth.token file SecretRefs remain valid configuration. Native app handling of those refs, absent credentials in a deliberately clean state directory, and optional OAuth refresh behavior involve separate owners and are not claimed fixed here.

Evidence

Final merged PR head: f165958b00229c0475e18f557d5aea5742812381. Individual proof runs below retain their tested source heads.

  • Corrected fixture: PASS, 35/35. One rerun of pnpm test src/secrets/apply.test.ts --maxWorkers=1 on the exact pushed head took 31.31 s wall; Vitest duration 29.37 s, about 10 s test work. The previously failing preservation case passed in 309 ms. Its old fixture wrote mode: "oauth" into canonical SQLite while already expecting type: "oauth"; the final commit fixes only that input and retains every assertion.
  • Full changed-file validation: PASS (exit 0), 1,396.64 s wall. node scripts/check-changed.mjs --base b4836fcbb48728ecd493ec9276e67b68c0e022d9 --head fbd3ed117834bf67dccb09be3499bd9c3331a44f passed on fresh Blacksmith Testbox tbx_01m3wm9821jnhag59bfzet1kms (run), after fetching that SHA and pnpm install --frozen-lockfile. Node 24.19.0, pnpm 12.5.1. All 27 test typecheck groups, all dead-export scans, and all selected guards passed; lint reported zero warnings/errors and the runtime import-cycle scan reported zero cycles. No local source sync, suites, builds, or typechecks.
  • Regression red/green: at c8be6faef7dc73e4a6f1f899fd9bb0625e06813a, the strengthened import regression failed against the original implementation with the expected migration-required error (106 ms test time). Restoring the fix passed all 8 import-recovery cases in 28.68 s wall. The original PR's 208 tests across 11 files also passed; its full gate exposed the line-cap and obsolete-export gaps fixed here.
  • Importing siblings: prior-head run at c8be6fa accounted for all 130 direct/barrel/mock importers: 128 files passed, one fixture failed, one live-provider file skipped; 2,207 cases passed, one failed, one skipped. The corrected fixture now passes as recorded above. Reporter/routing limitations were handled by continuing only unstarted files, preserving completed evidence. No failed test was retried to obtain green. After the export cleanup at production head f8b0adce, the affected worker file passed all 13 cases in 32.78 s wall (16.77 s Vitest duration, about 7.9 s test work).
  • P1 review: scoped-clean. Fresh direct-route Codex P1 review found the alias early-return defect. The behavioral repair, extraction, obsolete-export cleanup, and final fixture correction each received a fresh scoped-clean P1 review with no remaining accepted/actionable findings.

Waived slow-test follow-up

The maintainer explicitly waived the pre-existing src/commands/doctor.auth-profile-consumers.e2e.test.ts slow-test STOP for this lane. Its “unoccupied destination and padded references” case took 44.306 s of test time; the other cases took 28.895 s and 21.929 s. Each runs the full built Doctor CLI twice, six boots overall. Shared compiler preparation had finished, so these are actual test costs.

Follow-up: profile Doctor startup and the test composition, then reduce cost while preserving migration, repeated-run idempotence, and interactive entrypoint proof. The exact child-process hotspot is not yet isolated. No timeout increase, retry, skip, or weaker assertion was introduced.

Published-driver × candidate

PASS for production head f8b0adce50b1790b975af2ea11bf552a0096b4e1 on Blacksmith run, lease tbx_01m3wj80nvd142dn0pcpe4cddb. The final PR head also replaces the duplicated OPENAI_PROVIDER_ID literal with the existing shared "openai" constant in two production files, alongside the one-line test fixture correction. Migration and backup logic are unchanged; the update result remains attributed to f8b0adce50b1790b975af2ea11bf552a0096b4e1.

Published [email protected] ran openclaw update --tag file:/tmp/l1374-package/candidate.tgz --yes --json --no-restart --timeout 1200, returned status: ok in 153.92 s, and installed the exact candidate build. Doctor, lint, config, plugins, recovery, and Gateway startup checks exited 0. Canonical packaging took 477.74 s. Candidate SHA-256: 136b1d8911fd1a23598dbf75b3492fcdc18abcea26e03b2c2c6118f0150ffb59.

Six legacy SQLite credential forms normalized and one JSON profile imported. Original IDs, explicit order, last-good selection, and rotation bytes survived. Backup retained original credential fields; JSON archive retained exact bytes with a completed receipt. Repeated Doctor (8.24 s) changed no auth rows, timestamps, receipts, or backup inventory. Installed models status --json (1.05 s) reported seven profiles, provider health ok, and the original effective order. Canonical SDK reads/order and inline resolution passed; SecretRefs retain their activated-snapshot requirement. No live provider request, macOS app proof, or OAuth refresh was attempted.

No merge, auto-merge, release, or package publication was performed.

The resumed lease was released after verification. The pre-existing slow-test follow-up is explicitly waived for this PR; all requested readiness checks are complete.

@clawsweeper

clawsweeper Bot commented Oct 1, 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 gateway Gateway runtime commands Command implementations agents Agent runtime and tooling size: XL labels Oct 1, 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: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 1, 2026
@clawsweeper

clawsweeper Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 1, 2026, 5:38 PM ET / 21:38 UTC (Revision 6).

ClawSweeper review

What this changes

The PR moves legacy credential conversion into Doctor, preserves migration backups and account selections, and makes runtime readers require canonical credential fields.

Warning

SQLite table change

This PR modifies persisted SQLite tables in src/agents/auth-profiles/sqlite.ts. Prefer a design that avoids changing persisted SQLite tables. Migration or upgrade compatibility proof is recorded, but maintainers should still confirm that the schema change is necessary.

Merge readiness

✅ Ready for maintainer review

This remains a useful landing candidate: current main still needs the repair, and the updated evidence addresses the previous review blockers. No actionable introduced defect was found.

Priority: P2
Reviewed head: fbd3ed117834bf67dccb09be3499bd9c3331a44f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A solid migration repair with relevant production-path upgrade evidence, meaningful recovery coverage, and no remaining actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The recorded published-updater run exercises Doctor's changed SQLite and JSON migration owners, then installed credential reads and repeated repair, with observed preservation and idempotence. Existing-state compatibility is supported by the backup, archive, selection, rotation, and receipt checks; the final head changes only a test fixture.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The recorded published-updater run exercises Doctor's changed SQLite and JSON migration owners, then installed credential reads and repeated repair, with observed preservation and idempotence. Existing-state compatibility is supported by the backup, archive, selection, rotation, and receipt checks; the final head changes only a test fixture.
Evidence reviewed 8 items Current main still needs the repair: Fetched main still returns immediately when the profile-ID map is empty, before repairing credential fields. Its persisted reader still converts legacy fields during runtime reads.
Introduced migration safeguards: The pinned introduction diff makes field normalization independent of alias renaming, removes rejected mappings individually, verifies private snapshots, and rechecks maintenance ownership, physical database generation, and source rows before transaction writes.
Recovery and account preservation: Receipt recovery accepts exact original or normalized fingerprints and rejects changed accounts. Regression coverage exercises occupied destinations, unreadable sibling owners, database replacement after backup, interrupted owner commits, and unchanged repeated-run receipts.
Findings None None.
Security None None.

How this fits together

Doctor repairs stored credentials before updates and runtime authentication consume them. It coordinates SQLite stores, legacy JSON imports, and account references so canonical credentials remain attached to their existing owners.

flowchart TD
  A[Stored credentials and legacy JSON] --> B[Doctor repair planning]
  B --> C{Account mapping safe?}
  C -->|Yes| D[Repair fields and account references]
  C -->|No| E[Repair fields and defer mapping]
  D --> F[Verified backups and guarded writes]
  E --> F
  F --> G[Canonical runtime authentication]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +378, Tests +802, Docs +37. Total +1217 across 19 files.

View PR surface stats
Area Files Added Removed Net
Source 11 976 598 +378
Tests 7 831 29 +802
Docs 1 37 0 +37
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 19 1844 627 +1217

Review metrics

Metric Value Why it matters
Production versus test growth production net +378 lines; tests net +802 lines The body explains production growth through verified backups, migration recovery, and removal of runtime conversion; relocated transformations account for much of the gross addition.
Upgrade coverage 6 legacy SQLite forms; 1 JSON import; repeated-run idempotence The published-driver proof exercises existing state through the actual update and installed Doctor boundaries.

Stored data model

Persistent data-model change detected: migration/backfill/repair: src/agents/auth-profiles/sqlite.ts, migration/backfill/repair: src/commands/doctor/auth-alias-receipt.ts, migration/backfill/repair: src/commands/doctor/auth-alias-transforms.ts, migration/backfill/repair: src/commands/doctor/auth-profile-repair.ts, migration/backfill/repair: src/commands/doctor/repair-sequencing.ts, serialized state: src/agents/auth-profiles/legacy-flat-credential.ts, and 7 more. Migration or upgrade compatibility proof is recorded; maintainers should verify it before merge.

Root-cause cluster

Relationship: canonical
Canonical: #162958
Summary: This branch retains the original migration implementation and adds the conflict-handling and validation corrections documented by the replacement.

Members:

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

Technical review

Best possible solution:

Keep credential conversion with Doctor and its existing storage owners, preserving verified recovery and account identity before canonical runtime reads.

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

Yes, from source: current main skips SQLite credential-field repair when no profile IDs require renaming. This review did not execute a reproduction; the supplied evidence records regression red/green results.

Is this the best way to solve the issue?

Yes. Moving conversion into the existing migration owner, with verified backups and deferred unsafe mappings, provides a complete cutover without another runtime compatibility reader.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 63a514d927e8.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded credential-migration reliability repair with meaningful upgrade impact and no demonstrated emergency.
  • 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 recorded published-updater run exercises Doctor's changed SQLite and JSON migration owners, then installed credential reads and repeated repair, with observed preservation and idempotence. Existing-state compatibility is supported by the backup, archive, selection, rotation, and receipt checks; the final head changes only a test fixture.
  • proof: sufficient: Contributor real behavior proof is sufficient. The recorded published-updater run exercises Doctor's changed SQLite and JSON migration owners, then installed credential reads and repeated repair, with observed preservation and idempotence. Existing-state compatibility is supported by the backup, archive, selection, rotation, and receipt checks; the final head changes only a test fixture.

Evidence

What I checked:

  • Current main still needs the repair: Fetched main still returns immediately when the profile-ID map is empty, before repairing credential fields. Its persisted reader still converts legacy fields during runtime reads. (src/commands/doctor-auth-flat-profiles.ts:1812, 63a514d927e8)
  • Introduced migration safeguards: The pinned introduction diff makes field normalization independent of alias renaming, removes rejected mappings individually, verifies private snapshots, and rechecks maintenance ownership, physical database generation, and source rows before transaction writes. (src/commands/doctor-auth-flat-profiles.ts:1392, fbd3ed117834)
  • Recovery and account preservation: Receipt recovery accepts exact original or normalized fingerprints and rejects changed accounts. Regression coverage exercises occupied destinations, unreadable sibling owners, database replacement after backup, interrupted owner commits, and unchanged repeated-run receipts. (src/commands/doctor/auth-alias-receipt.ts:145, fbd3ed117834)
  • Production-path upgrade proof: The captured PR body reports that published [email protected] updated to production head f8b0adc successfully in 153.92 seconds. Six legacy SQLite credential forms normalized and one JSON profile imported; IDs, order, last-good selection, rotation bytes, original backups, archives, and completed receipts were checked. A second Doctor run changed no rows, timestamps, receipts, or backup inventory, and installed models status reported seven healthy profiles. The linked launcher is https://github.com/openclaw/openclaw/actions/runs/36921361224; its API confirms the production SHA but reports cancellation, so the behavior assessment relies on the recorded Testbox results rather than workflow conclusion. (f8b0adce50b1)
  • Proof remains applicable to the final head: Comparison against the proven production head shows that the final commit only changes the secrets test fixture from mode: oauth to type: oauth; production code is identical. The captured body reports that all 35 secrets tests and the full changed-file gate passed on the final head. (src/secrets/apply.test.ts:1006, fbd3ed117834)
  • Previous review blockers addressed: The captured body explicitly records the lane-specific maintainer waiver for the pre-existing Doctor CLI slow-test STOP, retaining profiling as a follow-up without retries, timeout increases, skips, or weaker assertions. It also supplies the final fixture result and completed changed-file validation requested by the previous review. The supplied security-guard comment identifies the author as a repository administrator. (src/commands/doctor.auth-profile-consumers.e2e.test.ts, fbd3ed117834)

Likely related people:

  • obviyus: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • steipete: 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 (5 earlier review cycles)
  • reviewed 2026-10-01T19:50:01.271Z sha c8be6fa :: blocked before merge. :: none
  • reviewed 2026-10-01T19:59:21.006Z sha c8be6fa :: blocked before merge. :: none
  • reviewed 2026-10-01T20:35:16.335Z sha f8b0adc :: blocked before merge. :: none
  • reviewed 2026-10-01T20:45:53.756Z sha fbd3ed1 :: blocked before merge. :: none
  • reviewed 2026-10-01T20:58:57.748Z sha fbd3ed1 :: blocked before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels Oct 1, 2026
@steipete
steipete marked this pull request as ready for review October 1, 2026 21:31
@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components. This comment is informational because the PR author has repository Maintain or Admin access.

  • Current SHA: f165958b00229c0475e18f557d5aea5742812381
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/legacy-flat-credential.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/legacy-source-diagnostic.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/persisted.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/sqlite-json.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/sqlite.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@steipete
steipete merged commit 9b0a90e into main Oct 1, 2026
38 of 39 checks passed
@steipete

steipete commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Landed (squash 9b0a90e3b9eb7c39ce15d493c45e82641e6489ee, head f165958b0022): lead review scoped-clean (0.86) at fbd3ed1; the only later change is a two-line fix for the check-source-contracts red this PR caused (its new auth-alias-transforms.ts re-exported OPENAI_PROVIDER_ID, colliding with src/agents/openai-routing.ts; both Doctor files now import the canonical constant). Export-collision guard, import-cycle check and the importer suite (68 tests) pass locally. Exact-head CI was cancelled at ~21:37Z; admin-merged per the unrelated-red rule rather than re-running CI.

@steipete
steipete deleted the fix/auth-doctor-canonical-credentials-l1374 branch October 1, 2026 22:12
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 2, 2026
…or normalization (openclaw#162958)

Setup and auth flows persisted plaintext provider tokens and lost rotation state when Doctor normalized legacy auth profiles. Credentials are now normalized by the Doctor owner only, with credential values and rotation state preserved, verified migration backups, and no runtime fallback reader for the legacy plaintext shape. Supersedes openclaw#162685 (thanks @yashas-13 for the original report and candidate).

Refs openclaw#162685
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 P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. security-sensitive-changed size: XL status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant