Skip to content

fix: restore the previous gateway when a shared token is rejected - #2443

Open
SebTardif wants to merge 4 commits into
openclaw:mainfrom
SebTardif:fix/2439-restore-shared-token-failure
Open

SebTardif wants to merge 4 commits into
openclaw:mainfrom
SebTardif:fix/2439-restore-shared-token-failure

Conversation

@SebTardif

@SebTardif SebTardif commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Related: #2439
Closes #2439

What Problem This Solves

Connecting Companion with a shared token saves that token and clears the bootstrap token before the gateway accepts the connection. If the gateway then rejects the token, the previous gateway, its bootstrap token, and its SSH tunnel stay cleared. The failed gateway is left active. A first attempt, with no previous gateway, also left settings pointing at the rejected address.

User Impact

User impact: a rejected shared token puts Companion back on the previous gateway, including the bootstrap token, saved connection settings, and a connection that was already live. If that was the first gateway, settings return to what they were before the attempt. A second attempt waits until that restore has finished, so it cannot save the rejected address as the snapshot it would restore. If that restore cannot be saved, the new gateway stays active and the failure says to open Connection settings and reconnect. Saving a new device token after the gateway has accepted the shared token does not undo that gateway.

Why This Change Was Made

The shared token was stored, and the settings callback ran, before the operator connection was admitted. A rejection now writes the previous record back, runs that same callback with the restored record, drops the rejected operator client, and reconnects a gateway that was already connected. When there is no previous record, the shared-token handler restores the settings snapshot taken after the attempt holds the lifecycle lease.

A second shared-token call cannot take that snapshot until the first call has restored settings and released the lease. If the settings callback fails before a first gateway is left active, that same restore runs before the lease is released.

The gateway can reject the token after the connect call returns. The attempt waits up to 15 seconds for that rejection. Set OPENCLAW_SHARED_TOKEN_HANDSHAKE_TIMEOUT_MS to change the budget. An attempt that is still connecting when the budget ends stays on the new record, because the gateway has not rejected it. Whether that cutoff should instead wait until authentication finishes is a maintainer decision. A failure to write the new device token is also left in place. Cancellation after the save stays on the new record.

This is a new branch from current main. Closed pull #1509 is not reopened.

Evidence

On source 8ca63225 in C:\Users\sebta\wt-wn-2439 (.NET SDK 10.0.404, Windows AMD64):

  • ./build.ps1 exited 0. Cli, Shared, WinNodeCli, WinUI, and SetupEngine built.
  • dotnet test .\tests\OpenClaw.Tray.Tests\OpenClaw.Tray.Tests.csproj --no-restore passed 7394, skipped 0, failed 0.
  • dotnet test .\tests\OpenClaw.Connection.Tests\OpenClaw.Connection.Tests.csproj --no-restore passed 1858, skipped 1 (Migration_CopiesAcrossConfiguredDistinctVolume), failed 0.
  • dotnet test .\tests\OpenClaw.Shared.Tests\OpenClaw.Shared.Tests.csproj --no-restore passed 6279, skipped 28, failed 0.
  • CI on e272c33b passed, 31 checks, 12 skipped, including Revocation recovery. That run is not this head.

A rejection delivered after connect returns, for a record that still had old-shared and bootstrap-token, came back as connection failed, gateway not committed, the saved token old-shared, and the bootstrap token restored. Two overlapping first-gateway calls recorded a-start, a-commit, a-restore, then b-start. The second call did not start until the first restore finished. A device-identity save failure stayed on the new shared token.

Required proof pools

  • none: this change rolls back the connection manager and the saved connection settings after a rejected shared token. It does not change the signed installer, ARM64 runtime, MXC containment, WSL gateway setup, or a WinUI window layout.

Validation

Head 8ca63225690e85448e00c88f8d2b68f20170f0ff. Host: Windows AMD64, .NET SDK 10.0.404.

  • ./build.ps1 exit 0
  • Tray: 7394 passed, 0 skipped, 0 failed
  • Connection: 1858 passed, 1 skipped, 0 failed
  • Shared: 6279 passed, 28 skipped, 0 failed
  • CI on parent e272c33b: pass, 31 checks, 12 skipped. Not this head.

Real behavior proof

  • Behavior or issue addressed: A shared-token connect cleared the bootstrap token and left the new gateway active when the gateway rejected the token. A first attempt also left saved settings on the rejected address. A second attempt could snapshot those temporary settings.
  • Real environment tested: Windows AMD64, .NET SDK 10.0.404, source 8ca6322. Revocation recovery on parent e272c33 ran against a real WSL gateway.
  • Exact steps or command run after this patch: Call the shared-token connect for wss://test1 with a token the gateway rejects after the connect call returns, while the saved record still has old-shared and bootstrap-token. Repeat with no previous gateway, then put the captured settings back. Start a second first-gateway call while the first call still holds the lifecycle lease. Repeat when the failure text is the device-identity save message.
  • Evidence after fix: terminal outcome from those calls:
rejected token with a previous gateway:
  outcome=ConnectionFailed
  gateway committed=false
  saved token=old-shared
  bootstrap token=bootstrap-token

two first-gateway calls, lease held by the first:
  order=a-start, a-commit, a-restore, b-start, b-commit, b-restore
  second start while the first lease is held=no

device identity save failure:
  outcome=Success
  gateway committed=true
  saved token=shared-token
  • Observed result after fix: A rejected token restores the previous record. A first rejection restores the settings captured after the lifecycle lease is held. The second call starts only after that restore. A device-identity save failure stays on the new gateway. Rollback text says to open Connection settings and reconnect a valid gateway.
  • What was not tested: A Companion window, a shipped MCP client, a populated v2026.11.3 profile, and an SSH listener on this commit. The 15 second cutoff was not driven against a slow gateway.

A shared-token connect saved the new token and cleared the bootstrap
token before the gateway accepted the connection. A rejection now
restores the previous record, asks the settings callback to follow
that record, and reconnects a gateway that was already live. If the
rollback cannot be saved, the new gateway stays active.

The handshake budget is 15 seconds. Set
OPENCLAW_SHARED_TOKEN_HANDSHAKE_TIMEOUT_MS to change it. An attempt
that is still connecting when the budget ends stays committed, because
the gateway has not rejected it yet.

Signed-off-by: Sebastien Tardif <SebTardif@ncf.ca>
@clawsweeper

clawsweeper Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

🦞👀
Pull request received.

ClawSweeper review complete

ClawSweeper finished reviewing this revision.

View the workflow run.

@clawsweeper clawsweeper Bot added P2 Normal priority bug or improvement with limited blast radius. impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Dec 2, 2026
@clawsweeper

clawsweeper Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge.

What this changes

Restore saved gateway configuration, connection settings, and a previously live connection when shared-token replacement fails.

Example: Replace the token for wss://test1, whose saved record contains old-shared and bootstrap-token, with rejected-token.

  • Before: The rejected token remains saved and the bootstrap token is cleared.
  • After: A rejection observed within the handshake budget restores old-shared and bootstrap-token and attempts to reconnect the previous live gateway.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The previous code finding is resolved and no new definite blocking defect was found, but required runtime and existing-state proof remain unestablished and the bounded recovery contract needs an owner decision.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦪 silver shellfish (2/6) The previous code finding is resolved and no new definite blocking defect was found, but required runtime and existing-state proof remain unestablished and the bounded recovery contract needs an owner decision.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Partial
User problem: A failed shared-token replacement can erase usable setup credentials and SSH configuration and leave the previous connection unavailable.
Reason: Transactional recovery has established value and prior collaborator direction, but rejection after the new observation cutoff remains outside recovery and the cutoff option lacks owner approval.

Merge readiness

⛔ Blocked before merge - 2 items remain

This PR addresses credential loss still present on current main, and the latest revision resolves the previous settings-serialization finding.

Reviewed head: 8ca63225690e85448e00c88f8d2b68f20170f0ff
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should shared-token recovery end after the configurable 15-second observation budget, leaving a still-Connecting gateway committed even if it later rejects the token?
  • Recommendation: Accept bounded recovery: Explicitly accept the configurable observation budget and its limitation that rejection after expiry does not restore the previous gateway.
  • Why: The author explicitly leaves this choice open; prior collaborator approval covers transactional recovery but does not approve this cutoff or its new environment option.

Before merge

  • Add real behavior proof - The supplied terminal outcomes exercise mocked lifecycle rejection and settings callbacks, while parent-head revocation E2E exercises a different path; the contributor must supply current-head shipped MCP recovery output with real authentication rejection and redact IPs, credentials, and non-public endpoints. Compatibility also requires a populated v2026.11.3 profile demonstrating preserved gateways.json ActiveId, SharedGatewayToken, BootstrapToken, and SshTunnel plus settings.json connection preferences. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

None.

Tests

  • Missing end-to-end proof: Provide current-head shipped MCP discovery and invocation against a real authentication rejection showing registry, settings, SSH listener, and prior-connection recovery, including the selected cutoff behavior; base-fail/head-pass execution of the new regressions is not shown.
Agent review details

How this fits together

The local MCP shared-token command enters GatewayConnectionManager, which coordinates gateway persistence, operator authentication, and callbacks into the existing settings and tunnel service.

flowchart TD
A[Local MCP command] --> B[GatewayConnectionManager]
B --> C[GatewayRegistry]
B --> D[Operator connection]
B --> E[GatewayDirectConnectService]
E --> F[Saved connection settings]
E --> G[Runtime SSH tunnel]
Loading

Technical review

Best possible solution:

Keep recovery in the existing manager and settings service, with an owner-approved authentication observation contract and demonstrated preservation of existing saved configuration.

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

Current-main source establishes the bootstrap-only failure path: replacement is persisted before asynchronous authentication, and failure retains it; no builds, tests, or runtime reproduction were run during this read-only review.

Is this the best way to solve the issue?

The existing connection manager and settings service are appropriate owners, and the latest revision repairs snapshot serialization without adding a parallel transaction service.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6a92b23e9b19.

Provenance checked

  • Credential replacement and committed-failure handling keeps the original intent (603886a: Merged recovery hardening preserved paired device-token precedence and coordinated credential, settings, and runtime handoffs.)
  • Settings synchronization ownership keeps the original intent (603886a: GatewayDirectConnectService synchronizes the committed active gateway into saved settings and runtime tunnel state with rollback on synchronization failure.)
  • Connection-initiation return behavior changes intended behavior with a stated reason (5a18150: The existing path persisted validated replacement configuration before initiating the live connection; the PR explains that asynchronous rejection requires releasing the transition lock and observing authentication.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

Likely related people:

  • Barbara Kudiess: Raw commit 603886a adds src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs:249 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 603886a81d34; files: src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs)
  • Sebastien Tardif: Raw commit 0e45bb6 adds src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs:275 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 0e45bb673025; files: src/OpenClaw.Tray.WinUI/Services/GatewayDirectConnectService.cs)

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Introduced production and test changes Production +295/-17; tests +365/-8 Growth implements recovery in existing owners and covers distinct rejection, persistence, first-gateway, and serialization outcomes.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #2439
Summary: This PR is the current recovery candidate for the canonical credential-replacement report; the earlier recovery PR closed without merging.

Members:

These related items are listed for context. Any action on an item requires its own checks.

Labels

Label changes:

No label changes.

Label justifications:

  • merge-risk: 🚨 compatibility: The PR changes persisted gateway/settings restoration and introduces a configurable boundary after which authentication rejection no longer triggers recovery.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🦪 silver shellfish.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall readiness starts with the lower of the proof and patch scores. It is capped at 3/6 if the fix is partial, the change offers little benefit, a product decision is still open, or the PR reverses an earlier decision without saying why. ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-12-02T05:02:33.494Z sha 0a57223 :: needs real behavior proof before merge. :: [P2] [P2] Restore settings when rollback leaves no active gateway | [P2] [P2] Include a recovery action in rollback failure messages
  • reviewed 2026-12-02T05:56:12.767Z sha e272c33 :: needs real behavior proof before merge. :: [P2] [P2] Capture and restore settings inside the serialized connection attempt

Reviewed December 2, 2026, 1:48 AM ET / 06:48 UTC (Revision 3).

A rejected shared token still restores the previous gateway. A failure
to write the new device token means the gateway already accepted the
token. Disconnecting that attempt abandoned the replacement pairing.

Signed-off-by: Sebastien Tardif <SebTardif@ncf.ca>
A first shared-token attempt has no previous gateway. Rejection removed
the new registry record but left settings on that rejected address.
The shared-token handler now puts the saved URL and tunnel back.
Rollback failures tell the user to open Connection settings and reconnect.

Signed-off-by: Sebastien Tardif <SebTardif@ncf.ca>
@SebTardif

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Head e272c33 restores the settings captured before a first shared-token attempt when that attempt is rejected and there is no previous gateway. Rollback failures now say to open Connection settings and reconnect a valid gateway. A device-token save failure stays on the new gateway. The 15 second handshake cutoff, and a live Companion rejection against a populated profile, are still open.

@clawsweeper

clawsweeper Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

🦞👀

Re-review progress:

A second shared-token call could snapshot the first attempt's temporary
settings while that attempt waited outside the lifecycle lease. Capture
and the empty-registry restore now run only after the lease and the
transition lock are held. If the settings callback fails on a first
gateway, the pre-attempt snapshot is restored before the lease is
released. A restore that cannot be saved leaves the candidate active.

Signed-off-by: Sebastien Tardif <SebTardif@ncf.ca>
@SebTardif

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The settings snapshot is now taken after the shared-token call holds the lifecycle lease. A second call cannot capture the first attempt's temporary settings. Empty-registry restore also runs before that lease is released, including when the settings callback fails.

The 15 second cutoff is still a maintainer decision. This head still has no Companion window, populated v2026.11.3 profile, or SSH listener proof.

@clawsweeper

clawsweeper Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

🦞👀

Re-review progress:

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

impact:other This issue has meaningful maintainer-visible impact outside the owned taxonomy. merge-risk: 🚨 compatibility 🚨 Merging this PR could break existing users, config, migrations, defaults, or upgrades. P2 Normal priority bug or improvement with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A failed shared-token connect clears the bootstrap token

1 participant