Repository navigation
fix(matrix): enforce exclusive crypto store ownership - #160707
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. What this changesThis PR gives each Matrix crypto store exclusive ownership through restoration, shutdown, and final persistence, with explicit recovery after unsafe termination. Example: Two encrypted clients for the Matrix account ops select the same storage root.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this PR fixes a current Matrix key-loss failure that main still permits; no actionable introduced defect remains. Priority: P1 Before mergeNone. FindingsNone. Agent review detailsHow this fits togetherThe Matrix plugin connects Gateway and CLI operations to matrix-js-sdk and Rust crypto; account storage supplies snapshots and sync cursors, and shutdown publishes their final durable state. flowchart TD
A[Gateway and Matrix CLI] --> B[Shared client registry]
B --> C[Exclusive store custody]
C --> D[Validated snapshot restoration]
D --> E[Matrix SDK and Rust crypto]
E --> F[Storage retirement]
F --> G[Final snapshot cursor and seal]
G --> C
Technical reviewBest possible solution: Land exclusive custody with the documented explicit recovery contract, while keeping eager crash durability as separate work. Do we have a high-confidence way to reproduce the issue? Current main permits overlapping crypto generations and treats invalid snapshot state as absent; the earlier merged read-authority PR also records a matched late-writer key-loss reproduction. Is this the best way to solve the issue? The patch repairs ownership at the storage and client lifecycle boundaries, preserves the existing canonical SQLite owner, and validates restoration before replacing retained keys. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 230ea6864eb1. Provenance checked
TestingProof path: shipped entry point. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +1177, Tests +1993, Docs +15, Other -5. Total +3180 across 53 files. Added test files: 6. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment HistoryReview history (25 earlier review cycles; latest 8 shown)
Reviewed October 12, 2026, 4:40 AM ET / 08:40 UTC (Revision 26). |
|
🦞👀 Re-review progress:
|
|
🦞👀 Re-review progress:
|
What Problem This Solves
Fixes: encrypted Matrix clients can replace newer room keys when client generations share an account, and invalid saved state can erase retained keys during restoration.
Original ownership fix contributed by Agustin Rivera (@eleqtrizit); the branch preserves the contributor's commits.
User Impact
One client owns an account's persistent state through restoration, accepted work, SDK storage retirement, and final persistence. Corrupt snapshots refuse startup before retained account databases are replaced. Verification operations use the running Gateway owner; other offline commands require stopping the Gateway through its service owner.
Use normal
openclaw updatefor managed installations. Independently installed processes sharing an account must stop older writers and upgrade before concurrent use. The first upgrade depends on the installed version completing its final save; this patch cannot recover or detect keys that an older writer never saved.After an interrupted session or failed final publication, another crypto owner is refused. Stop all processes and preserve the state directory before considering
openclaw matrix doctor recover --account <id> --accept-snapshot-rollback. Recovery validates the entire canonical snapshot by replaying it in isolation under exclusive custody, then publishes a new guard and seal. This explicitly accepts possible loss of keys received after the last save. Missing or invalid snapshots require restoring a valid backup or storage-owner assistance. Clean sessions retain.owner.poisoned; do not delete this guard manually. Failed Rust initialization or uncertain backend retirement keeps custody until the process exits.Why This Change Was Made
The shared registry admits clients by the actual selected storage root, including token-rotation aliases, across captured plugin modules. An incompatible active transport generation returns a retryable account-restart error; the existing account lifecycle owns retirement.
The SDK storage adapter closes native IndexedDB connections, joins accepted transactions and pending opens, and denies writes from retired continuations before final export. A retained, synced generation guard must match a seal in canonical SQLite state. Final publication writes crypto state and the sync cursor before publishing that seal. An encrypted diagnostic client that never initialized crypto preserves the loaded cursor's clean/dirty status. Metadata-only Doctor inspection receives its existing state-store context and needs only lookup access, without initializing the Matrix runtime.
Startup and explicit Doctor recovery use the same complete isolated replay validation. The snapshot chunker preserves existing byte boundaries while avoiding per-character allocations. There are no new configuration options, protocol changes, dependency patches, or SDK version requirements.
Evidence
Reviewed candidate:
e85a60226db2e7ab9d11c959cebfadef4c49bfde.Current-head CI passed on
e85a60226db2, including the two previously failing test shards; the combinedopenclaw/ci-gatestatus also succeeded on this head. A successful automated review workflow records workflow completion, not a clean code-review verdict. The ClawSweeper review at 08:04 UTC reviewede85a60226db2, confirmed the startup-guidance fix, and found no actionable code defects. That review still requested completed upgrade proof from 2026.10.2 and predates the completed cell documented below. Skipped jobs are not counted as executed proof.Earlier managed-upgrade runtime:
d59e2fc19e5dedf45114d8de2815d145703dc233, integrating main716e1f45269409e57b2e1321dfe43bb030597647. The follow-up at66f45995356achanges only the readiness fixture, its database-worker routing, and the routing regression expectation. The current follow-up changes only unsafe-startup error text; custody, recovery, and stored-data behavior are unchanged.openclaw matrix doctor inspect, and consult the encryption documentation. The same failed-publication client/SQLite entry point emitted the unhelpful refusal before the change and the actionable guidance afterward. Both unchanged ownership/startup suites passed all 22 cases (18.27 s command wall time). The diff contains one production error-message change and no test additions. Independent P0–P2 review of this correction was scoped-clean; formatting, ratchets, extension production/test types, and targeted typed lint passed. The changed-file aggregate reproduced the same five-production/four-full-tree inherited UI export findings documented below.d59e2fc19e5dfound two test integration defects: the live-room readiness fixture did not install the Matrix state runtime required by custody, and a routing regression copied an obsolete SDK worker-file inventory. The existing isolated test runtime now supplies state access; the suite runs in the canonical database-worker project. Routing assertions derive membership and order from the authoritative lane input while retaining exact equality and unrelated-directory exclusion. All 12 readiness cases pass after failing before the fixture repair. Production code is unchanged. All 297 routing cases passed (108.53 s command wall time); the 12 readiness cases took 22.71 s. Fresh independent review of the final three-file correction found no actionable P0–P2 findings. The correction contains no production changes, weakened assertions, or test exceptions. Affected extension-test and all four root-test typecheck shards, targeted typed lint, formatting, ratchets, and plugin boundary checks passed. The changed-file aggregate still exits 1 solely for the same inherited five-production/four-full-tree UI exports qualified below; no exception or skip was used.git diff --checkpassed. The main integration resolved one test-fixture conflict using the upstream fixture; all 29 affected Doctor cases passed again. The fresh canonical core package build and tarball-integrity check passed (terminal exit 0, 267.66 s command wall time) on private fixture9c97a78bade493b755c990ffb8dbae1b1395c7ae, whose parent is the production candidatee85a60226db2e7ab9d11c959cebfadef4c49bfde. The fixture differs only in its two private version labels and private package note. Matrix was built and packed separately through its canonical standalone runtime and npm-manifest owners; the normal core tarball contains no Matrix runtime. It recorded existing UI performance advisories: chat boot 38 JS requests versus budget 35, and startup CSS above its advisory target but below its hard ceiling. The PR has no effective UI changes. A separate full typed-lint run exited 1 with 18 line-limit errors outside this PR's effective diff; no other errors were reported. All 18 reproduced exactly on unchanged main using the supported focused syntax lane with identical source, limits, and tool configuration. Baseline full typed lint could not start because its shared dependency symlink failed declaration admission; this is a deterministic line-limit qualification, not a baseline full typed-lint pass. The scripts lint lane and separately completed Stylelint passed. These are stricter standalone lint diagnostics; the existing changed-check owner ordinarily treats untouched line limits as advisory.pnpm deadcode:exportson unchanged main716e1f452694reproduced all five production UI findings (PanelToggleElement,ApprovalPage,CustodianPage,QuestionPage,SkillWorkshopViewProps) and all four full-tree UI findings. UI sources, Knip configuration, scanner, dependency manifests, and lockfile are byte-identical; Matrix changes do not consume these UI modules. The baseline also reports additional core exports, so its complete finding set differs. This qualification covers the exact inherited UI diagnostics only; no scanner exception was added. The subsequent native lint and runtime import-cycle stages were run separately because the aggregate stopped before reaching them; their outcomes are recorded above.The latest-stable native macOS managed-update cell passed from running published core and official npm Matrix
2026.10.2through the installed updater to private candidate2026.10.3, without manually stopping the Gateway. Terminal exit was 0, command wall time 311.50 s (structured product duration 283.881 s), statusok, durable runsucceeded/finished, and all 20 steps exited 0. The serving build is private fixture9c97a78bade4, whose parent is production candidatee85a60226db2. All 1,860 files in the separately installed Matrix package match the candidate artifact byte for byte; the normal core tarball has no Matrix runtime.The native Gateway read the exact original event and plaintext after both upgrade and a native service restart (restart exit 0, 75.41 s). The restart reconciled the service definition for the fixture's temporary npm prefix. The server event remained
m.room.encrypted. Device identity/public keys, all seven verification flags, recovery identity, trusted backup version and backup-key records, canonical account storage root, and Matrix/Gateway settings were preserved. The canonical snapshot retained exact records for one inbound session, two backup-key records, three core-key records, one outbound session, and one room setting. The Olm session store was empty before and after; this cell does not exercise a remote Olm session. Full configuration comparison against the installed updater's original-state capture also recorded normal Doctor additions ofagents.entries.mainand wizard last-run metadata, plusmeta.lastTouchedVersion. Stored credential identity was unchanged;lastUsedAtadvanced with actual use.A successful canonical clean-state sample was captured after the old PID disappeared and 42.93 s before the candidate guard's birth. The first subsequent real bot
/syncarrived 43.47 s after that sample and reused its exact final cursor. The initial sampling attempt encountered a transient path-opening failure; the proved boundary is the later successful sample before candidate ownership. This uses real Synapse 1.162.0 in an owned container, with a task-owned localhost HTTP relay forwarding client requests throughdocker execbecause the existing VM context did not expose container ports on this host. Matrix SDK traffic and encrypted events are real; the relay is a fixture transport adaptation. A repository-native npm fixture registry supplied the private core and Matrix artifacts while forwarding other dependencies upstream; the installed updater and official plugin convergence owners performed the upgrade.The 2026.10.2 run recorded a material rollback limitation: the main agent database changed during its pre-migration snapshot capture, so the updater retained its snapshot for manual recovery and disabled automatic database restoration to preserve later writes. The published 2026.10.2 generation-check policy already contains this behavior; it did not prevent the successful Matrix upgrade. Other warnings covered deferred advisory Doctor inspections, synthetic plaintext fixture credentials, temporary package convergence that subsequently completed, and managed-service reconciliation. This cell proves the successful upgrade and restart, not live rollback.
The earlier native macOS managed-update cell passed from running published core and official Matrix
2026.10.1to the exact private candidate artifacts, without manually stopping the Gateway. Terminal exit was 0, wall time 329.86 s, structured statusok, runsucceeded/finished, and all 20 steps exited 0, including the previously failing post-plugin Doctor, managed-service reconciliation, and Gateway verification. The serving build matched fixture401e67e13d22; the selected official npm Matrix installation matched the separately built package integrity, and the core tarball contained no Matrix runtime.Native Gateway
message.actionreturned the exact original plaintext from the still-encrypted server event. Device identity/public keys, all seven verification flags, recovery identity, backup version/count/trust, inbound sessions/keys, storage root, and Matrix/Gateway settings were preserved. Comparison against the fresh pre-update configuration changed only normalmeta.lastTouchedVersionmetadata and the explicitly requestedupdate.channel. A paused canonical clean-state sample after the old PID exited and before the candidate guard existed matched the first subsequent real bot/sync?since; the initial observer encountered a transient path-opening failure, so this proves the later sampled boundary, not immediate stop sampling.Earlier native clean stop/restart and same-device token reload passed on production
2ea3de38b206/ private artifactec1e7a1532ad: retained guard inode, matching SQLite seal, new owner generation, one custody lock, cursor continuity, and preserved identity/history/settings. Reload used native Gatewayconfig.get/config.setand kept the same Gateway PID. That proof is reused for the unchanged Matrix lifecycle implementation; it was not rerun on the final artifact. The later Doctor repair and mechanical main integration did not change that implementation.The first update rehearsal exposed metadata-only Doctor inspection incorrectly depending on an initialized Matrix runtime; the existing Doctor context now supplies lookup access, with a real SQLite regression and the final native Doctor step passing. A leftover activation record from restoring that failed synthetic installation caused a separate preflight refusal. Published
openclaw update repair --yes --jsonsettled it through the native owner, archived the prior record, and passed before the fresh baseline was captured.The earlier 2026.10.1 update retained 15 recorded warnings covering deferred advisory Doctor inspections, package convergence, synthetic plaintext credential configuration, configured browser/provider advisories, and completed service reconciliation. One inherited debug-level JSON-output defect caused candidate admission to fall back to the installed updater: six SQLite debug stdout lines preceded an otherwise valid protocol-1 admit verdict. A narrow passive capture reproduced it; the involved core sources are byte-identical to main, and the installed fallback completed the required checks. Follow-up: route debug logs to stderr in the early core admission entry point. No admission bypass or scanner exception was added here.
These are two real Synapse/macOS managed-upgrade cells (2026.10.1 and latest stable 2026.10.2), plus scoped storage/dependency proof. Native Linux/Windows execution, power-loss behavior, and live rollback execution were not exercised. The prior
d59e2fc19e5dCI remains failed for the two test-integration defects described above. The published follow-up at66f45995356ae220c2ad8fe2fe3c768aff1423f1passed its exact-head CI after those repairs. CI for the guidance follow-up passed one85a60226db2; older-head CI is not counted as current-head evidence. The green CI result does not erase the separately recorded inherited local-check diagnostics.Private test artifact identities
Latest-stable upgrade cell: production source
e85a60226db2e7ab9d11c959cebfadef4c49bfde; private package source9c97a78bade493b755c990ffb8dbae1b1395c7ae, differing only in two version labels and its private package note. These test packages were not published as a release. The serving core build and selected separate Matrix package are checked against these identities.a0e5f3cc19e7d972273165987efac4c2883cd0604651aadbda5957339f39271a46dab6d5af0ce837cfb2afc3b5d4ee66f52ea894f72a267a55958dd1b8ff3175Earlier 2026.10.1 cell: production source
d59e2fc19e5dedf45114d8de2815d145703dc233; private package source401e67e13d222617c233a795317da6eb1961a451, with the same private-label convention.5c8b658459559985f21fc6916711b08e5d53ccf1d67140483b238308b2542c2687e89de8e91cf9236151d56f4296f9cd1c1f1726029f1af93191b6b67c78e0494511736043a6f85e28d208d81c9b247f232eff8fbdcc5b8c4e3c95ee5b50e008Inherited standalone lint diagnostics
All entries reproduced with identical positions and limits on integration base
716e1f452694. No exceptions or unrelated source changes were added.extensions/openai/image-generation-provider.test.tsextensions/crabbox/src/crabbox-worker-provider.tsui/src/e2e/model-providers.e2e.test.tssrc/plugins/registry-runtime-session-ownership.tsui/src/components/board/board-widget-cell.solid.tsxui/src/pages/chat/components/chat-detail-panel.tsxui/src/pages/chat/components/chat-transcript-projection.tsui/src/pages/chat/components/chat-message-images-solid.tsxsrc/cli/update-cli/update-command-post-update.tssrc/agents/isolated-completion.tssrc/auto-reply/reply/dispatch-from-config.choose-route.tssrc/gateway/server-methods/chat-abort-runtime.tssrc/agents/worktrees/checkout.tssrc/gateway/session-worktree-preparation.tssrc/agents/tools/sessions-send-tool.tssrc/config/sessions/transcript.tssrc/plugin-state/plugin-state-store.tssrc/state/openclaw-agent-db-validation-cache.tsFocused test costs
Local command:
pnpm test <file> --maxWorkers=1. Paths below are relative toextensions/matrix/. Local macOS measurements include command wall time, with valid unchanged-input measurements reused across the mechanical main integration. CI measurements come from the completed preceding-head run at66f45995356ae220c2ad8fe2fe3c768aff1423f1; each linked value sums the reported passing case durations for that file. These rounded case durations exclude compilation, runner preparation, import, worker, and suite-level setup/teardown overhead, and are not CI job wall time.src/matrix/sdk/client-startup-recovery.test.tssrc/matrix/sdk/live-room-readiness.test.tssrc/matrix/sdk/client-real-snapshot-custody.test.tssrc/matrix/sdk/indexeddb-session.test.tssrc/matrix/client/create-client.storage.test.tssrc/matrix/crypto-unsafe-state-doctor.test.tssrc/matrix/sdk.test.tssrc/matrix/sdk/idb-persistence.test.tssrc/matrix/client/shared.test.tssrc/matrix/client/shared.lifecycle.test.tssrc/matrix/monitor/index.test.tssrc/direct-encryption.test.tssrc/matrix/sdk/crypto-store-ownership.process.test.tsdoctor-contract-api.import.test.tsdoctor-contract-api.test.tsThe additional routing-owner command,
pnpm test test/scripts/test-projects.test.ts --maxWorkers=1, passed all 297 cases in 108.53 s local command wall time. CI at66f45995356apassed the same 297 cases with 35.054 s summed case durations; Vitest reported 35.864 s for the file.All 266 focused Matrix cases in the table also passed in CI at
66f45995356a. These are preceding-head timings, not current-head CI proof. Longer persistence/ownership cases exercise real SQLite workers and native storage boundaries. The managed update campaign is separate from ordinary unit-test CI.