Skip to content

Fail closed when persisted device identity cannot load - #1065

Merged
shanselman merged 3 commits into
openclaw:mainfrom
bkudiess:bkudiess-trace-identity-rotation
Jul 29, 2026
Merged

shanselman merged 3 commits into
openclaw:mainfrom
bkudiess:bkudiess-trace-identity-rotation

Conversation

@bkudiess

Copy link
Copy Markdown
Collaborator

Related to #1031

Summary

Persisted Windows device identities now load fail closed. The root cause was broad fail-open recovery in DeviceIdentity.LoadExisting: any read, parse, validation, or key-reconstruction failure generated and persisted a new Ed25519 key. Because the device ID is derived from the public key, that recovery silently changed node identity and forced re-pairing.

The persistence boundary now distinguishes conclusive absence from failure:

  • Existing identity files are validated and loaded without mutation.
  • Invalid, unreadable, locked, or raced identity files throw DeviceIdentityLoadException.
  • New identities are generated only after conclusive absence and published with create-once, no-overwrite semantics.
  • Concurrent initializers load the persisted winner and converge on one device ID.
  • Caller paths classify the typed failure and show the safe explicit-reset recovery message.

The security invariant is that failure to read or validate an existing persisted identity must never silently replace its cryptographic identity, tokens, or pairing state.

Architecture handoff

The old owner was broad fail-open recovery inside DeviceIdentity.LoadExisting. The new owner is the typed, fail-closed persistence boundary in DeviceIdentity, with connection, setup, startup, tray, and CLI callers responsible only for classification and user-safe diagnostics. App remains the composition root and does not take ownership of identity persistence.

Review fixes included:

  • Any-usable saved-gateway scans validate the active record first, skip only corrupt inactive records, and continue to healthy saved records.
  • Node-mode startup validates the active per-gateway identity before legacy or inactive fallback scans.
  • OpenClaw.Cli catches only DeviceIdentityLoadException, returns exit code 1, and emits only the safe recovery message even with --verbose.
  • Passive reconnects retain live operator and node clients. Versioned, synchronized node-start ownership prevents automatic re-handshakes and stale delayed attempts from replacing a newer live node client.

Scope

  • The gateway-reconnect deviceFamily metadata fix is intentionally excluded and will be handled in a separate PR.
  • Historical stale gateway pairing entries are not cleaned up.
  • No automatic identity reset or re-pair workflow was added.

Validation

  • .\build.ps1: passed, all 5 projects built.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore: 3,243 passed, 31 skipped, 0 failed.
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore: 1,966 passed, 0 failed.
  • dotnet test .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --no-restore: 452 passed, 0 failed.
  • dotnet test .\tests\OpenClaw.SetupEngine.Tests\OpenClaw.SetupEngine.Tests.csproj --no-restore: 700 passed, 0 failed.
  • dotnet build .\src\OpenClaw.Cli\OpenClaw.Cli.csproj --no-restore: passed with 0 warnings and 0 errors.
  • git diff --check: passed.

Total: 6,361 passed, 31 skipped, 0 failed.

Real behavior proof

  • Two independent test-host processes initialized the same empty identity directory and returned the same device ID: d7029c9611e38435b8ed2b02698d2204208f52164ce2403dfbb5baea478eb038.
  • Corrupt persisted identity through OpenClaw.Cli, in normal and --verbose modes:
    • Exit code: 1
    • Standard output: empty
    • Standard error: Saved device identity could not be loaded. OpenClaw did not replace it. Check file access or reset pairing explicitly.
    • Stack trace: absent
    • SHA-256 before and after: 021FB596DB81E6D02BF3D2586EE3981FE519F275C0AC9CA76BBCF2EBB4097D96
    • Identity temp files: 0
  • Passive gateway-restart tests prove the same operator and node lifecycle reconnects without replacement client construction, token clearing, pairing initiation, identity-byte mutation, or temp files.
  • Visible UI proof: Not verified / blocked because computer-use capability was unavailable. Tray startup, onboarding, chat-bootstrap, and source-contract tests cover the changed diagnostics and routing.

Review

The structured autoreview helper built the complete review bundle but Codex failed before review with HTTP 401. An independent read-only rubber-duck review then inspected the full diff iteratively. All accepted findings were fixed, including active-record ordering, inactive scan continuation, CLI output isolation, deterministic creation contention, passive node replacement, supersession ownership, stale delayed reconnects, and guard atomicity. The final independent review reported no actionable findings.

Residual risk

The external boot-time actor that corrupts, locks, or deletes the identity remains unknown. This change prevents that condition from silently rotating identity and surfaces explicit recovery instead. An already-corrupt identity still requires the existing explicit reset and re-pair action.

@clawsweeper clawsweeper Bot added proof: sufficient Contributor real behavior proof is sufficient. 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. P1 Urgent regression or broken agent/channel workflow affecting real users now. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. labels Jul 29, 2026
@clawsweeper

clawsweeper Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Codex review: needs maintainer review before merge. Reviewed July 29, 2026, 2:12 PM ET / 18:12 UTC.

ClawSweeper review

What this changes

The PR prevents corrupted, unreadable, locked, or raced persisted Windows device identity files from being silently replaced, and routes typed recovery errors through gateway connection, setup, tray, CLI, and node startup paths.

Merge readiness

⚠️ Ready for maintainer review - 4 items remain

Keep this PR open for explicit maintainer review. It is a collaborator-authored, cross-cutting hardening change that appears to address the identity-rotation problem safely, has concrete current-head terminal proof, and is not eligible for automated cleanup closure.

Priority: P1
Reviewed head: bb06fdc91badea41e602f7a7ed90201a4b6df5f7
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) The PR has strong focused terminal proof and broad regression coverage; its cross-cutting compatibility and connection surface still merits a maintainer merge review.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): The PR body and current-head collaborator report provide after-fix out-of-process terminal proof for corrupt and locked identities, including stable file hashes, explicit recovery output, no temporary files, and successful fresh initialization.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (terminal): The PR body and current-head collaborator report provide after-fix out-of-process terminal proof for corrupt and locked identities, including stable file hashes, explicit recovery output, no temporary files, and successful fresh initialization.
Evidence reviewed 5 items Fail-closed persistence boundary: The proposed identity exception explicitly states that an existing identity is not replaced after load or save failure, providing a single typed signal for callers to preserve durable pairing state.
CLI recovery behavior: The CLI constructs the gateway client behind a typed identity-load catch and returns a safe recovery message instead of allowing verbose diagnostics to expose a stack trace from identity initialization.
Current-head real behavior proof: The collaborator's current-head report says the out-of-process test host handled corrupt and exclusively locked valid identities with exit code 2, unchanged SHA-256 bytes, no temporary files, and an explicit recovery message; it identifies head bb06fdc.
Findings None None.
Security None None.

How this fits together

The Windows tray, setup engine, CLI, and Windows node load a persisted Ed25519 identity before authenticating to a gateway. That identity determines the stable device ID and stored pairing tokens, so a failed read must either preserve it and surface recovery guidance or safely create one only when absence is conclusive.

flowchart LR
  A[Saved device identity] --> B[Identity load and validation]
  B -->|valid identity| C[Credential resolution]
  C --> D[Tray CLI setup and node clients]
  D --> E[Gateway pairing and reconnect]
  B -->|unreadable or corrupt| F[Typed identity failure]
  F --> G[Explicit recovery diagnostics]
  G --> H[Preserved identity and pairing state]
Loading

Decision needed

Question Recommendation
Should this collaborator-authored PR land with the intentional upgrade behavior that unreadable saved identities require explicit recovery rather than automatic identity replacement? Approve the fail-closed contract: Merge after the pending current-head checks confirm the typed recovery message and explicit reset and re-pair flow across tray, setup, CLI, and node startup.

Why: The patch is an intentional cross-cutting compatibility and authentication behavior change, and repository policy keeps collaborator-authored items open for explicit maintainer judgment.

Before merge

  • Resolve merge risk (P1) - Existing installations whose identity file is unreadable will now stop at explicit recovery instead of silently receiving a new device ID. That is the intended safety change, but maintainers should confirm the documented reset and re-pair path is reachable in the affected tray and setup flows.
  • Resolve merge risk (P1) - The patch changes durable identity, token persistence, gateway reconnect, node startup, CLI, setup, and tray handling across 31 files, so final CI and a focused maintainer review remain important even though no discrete current-head defect is established.
  • Complete next step (P2) - The PR is collaborator-authored and changes a durable identity and authentication boundary, so the remaining action is explicit maintainer acceptance rather than an automated repair.
Agent review details

Security

None.

Review metrics

Metric Value Why it matters
Changed surface 31 files, 2,782 additions, 282 deletions The patch reaches the durable identity boundary and every principal caller that creates or reconnects a gateway client.
Reported focused validation 6,392 passed, 31 skipped, 0 failed The PR and follow-up report shared, tray, connection, setup, and CLI validation in addition to terminal behavior proof.

Merge-risk options

Maintainer options:

  1. Confirm upgrade recovery before merge (recommended)
    Verify that a corrupt or locked active identity preserves its bytes and presents a reachable explicit reset and re-pair route in the tray and setup surfaces.
  2. Accept the explicit-recovery change
    Merge while accepting that users with damaged identity files must repair access or reset pairing instead of receiving a replacement identity automatically.

Technical review

Best possible solution:

Merge only after a maintainer accepts the intentional fail-closed upgrade behavior and the remaining current-head connection and setup checks confirm that users can reach explicit reset and re-pair recovery without losing an existing identity silently.

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

Yes. The branch adds targeted corrupt, locked, first-write, and concurrent-initializer tests, and its current-head test-host proof exercises corrupt and exclusively locked persisted identities out of process.

Is this the best way to solve the issue?

Yes. Centralizing fail-closed behavior in the persisted identity boundary and having callers classify the typed failure is narrower and safer than allowing each caller to regenerate or overwrite cryptographic identity material.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 80f35d074876.

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.

Label justifications:

  • P1: Silent device identity replacement forces re-pairing and interrupts real gateway and Windows node workflows.
  • merge-risk: 🚨 compatibility: Previously automatic recovery becomes an explicit repair and re-pair requirement for installations with unreadable identity files.
  • merge-risk: 🚨 auth-provider: The patch changes how device identity loading and durable device tokens participate in gateway authentication.
  • merge-risk: 🚨 availability: Gateway and node startup now fail explicitly when an active persisted identity cannot be loaded or safely updated.
  • 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 (terminal): The PR body and current-head collaborator report provide after-fix out-of-process terminal proof for corrupt and locked identities, including stable file hashes, explicit recovery output, no temporary files, and successful fresh initialization.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body and current-head collaborator report provide after-fix out-of-process terminal proof for corrupt and locked identities, including stable file hashes, explicit recovery output, no temporary files, and successful fresh initialization.

Evidence

What I checked:

Likely related people:

  • shanselman: The collaborator supplied the follow-up hardening commit and current-head validation report covering identity persistence, reconnect behavior, token storage, and recovery routing. (role: recent branch hardening contributor; confidence: high; commits: ba4fa8eb8b39, bb06fdc91bad; files: src/OpenClaw.Shared/DeviceIdentity.cs, src/OpenClaw.Connection/GatewayConnectionManager.cs, src/OpenClaw.Tray.WinUI/App.xaml.cs)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Review the explicit reset and re-pair recovery path alongside pending current-head connection and setup checks.

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 (1 earlier review cycle)
  • reviewed 2026-07-29T13:00:46.562Z sha 72e3c44 :: needs maintainer review before merge. :: none

Co-authored-by: Copilot App <[email protected]>

Copilot-Session: 7b9bc681-ce19-4a8b-b06c-94efb63a5f9f
@shanselman

Copy link
Copy Markdown
Collaborator

I pushed a maintainer hardening patch onto this branch and merged current main without rewriting history.

Key fixes:

  • Validate key material before token clearing or token updates, and never mutate corrupt identities.
  • Surface first-write and token-write failures as typed identity failures while preserving the existing file and in-memory token.
  • Keep successful operator/node handshakes alive when the client's first persistence attempt fails, then let the manager retry durable storage before clearing bootstrap credentials.
  • Stop orphaned SSH tunnels, with generation-safe and bounded node-only cleanup.
  • Keep optional token bookkeeping failures from poisoning a healthy operator connection.
  • Allow terminal node failures to recover on the next operator handshake.
  • Preserve MCP-only startup when gateway identity loading fails.
  • Give recovery guidance that works for per-gateway and legacy identity paths.

Validation

  • ./build.ps1: all projects built successfully.
  • dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-restore: 3,277 passed, 31 skipped.
  • dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj --no-restore: 1,958 passed.
  • dotnet test ./tests/OpenClaw.Connection.Tests/OpenClaw.Connection.Tests.csproj --no-restore: 457 passed.
  • dotnet test ./tests/OpenClaw.SetupEngine.Tests/OpenClaw.SetupEngine.Tests.csproj --no-restore: 700 passed.
  • Two independent final reviews found no remaining significant issues.

Real behavior proof

Current-head OpenClaw.Shared.TestHost was run out of process against both a corrupt identity and an exclusively locked valid identity:

  • Both exited with code 2 and the explicit recovery message.
  • SHA-256 before and after matched in both cases.
  • No temporary identity files remained.
  • A fresh identity still initialized successfully with a 64-character device ID.

Exact pushed head: bb06fdc91badea41e602f7a7ed90201a4b6df5f7.

@clawsweeper clawsweeper Bot added 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. labels Jul 29, 2026
@shanselman
shanselman merged commit c04c5fb into openclaw:main Jul 29, 2026
18 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 auth-provider 🚨 Merging this PR could break OAuth, tokens, provider routing, model choice, or credentials. merge-risk: 🚨 availability 🚨 Merging this PR could cause crashes, hangs, restart loops, stalls, or process outages. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P1 Urgent regression or broken agent/channel workflow affecting real users now. proof: sufficient Contributor real behavior proof is sufficient. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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.

2 participants