Skip to content

Commit 603886a

Browse files
bkudiessCopilot
andauthored
fix: harden gateway recovery credential handoffs (#1076)
Co-authored-by: Copilot App <[email protected]>
1 parent 20d29e1 commit 603886a

68 files changed

Lines changed: 6317 additions & 677 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/ci.yml‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ jobs:
352352
include:
353353
- name: setup-connect
354354
timeout_minutes: 45
355-
filter: "FullyQualifiedName~OpenClaw.E2ETests.Setup.SetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MxcSetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MirroredWslPortLeaseTests"
355+
filter: "FullyQualifiedName~OpenClaw.E2ETests.Setup.SetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MxcSetupAndConnectTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.MirroredWslPortLeaseTests|FullyQualifiedName~OpenClaw.E2ETests.Setup.SshOwnershipAdversarialProofTests"
356356
- name: revocation-recovery
357357
timeout_minutes: 25
358358
filter: FullyQualifiedName~OpenClaw.E2ETests.Setup.RevocationAndRecoveryTests
@@ -450,6 +450,29 @@ jobs:
450450
exit 1
451451
}
452452
}
453+
454+
$sshOwnershipProofNames = @(
455+
"UnownedListenerIsRejectedThenOwnedTunnelRecoversWithoutRepairing",
456+
"InitialHandshakeListenerReplacementWithholdsCredentialFrame",
457+
"InitialNodeHandshakeListenerReplacementWithholdsCredentialFrame"
458+
)
459+
foreach ($sshOwnershipProofName in $sshOwnershipProofNames) {
460+
$sshOwnershipProof = @(
461+
$trx.TestRun.Results.UnitTestResult |
462+
Where-Object { $_.testName -like "*$sshOwnershipProofName*" }
463+
) | Select-Object -First 1
464+
if ($null -eq $sshOwnershipProof) {
465+
Write-Error "E2E shard '${{ matrix.name }}' did not report the SSH ownership proof test '$sshOwnershipProofName'. Check the setup-connect filter before merging."
466+
exit 1
467+
}
468+
469+
$sshOwnershipOutcome = [string]$sshOwnershipProof.outcome
470+
if ($sshOwnershipOutcome -ne "Passed") {
471+
Write-Error "SSH ownership E2E proof '$sshOwnershipProofName' had outcome '$sshOwnershipOutcome'; this proof must pass and may not skip."
472+
exit 1
473+
}
474+
Write-Host "SSH ownership E2E proof passed: $sshOwnershipProofName"
475+
}
453476
}
454477
455478
- name: Upload E2E Test Results & Logs

‎docs/ARCHITECTURE.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ These are the canonical homes. Do not reintroduce private copies elsewhere.
7777
| `src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs` | `ChatSendQueue`, `ChatBridgeEventPump`, `ChatHistoryLoader`, `ChatSnapshotProjector`, `AttachmentMetadataStore`; pure native tool projection stays in `NativeToolProjector` |
7878
| `src/OpenClaw.Tray.WinUI/Chat/OpenClawChatTimeline.cs` | `ReactorChatTimeline` (production `ItemsView` / `ItemContainer`), `ChatBubbleRenderer`, `ToolCallCardRenderer`, `PermissionRequestCard`, `AttachmentBubbleRenderer` |
7979
| `src/OpenClaw.Tray.WinUI/Chat/OpenClawComposer.cs` | `ComposerViewModel`, `SlashCommandPalette`, `AttachmentPreviewStrip`, `VoiceComposerController` |
80-
| `src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs` | `ConnectionPagePlan` (pure), `ConnectionPageViewModel`, gateway row models |
80+
| `src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs` | `ConnectionPagePlan` (pure), `ConnectionPageViewModel`, `GatewayDirectConnectService`, gateway row models |
8181
| `src/OpenClaw.Tray.WinUI/Pages/SettingsPage.xaml.cs` | settings read/persist → `SettingsPageViewModel` + `ISettingsStore`; keep gateway-uninstall, uptime timer, saved-indicator, and app-info in the view |
8282
| `src/OpenClaw.Tray.WinUI/Services/NodeService.cs` | `McpServerHost`, `CanvasWindowManager`, `MediaCapabilityHost`, `RecordingConsentService`, `NodeCapabilityRegistry` |
8383
| `src/OpenClaw.Shared/OpenClawGatewayClient.cs` | `PendingRequestRegistry`, `ConnectEnvelopeBuilder`, `GatewayMessageRouter`, per-domain API facades |
@@ -125,6 +125,8 @@ leading and trailing pipe. Columns, in order:
125125
| gateway-wizard-restart-recovery | authoritative | WizardPage + SetupWizardRunner reconnect call sites | duplicated exact-version terminal-restart classification and bounded provenance retry orchestration | GatewayWizardRestartRecoveryPolicy | WizardPage and SetupWizardRunner apply hosted and headless lifecycle and consume provenance inspection results | only managed-local restart-like disconnects may retry NoListener or the typed snapshot-changed race; other unknown or conflicting ownership fails immediately, retryable startup close 1013 stays inside the existing reconnect bound, and exact Gateway 2026.7.1 final model-check close 1012 completes only after a fresh hello-ok | GatewayWizardRestartRecoveryPolicyTests.Exact2026_7_1TerminalModelCheckServiceRestart_IsExpected | behavioral | when the 2026.7.1 terminal-restart compatibility path is removed |
126126
| managed-local-repair | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs and direct reconnect callbacks | repair eligibility, restart budgets, port remediation, and reconnect verification | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | App composition and dependency callbacks only | explicit disconnect and gateway switches abort repair before restart or reconnect | ManagedLocalGatewayRepairCoordinatorTests.UserDisconnectedIntent_AbortsBeforeProbeOrRestart | behavioral | - |
127127
| app-managed-local-repair-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | managed-local repair loops, probing, restart budgeting, and verification implementation | ManagedLocalGatewayAutoRepairMonitor + ManagedLocalGatewayRepairCoordinator | service construction, callback adapters, and lifetime wiring only | App remains the composition root and does not regain repair implementation | AppRefactorContractTests.ManagedLocalGatewayRepair_StaysDelegatedToDedicatedOwners | source-shape | when App no longer constructs the managed-local repair services directly |
128+
| connection-page-direct-connect-closed | closed | src/OpenClaw.Tray.WinUI/Pages/ConnectionPage.xaml.cs | direct-connect registry, identity-token, settings, rollback, terminal-wait, and runtime-tunnel transaction | GatewayDirectConnectService | add-form control reads, input validation, result text, and post-success visual refresh only | the page delegates one request; rollback restores the durable registry before identity and settings, reconnects a previously live gateway, and a later credential writer wins | GatewayDirectConnectServiceTests.Connect_Failure_RestoresPreviousLiveConnection | behavioral | when the Connection page no longer contains any direct-connect persistence or rollback logic |
129+
| connection-status-direct-connect-closed | closed | src/OpenClaw.Tray.WinUI/Windows/ConnectionStatusWindow.xaml.cs | direct-connect registry, settings, rollback, terminal-wait, and runtime-tunnel transaction | GatewayDirectConnectService | diagnostics control reads, input validation, and result text only | diagnostics direct connect delegates one request and cannot report success before a terminal manager state | AppRefactorContractTests.StatusWindowDirectConnect_WaitsForManagerStateBeforeReportingConnected | source-shape | when the status window no longer contains direct-connect persistence or rollback logic |
128130
| app-window-manager | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | window creation/show/hide/shutdown | IWindowManager | composition/delegation only | startup/shutdown ordering deterministic; disposed once | none | review-only | extracted in Phase 3 |
129131
| app-tray-controller | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | tray icon/menu/action routing | ITrayController | composition/delegation only | tray actions route unchanged | none | review-only | extracted in Phase 3 |
130132
| app-activation-router | planned | src/OpenClaw.Tray.WinUI/App.xaml.cs | deep-link/toast/single-instance activation | IActivationRouter | composition/delegation only | activation routes land on the same UI/actions; current-user pipe security preserved | none | review-only | extracted in Phase 3 |

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,8 @@ Many gateway records may be saved, but only `ActiveId` in `gateways.json` is the
170170

171171
`SettingsManager` still owns general tray settings (node mode, MCP mode, SSH tunnel toggles, notifications, UI preferences). It may read legacy `Token` / `BootstrapToken` JSON fields into memory for migration, but save must not write those legacy credential fields back.
172172

173+
`GatewayDirectConnectService` is the single transaction owner for direct-connect UI surfaces. It commits the registry and active id, applies identity changes, persists `SettingsManager`, waits for a terminal manager state, and rolls back ordinary asynchronous connection failures as well as thrown failures. When the operation replaced a live operator connection, successful rollback reconnects that previous gateway before returning the failure. The Connection page and Connection Status window only validate controls and render the result. MCP shared-token replacement keeps its device-token-preserving validation semantics, then asks this service to synchronize the committed active gateway into settings and the runtime tunnel.
174+
173175
## Credential precedence
174176

175177
Credential resolution order is intentionally strict:
@@ -228,12 +230,12 @@ Both paths dispose old clients before creating new ones.
228230

229231
Setup codes (from QR scan or paste) decode to `{ url, bootstrapToken }` via `SetupCodeDecoder`. The flow:
230232

231-
1. `ApplySetupCodeAsync(code)` decodes and validates
232-
2. Creates/updates a `GatewayRecord` with the bootstrap token
233-
3. Clears stored device tokens (fresh pairing)
234-
4. Connects to the new gateway
235-
5. Gateway returns `hello-ok.auth.deviceToken` after pairing
236-
6. Connection manager persists the device token to the identity file
233+
1. `ApplySetupCodeAsync(code)` decodes and validates the gateway URL and bootstrap token
234+
2. Creates/updates and persists the active `GatewayRecord`, preserving any shared token and durable per-role device tokens
235+
3. Disconnects the previous connection only after the record is durable
236+
4. Forces `auth.bootstrapToken` for this connection attempt without clearing stored device tokens; the record-scoped force flag is consumed or cleared even when identity loading fails
237+
5. After successful pairing, the gateway returns `hello-ok.auth.deviceToken` and the connection manager persists the replacement role token
238+
6. If pairing or connection fails, the previously stored device tokens remain intact, so retrying or returning to the prior pairing does not require an unintended full re-pair
237239

238240
**Approval boundaries**: `GatewayConnectionManager` leaves node-pair command-trust requests and reapproval pending for explicit operator approval. It may automatically approve and reconnect only an explicitly typed device-pair request used for a device role upgrade.
239241

@@ -247,7 +249,9 @@ When **another** device or node requests pairing, the gateway broadcasts `device
247249

248250
`SshTunnelService` manages an SSH local port-forward process and implements `ISshTunnelManager` directly for the connection manager.
249251

250-
When a `GatewayRecord` has `SshTunnel` config, the connection manager starts the tunnel before connecting the WebSocket client to `ws://localhost:<localPort>`. The config stores the SSH daemon port (`sshPort`, default `22`) separately from the remote gateway port forwarded by `-L`.
252+
When a `GatewayRecord` has `SshTunnel` config, the connection manager starts the tunnel before connecting the WebSocket client to `ws://localhost:<localPort>`. The config stores the SSH daemon port (`sshPort`, default `22`) separately from the remote gateway port forwarded by `-L`. Startup allows up to 20 seconds for SSH transport, key exchange, authentication, and local-forward binding, while every sample still fails closed on incomplete listener capture or a conflicting loopback/wildcard owner. Same-number listeners bound only to non-loopback interfaces are irrelevant to the local forward and are ignored.
253+
254+
Credential handoff pins the verified tunnel lifecycle generation (or managed-local process identity) from preflight through the initial challenge authorization. If ownership changes between WebSocket acceptance and the credential frame, the current socket is aborted and only a fresh, reauthorized socket may retry.
251255

252256
`SshTunnelSnapshot` provides a read-only point-in-time view of tunnel state for UI consumption (avoids coupling UI to the mutable service).
253257

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"tunnelPort": 35064,
3+
"listenerCount": 3,
4+
"unrelatedListenerPresent": true,
5+
"ownedProcessId": 56340,
6+
"unrelatedProcessId": 41032
7+
}
86.7 KB
Loading
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
{
2+
"connectionStatus": "Connected",
3+
"overallState": "Degraded",
4+
"operatorState": "Connected",
5+
"nodeState": "Error",
6+
"nodeConnected": false,
7+
"nodePaired": false,
8+
"nodePendingApproval": false,
9+
"nodeError": "The configured SSH listener is not owned by the active OpenClaw tunnel, so credentials were not sent.",
10+
"gatewayVersion": "2026.6.11",
11+
"sessionCount": 0,
12+
"nodeCount": 1,
13+
"operatorScopes": [
14+
"operator.admin",
15+
"operator.pairing",
16+
"operator.read",
17+
"operator.write"
18+
],
19+
"operatorDeviceId": null
20+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"head": "31e156399778be8200f717b59c03d103927db68d",
3+
"webSocketAcceptedBeforeListenerReplacement": true,
4+
"listenerOwnedAtTunnelStart": true,
5+
"listenerOwnedAtCredentialHandoff": false,
6+
"ownershipChecksBeforeChallenge": 1,
7+
"ownershipChecksAfterChallenge": 2,
8+
"credentialBearingConnectFramesReceived": 0,
9+
"operatorState": "Error",
10+
"error": "The configured SSH listener is not owned by the active OpenClaw tunnel, so credentials were not sent."
11+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"head": "31e156399778be8200f717b59c03d103927db68d",
3+
"webSocketAcceptedBeforeListenerReplacement": true,
4+
"listenerOwnedAtTunnelStart": true,
5+
"listenerOwnedAtCredentialHandoff": false,
6+
"ownershipChecksBeforeChallenge": 2,
7+
"ownershipChecksAfterChallenge": 4,
8+
"credentialBearingConnectFramesReceived": 0,
9+
"nodeState": "Error",
10+
"error": "Node transport error"
11+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"restoreOutcome": "Superseded",
3+
"newerOperatorCredentialPreserved": true,
4+
"newerNodeCredentialPreserved": true,
5+
"originalOperatorCredentialWasNotRestored": true,
6+
"originalNodeCredentialWasNotRestored": true
7+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
{
2+
"tunnelPort": 35064,
3+
"owned": true,
4+
"listenerCount": 2,
5+
"processName": "ssh",
6+
"processId": 56340,
7+
"addresses": [
8+
"127.0.0.1",
9+
"::1"
10+
]
11+
}

0 commit comments

Comments
 (0)