Skip to content

Commit ba4fa8e

Browse files
committed
Harden identity failure recovery
Co-authored-by: Copilot App <[email protected]> Copilot-Session: 7b9bc681-ce19-4a8b-b06c-94efb63a5f9f
1 parent 72e3c44 commit ba4fa8e

12 files changed

Lines changed: 658 additions & 104 deletions

File tree

‎src/OpenClaw.Connection/GatewayConnectionManager.cs‎

Lines changed: 89 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,43 @@ public async Task ConnectNodeOnlyAsync(string? gatewayId = null)
193193

194194
var startedGeneration = await StartNodeConnectionAsync(preparedGeneration.Value);
195195
if (startedGeneration.HasValue)
196+
{
196197
EmitStateChanged();
198+
}
199+
else
200+
{
201+
if (Interlocked.Read(ref _generation) != preparedGeneration.Value ||
202+
_tunnelManager?.IsActive != true)
203+
{
204+
return;
205+
}
206+
207+
var enteredTransition = await _transitionSemaphore
208+
.WaitAsync(TimeSpan.FromSeconds(1))
209+
.ConfigureAwait(false);
210+
if (!enteredTransition)
211+
{
212+
_logger.Warn("[ConnMgr] Timed out waiting to clean up failed node-only tunnel");
213+
_diagnostics.Record(
214+
"tunnel",
215+
"Timed out waiting to clean up failed node-only tunnel");
216+
return;
217+
}
218+
219+
try
220+
{
221+
if (Interlocked.Read(ref _generation) == preparedGeneration.Value &&
222+
_activeLifecycle == null &&
223+
_tunnelManager?.IsActive == true)
224+
{
225+
await StopTunnelAfterFailedConnectionAsync("node-only connection failure");
226+
}
227+
}
228+
finally
229+
{
230+
_transitionSemaphore.Release();
231+
}
232+
}
197233
}
198234

199235
/// <summary>Core connect logic. Caller must hold <see cref="_transitionSemaphore"/>.</summary>
@@ -376,6 +412,7 @@ tunnel.SshPort is < 1 or > 65535 ||
376412
_stateMachine.TryTransition(
377413
ConnectionTrigger.WebSocketError,
378414
DeviceIdentityLoadException.RecoveryMessage);
415+
await StopTunnelAfterFailedConnectionAsync("operator identity load failure");
379416
CompleteOperatorTelemetryAttempt(
380417
gen,
381418
"failure",
@@ -521,6 +558,21 @@ tunnel.SshPort is < 1 or > 65535 ||
521558

522559
var nodeCredentialResolution = _credentialResolver.ResolveNodeDetailed(record, perGatewayIdentityDir);
523560
var nodeCredential = nodeCredentialResolution.Credential;
561+
if (HasPersistedIdentityFailure(nodeCredentialResolution))
562+
{
563+
_diagnostics.RecordCredentialResolutionResult(nodeCredentialResolution);
564+
_diagnostics.Record(
565+
"identity",
566+
"Stored device identity could not be loaded for node-only connection",
567+
nodeCredentialResolution.Detail);
568+
_stateMachine.SetNodeCredentialResolution(nodeCredentialResolution);
569+
_stateMachine.BlockNodeStart(
570+
DeviceIdentityLoadException.RecoveryMessage,
571+
preserveCredentialResolution: true);
572+
EmitStateChanged();
573+
RecordNodePreflightTelemetryFailure(ConnectionErrorCategory.InternalError);
574+
return null;
575+
}
524576
if (nodeCredential == null)
525577
{
526578
_logger.Warn("[ConnMgr] No node credential available for node-only connect");
@@ -588,6 +640,30 @@ tunnel.RemotePort is < 1 or > 65535 ||
588640
}
589641
}
590642

643+
private async Task StopTunnelAfterFailedConnectionAsync(string operation)
644+
{
645+
if (_tunnelManager?.IsActive != true)
646+
return;
647+
648+
try
649+
{
650+
var stopTask = _tunnelManager.StopAsync();
651+
if (await Task.WhenAny(stopTask, Task.Delay(TimeSpan.FromSeconds(5))) != stopTask)
652+
{
653+
_logger.Warn($"[ConnMgr] Tunnel stop timed out after {operation}");
654+
return;
655+
}
656+
657+
await stopTask;
658+
_diagnostics.Record("tunnel", $"SSH tunnel stopped after {operation}");
659+
}
660+
catch (Exception ex)
661+
{
662+
_logger.Warn($"[ConnMgr] Tunnel stop failed after {operation}: {ex.Message}");
663+
_diagnostics.Record("tunnel", $"SSH tunnel stop failed after {operation}", ex.Message);
664+
}
665+
}
666+
591667
public async Task DisconnectAsync()
592668
{
593669
ThrowIfDisposed();
@@ -1167,6 +1243,11 @@ private async Task HandleDeviceTokenReceivedAsync(
11671243
catch (Exception ex)
11681244
{
11691245
_logger.Warn($"[ConnMgr] Failed to persist {e.Role} device token: {ex.Message}");
1246+
_diagnostics.Record(
1247+
"identity",
1248+
$"Failed to persist {e.Role} device token",
1249+
ex.Message);
1250+
return;
11701251
}
11711252
}
11721253

@@ -1709,10 +1790,6 @@ private bool TryReadStoredTokenPresence(
17091790
"identity",
17101791
$"Stored device identity could not be loaded while {operation}",
17111792
detail);
1712-
_stateMachine.TryTransition(
1713-
ConnectionTrigger.WebSocketError,
1714-
DeviceIdentityLoadException.RecoveryMessage);
1715-
EmitStateChanged();
17161793
return false;
17171794
}
17181795
}
@@ -1992,6 +2069,14 @@ private void OnNodeConnectionFailure(object? sender, GatewayErrorKind errorKind)
19922069
if (!IsCurrentNodeAttempt(lifecycleGeneration, nodeGeneration))
19932070
return;
19942071

2072+
lock (_nodeOperationLock)
2073+
{
2074+
Interlocked.CompareExchange(
2075+
ref _nodeStartLifecycleGeneration,
2076+
-1,
2077+
lifecycleGeneration);
2078+
}
2079+
19952080
CompleteNodeTelemetryAttempt(
19962081
nodeGeneration,
19972082
"failure",

‎src/OpenClaw.Shared/DeviceIdentity.cs‎

Lines changed: 79 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,14 @@ public static bool TryClearAllDeviceTokens(string dataPath, IOpenClawLogger? log
169169
return false;
170170
}
171171

172+
var data = root.Deserialize<DeviceKeyData>();
173+
if (data == null)
174+
{
175+
logger?.Warn("Failed to clear all device tokens: device-key-ed25519.json did not contain an object.");
176+
return false;
177+
}
178+
_ = ValidateAndReconstruct(data);
179+
172180
bool hadTokens = false;
173181
using var ms = new MemoryStream();
174182
using (var writer = new System.Text.Json.Utf8JsonWriter(ms, new System.Text.Json.JsonWriterOptions { Indented = true }))
@@ -209,6 +217,16 @@ public static bool TryClearAllDeviceTokens(string dataPath, IOpenClawLogger? log
209217
logger?.Warn($"Failed to clear all device tokens: {ex.Message}");
210218
return false;
211219
}
220+
catch (Exception ex) when (
221+
ex is FormatException
222+
or ArgumentException
223+
or InvalidDataException
224+
or InvalidOperationException
225+
or CryptographicException)
226+
{
227+
logger?.Warn($"Failed to clear all device tokens: {ex.Message}");
228+
return false;
229+
}
212230
}
213231

214232
/// <summary>
@@ -372,6 +390,22 @@ private static IdentityMaterial ValidateAndReconstruct(DeviceKeyData data)
372390
}
373391

374392
private void GenerateNewOrLoadWinner()
393+
{
394+
try
395+
{
396+
GenerateNewOrLoadWinnerCore();
397+
}
398+
catch (DeviceIdentityLoadException)
399+
{
400+
throw;
401+
}
402+
catch (Exception ex) when (IsIdentityLoadFailure(ex))
403+
{
404+
throw CreateLoadException(ex);
405+
}
406+
}
407+
408+
private void GenerateNewOrLoadWinnerCore()
375409
{
376410
_logger.Info("Generating new Ed25519 device keypair...");
377411

@@ -394,8 +428,9 @@ private void GenerateNewOrLoadWinner()
394428
if (!string.IsNullOrEmpty(dir) && !_fileSystem.DirectoryExists(dir))
395429
{
396430
_fileSystem.CreateDirectory(dir);
397-
McpAuthToken.TryRestrictDataDirectoryAcl(dir);
398431
}
432+
if (!string.IsNullOrEmpty(dir))
433+
McpAuthToken.TryRestrictDataDirectoryAcl(dir);
399434

400435
if (!TryCreateKeyFile(data))
401436
{
@@ -724,28 +759,23 @@ private void StoreDeviceTokenCore(string token, string[]? scopes)
724759
if (string.IsNullOrWhiteSpace(token))
725760
throw new ArgumentException("Device token cannot be empty.", nameof(token));
726761

727-
_deviceToken = token;
728-
_deviceTokenScopes = scopes;
729-
730-
// Update the key file with the token
731762
try
732763
{
733-
if (File.Exists(_keyPath))
734-
{
735-
var json = File.ReadAllText(_keyPath);
736-
var data = JsonSerializer.Deserialize<DeviceKeyData>(json);
737-
if (data != null)
738-
{
739-
data.DeviceToken = token;
740-
data.DeviceTokenScopes = scopes;
741-
AtomicWriteKeyFile(_keyPath, data);
742-
_logger.Info("Device token stored");
743-
}
744-
}
764+
var data = ReadCurrentIdentityForTokenUpdate();
765+
data.DeviceToken = token;
766+
data.DeviceTokenScopes = scopes;
767+
AtomicWriteKeyFile(_keyPath, data);
768+
_deviceToken = token;
769+
_deviceTokenScopes = scopes;
770+
_logger.Info("Device token stored");
745771
}
746-
catch (Exception ex)
772+
catch (DeviceIdentityLoadException)
773+
{
774+
throw;
775+
}
776+
catch (Exception ex) when (IsIdentityLoadFailure(ex))
747777
{
748-
_logger.Error($"Failed to store device token: {ex.Message}");
778+
throw CreateLoadException(ex);
749779
}
750780
}
751781

@@ -754,30 +784,43 @@ private void StoreNodeDeviceTokenCore(string token, string[]? scopes)
754784
if (string.IsNullOrWhiteSpace(token))
755785
throw new ArgumentException("Device token cannot be empty.", nameof(token));
756786

757-
_nodeDeviceToken = token;
758-
_nodeDeviceTokenScopes = scopes;
759-
760787
try
761788
{
762-
if (File.Exists(_keyPath))
763-
{
764-
var json = File.ReadAllText(_keyPath);
765-
var data = JsonSerializer.Deserialize<DeviceKeyData>(json);
766-
if (data != null)
767-
{
768-
data.NodeDeviceToken = token;
769-
data.NodeDeviceTokenScopes = scopes;
770-
AtomicWriteKeyFile(_keyPath, data);
771-
_logger.Info("Node device token stored");
772-
}
773-
}
789+
var data = ReadCurrentIdentityForTokenUpdate();
790+
data.NodeDeviceToken = token;
791+
data.NodeDeviceTokenScopes = scopes;
792+
AtomicWriteKeyFile(_keyPath, data);
793+
_nodeDeviceToken = token;
794+
_nodeDeviceTokenScopes = scopes;
795+
_logger.Info("Node device token stored");
774796
}
775-
catch (Exception ex)
797+
catch (DeviceIdentityLoadException)
798+
{
799+
throw;
800+
}
801+
catch (Exception ex) when (IsIdentityLoadFailure(ex))
776802
{
777-
_logger.Error($"Failed to store node device token: {ex.Message}");
803+
throw CreateLoadException(ex);
778804
}
779805
}
780806

807+
private DeviceKeyData ReadCurrentIdentityForTokenUpdate()
808+
{
809+
if (_deviceId == null)
810+
throw new InvalidOperationException("Device not initialized");
811+
if (!File.Exists(_keyPath))
812+
throw new FileNotFoundException("Device identity file is missing.", _keyPath);
813+
814+
var json = File.ReadAllText(_keyPath);
815+
var data = JsonSerializer.Deserialize<DeviceKeyData>(json)
816+
?? throw new InvalidDataException("Identity file was empty or invalid.");
817+
var material = ValidateAndReconstruct(data);
818+
if (!string.Equals(material.DeviceId, _deviceId, StringComparison.Ordinal))
819+
throw new InvalidDataException("Identity file changed while updating its device token.");
820+
821+
return data;
822+
}
823+
781824
/// <summary>
782825
/// Atomic write of device-key JSON: serialize to a sibling temp file
783826
/// (<c>.&lt;name&gt;.&lt;guid&gt;.tmp</c>), lock its ACL, then

‎src/OpenClaw.Shared/DeviceIdentityLoadException.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ namespace OpenClaw.Shared;
77
public sealed class DeviceIdentityLoadException : Exception
88
{
99
public const string RecoveryMessage =
10-
"Saved device identity could not be loaded. OpenClaw did not replace it. Check file access or reset pairing explicitly.";
10+
"Device identity could not be loaded or saved. OpenClaw did not replace an existing identity. Check access to the identity file shown in diagnostics. If it exists and you intend to reset pairing, move it aside explicitly, then reconnect.";
1111

1212
public DeviceIdentityLoadException(string identityPath, Exception innerException)
1313
: base(RecoveryMessage, innerException)

‎src/OpenClaw.Shared/OpenClawGatewayClient.cs‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1883,11 +1883,11 @@ private void HandleResponse(JsonElement root)
18831883
var persistedRoleTokens = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
18841884
foreach (var roleToken in EnumerateHandshakeDeviceTokens(payload))
18851885
{
1886-
_deviceIdentity.StoreDeviceTokenForRole(roleToken.Role, roleToken.Token, roleToken.Scopes);
1886+
var stored = TryStoreHandshakeDeviceToken(roleToken.Role, roleToken.Token, roleToken.Scopes);
18871887
persistedRoleTokens.Add(roleToken.Role);
1888-
if (roleToken.Role.Equals("node", StringComparison.OrdinalIgnoreCase))
1888+
if (stored && roleToken.Role.Equals("node", StringComparison.OrdinalIgnoreCase))
18891889
_logger.Info("Node device token stored for Windows tray node reconnect");
1890-
else
1890+
else if (stored)
18911891
_logger.Info($"{roleToken.Role} device token stored for reconnect");
18921892
DeviceTokenReceived?.Invoke(this, new DeviceTokenReceivedEventArgs(roleToken.Token, roleToken.Scopes, roleToken.Role));
18931893
}
@@ -1898,9 +1898,10 @@ private void HandleResponse(JsonElement root)
18981898
if (!string.IsNullOrWhiteSpace(nodeDeviceToken))
18991899
{
19001900
var nodeDeviceTokenScopes = TryGetHandshakeDeviceTokenScopesCore(payload, "node", allowDirectDeviceTokenFallback: true);
1901-
_deviceIdentity.StoreDeviceTokenForRole("node", nodeDeviceToken, nodeDeviceTokenScopes);
1901+
var stored = TryStoreHandshakeDeviceToken("node", nodeDeviceToken, nodeDeviceTokenScopes);
19021902
persistedRoleTokens.Add("node");
1903-
_logger.Info("Node device token stored for Windows tray node reconnect");
1903+
if (stored)
1904+
_logger.Info("Node device token stored for Windows tray node reconnect");
19041905
DeviceTokenReceived?.Invoke(this, new DeviceTokenReceivedEventArgs(nodeDeviceToken, nodeDeviceTokenScopes, "node"));
19051906
}
19061907
}
@@ -1913,9 +1914,10 @@ private void HandleResponse(JsonElement root)
19131914
var deviceTokenScopes = _bootstrapPairAsNode
19141915
? TryGetHandshakeDeviceTokenScopesCore(payload, OperatorRole, allowDirectDeviceTokenFallback: false)
19151916
: TryGetHandshakeDeviceTokenScopesCore(payload, preferredRole: null);
1916-
_deviceIdentity.StoreDeviceTokenWithScopes(newDeviceToken, deviceTokenScopes);
1917+
var stored = TryStoreHandshakeDeviceToken(OperatorRole, newDeviceToken, deviceTokenScopes);
19171918
_connectAuthToken = newDeviceToken;
1918-
_logger.Info("Operator device token stored for reconnect");
1919+
if (stored)
1920+
_logger.Info("Operator device token stored for reconnect");
19191921
DeviceTokenReceived?.Invoke(this, new DeviceTokenReceivedEventArgs(newDeviceToken, deviceTokenScopes, "operator"));
19201922
}
19211923

@@ -1974,6 +1976,21 @@ private void HandleResponse(JsonElement root)
19741976
}
19751977
}
19761978

1979+
private bool TryStoreHandshakeDeviceToken(string role, string token, string[]? scopes)
1980+
{
1981+
try
1982+
{
1983+
_deviceIdentity.StoreDeviceTokenForRole(role, token, scopes);
1984+
return true;
1985+
}
1986+
catch (DeviceIdentityLoadException ex)
1987+
{
1988+
_logger.Error(
1989+
$"Failed to persist {role} device token during handshake; connection remains active: {ex.InnerException?.Message}");
1990+
return false;
1991+
}
1992+
}
1993+
19771994
private bool HandleKnownResponse(string method, JsonElement payload)
19781995
{
19791996
switch (method)

0 commit comments

Comments
 (0)