diff --git a/.agents/skills/winnode/SKILL.md b/.agents/skills/winnode/SKILL.md
index bb13dddf08..34060e892d 100644
--- a/.agents/skills/winnode/SKILL.md
+++ b/.agents/skills/winnode/SKILL.md
@@ -617,6 +617,11 @@ Build the same gateway dashboard URL the tray opens.
{"path": "string"} // optional
```
Returns `{ url, credentialSource, usesSharedGatewayToken, hasTokenQuery }`.
+`credentialSource` is the selected credential's provenance, not proof it was
+included in the URL. `usesSharedGatewayToken` reports actual browser credential
+inclusion: false for verified Tailscale identity and bootstrap-only links, true
+for shared-token fallback. Device/bootstrap credentials are not exported.
+`hasTokenQuery` checks the query only; it does not describe a token fragment.
## App connection diagnostics and setup (app.connection.*)
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 53645034c1..13e2450592 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -334,6 +334,7 @@ new attempt. This boundary does not change release signing or Windows policy.
| Desktop lobster quick-chat mounts and dedicated session identity | `DesktopCompanionChatHost` borrows the current app provider and owns separate retained dedicated/reply Reactor mounts, window-owned attachment picking and invocation-scoped voice-service callbacks. Notification replacement hides the mount and cancels capture without discarding its draft; late picker/capture results cannot cross hide or Gateway changes. `DesktopCompanionChatSessions` retains one confirmed or in-flight dedicated session per Gateway; closing a bubble does not repeat `sessions.create`. `ReactorChatHostExtensions` remains the shared mount owner and `OpenClawReactorChatRoot` supplies the compact layout. Chat notifications select their existing action-route session, never the main conversation as a fallback | authoritative |
| Gateway/operator/node status flyout controls | `GatewayStatusContent` | authoritative |
| Tray-menu semantic composition and connection-toggle state | `TrayMenuPresenter` + `ConnectionTogglePresenter` | authoritative |
+| Dashboard link Tailscale revalidation, browser-credential fallback, and fail-closed URL policy | `GatewayDashboardLinkService` (Tailscale revalidation and fallback decisions) + `GatewayDashboardUrlBuilder` (URL scheme and token-fragment policy) | authoritative |
| App-owned non-tray window creation, reuse, focus, theme, and lifetime | `IWindowManager` + `WindowManager`; Workspace is the only application chat host, and the never-activated runtime anchor stays hidden without shell switcher registration | authoritative |
| Standalone compact chat hosting and prewarming | Removed; chat entry points use Workspace, with no hidden replacement window during background startup | closed |
| Composer session picker and compact-host layout mode | Removed, including the picker-only `IsVisibleInChatPicker` helper; non-picker session filters remain. Workspace owns session selection, while actual-width observation retains responsive model/reasoning controls and transcript geometry | closed |
@@ -1041,6 +1042,7 @@ leading and trailing pipe. Columns, in order:
| app-window-surface-ownership-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | concrete non-tray window fields, constructors, show/hide/focus/theme/close mechanics, and window event lifetime | IWindowManager + WindowManager | interface forwarding, immutable request construction, route and policy callbacks, and setup restart dialog policy only | App cannot regain a parallel Settings, Workspace, status, setup, canvas-request, or runtime-anchor owner, nor revive the retired chat popup | AppSurfaceOwnershipContractTests.App_DelegatesConcreteTrayAndWindowOwnership | source-shape | when App is replaced as the WinUI composition root |
| app-tray-controller | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs | tray icon creation, tray popup coordination, click routing, tooltip and live-toggle refresh, theme, callbacks, and disposal | ITrayController + TrayController | App captures immutable snapshots, implements semantic action callbacks, triggers refresh from authoritative state, preserves startup construction order, and constructs shutdown-plan callbacks | one tray icon and root menu are reused; A1 presenters retain semantics; TrayMenuWindow retains native popup mechanics; callbacks detach and resources dispose once | TrayControllerTests.Dispose_UnsubscribesAndDisposesEachResourceOnce | source-shape | when the WinUI tray surface is replaced |
| app-tray-surface-ownership-closed | closed | src/OpenClaw.Tray.WinUI/App.xaml.cs | concrete tray icon, root menu, weak live-control state, event subscriptions, popup build coordination, and resource disposal | ITrayController + TrayController | immutable snapshot and action callbacks plus state-change triggers only | App cannot regain tray controls or popup lifetime and TrayController cannot duplicate A1 semantic projection or TrayMenuWindow native mechanics | AppSurfaceOwnershipContractTests.App_DelegatesConcreteTrayAndWindowOwnership | source-shape | when the WinUI tray surface is replaced |
+| dashboard-link-policy | authoritative | src/OpenClaw.Tray.WinUI/App.xaml.cs + App.CapabilityHandlers.cs + Pages/ConnectionPage.xaml.cs | duplicated Tailscale revalidation and browser-credential fallback decisions, plus dashboard URL scheme and token-fragment policy | GatewayDashboardLinkService (Tailscale revalidation and fallback decisions) + GatewayDashboardUrlBuilder (URL scheme validation and token-fragment construction) | callers retain UI launch, error, provenance, and MCP response side effects | trusted Tailscale links omit shared credentials; degraded Tailscale revalidation falls back only to an approved shared browser credential and otherwise fails closed; non-Tailscale QR/bootstrap requests preserve the existing token-free dashboard URL | AppRefactorContractTests.DashboardLinkPolicy_StaysDelegatedToFocusedService | source-shape | when App, ConnectionPage, and local MCP no longer own dashboard-link entrypoints |
| native-tool-projector | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | pure native tool identity, allowlisted summaries, bounded redacted structured details, payload extraction, and flattened-history detection/classification/summary | NativeToolProjector | ChatEventMapper and ChatHistoryLoader call the projector; ChatConversationState supplies scoped correlation plans and ChatMetadataStore owns persistence | unknown identities remain truthful Tool; title aliases are strict; preview limits do not truncate the separately bounded full-detail projection; yield continuation input stays suppressed; live/history projection stays consistent | NativeToolProjectorTests.ExtractToolIdentity_TitleRequiresExactTrustedAlias | behavioral | - |
| provider-native-tool-projection-closed | closed | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | private static copies of native tool identity, display argument, payload, flattened-history projection, and scoped metadata upsert | NativeToolProjector + ChatEventMapper + ChatHistoryLoader + ChatConversationState + ChatMetadataStore | provider forwards typed tool metadata writes while retaining bridge IO, telemetry, and event publication only | provider does not regain native tool JSON projection, identity policy, timeline correlation, or metadata persistence | review-only: pure projection, atomic correlation, and persistence are delegated to focused owners while the provider remains the IO facade | review-only | when OpenClawChatDataProvider is retired |
| chat-conversation-state | authoritative | src/OpenClaw.Tray.WinUI/Chat/OpenClawChatDataProvider.cs | provider-owned runtime gate and cross-domain state transactions | ChatConversationState | sole lock, timeline and entry metadata, connection/disposal flags, and typed orchestration across lock-free substates; provider supplies bridge context and coordinates IO, telemetry, and events | one authoritative lock atomically commits reset, reconnect, dispose, queue, history, and event transitions without duplicate shared versions | ChatRuntimeOwnershipContractTests.Root_CoordinatesCrossDomainCommitsUnderSoleGate | source-shape | when the chat runtime is replaced by a different atomic transaction boundary |
diff --git a/docs/CONNECTION_ARCHITECTURE.md b/docs/CONNECTION_ARCHITECTURE.md
index fb8e883f06..8a7cf90bae 100644
--- a/docs/CONNECTION_ARCHITECTURE.md
+++ b/docs/CONNECTION_ARCHITECTURE.md
@@ -824,6 +824,24 @@ Many gateway records may be saved, but only `ActiveId` in `gateways.json` is the
## Credential precedence
+### Tailscale dashboard auth upgrade
+
+`GatewayConnectionManager` serializes enablement and dashboard revalidation with
+gateway transitions. Both use `GatewayTailscaleAuthUpgradeService` and the same
+live ingress verifier. Enablement requires Core-managed foreground Serve before
+dispatching the hash-conditional auth-only patch. It records new trust only after
+confirmed patch acceptance, not before dispatch or after an unknown outcome.
+The marker is not a readiness claim. `GatewayDashboardLinkService` still verifies
+applied config and live ingress before omitting a browser credential. See the
+[supported topology and retry contract](WSL_GATEWAY_ADMIN.md#upgrade-dashboard-authentication-on-an-existing-gateway).
+
+`app.dashboard.url` retains the selected credential's `credentialSource` as
+provenance, while `usesSharedGatewayToken` reports the emitted link's
+`BrowserCredentialIncluded`. Verified Tailscale identity can therefore report a
+shared-token source with `usesSharedGatewayToken=false`. Shared fallback reports
+true; bootstrap-only links retain bootstrap provenance without exporting that
+credential. `hasTokenQuery` describes the query only, not a token in the fragment.
+
### Native onboarding connection boundary
`SetupNativeConnectionPage` retains an immutable `SetupNativeConnectionRequest`.
diff --git a/docs/WSL_GATEWAY_ADMIN.md b/docs/WSL_GATEWAY_ADMIN.md
index 36eefaa93d..390b264710 100644
--- a/docs/WSL_GATEWAY_ADMIN.md
+++ b/docs/WSL_GATEWAY_ADMIN.md
@@ -120,7 +120,40 @@ wsl.exe -d OpenClawGateway --user openclaw -- bash -lc "systemctl --user status
The generated WSL distro is Ubuntu 24.04 (noble). Tailscale Serve setup requires that exact generated distro and rejects another `BaseDistro` before replacing an existing gateway. Setup installs Tailscale from its signed stable APT repository rather than executing the mutable `install.sh` bootstrap script as root.
-Tailscale Serve preserves Companion token and device authentication by default (`gateway.auth.allowTailscale=false`). Setup runs `tailscale up`, Serve, reset, logout, and daemon management as root; the `openclaw` account is never made a Tailscale operator. Tailscale's LocalAPI permits read-only operations, such as identity lookup, to local unprivileged clients while reserving mutation for root or an explicitly configured operator. In the setup review, **Trust Tailscale identities for gateway authentication** is an explicit opt-in; when enabled, verified Tailscale identity headers and tailnet ACLs become part of the gateway access-control boundary. Token and device credentials remain available for Companion pairing and compatibility. Do not enable Funnel for this generated gateway: this workflow supports private tailnet Serve only.
+Tailscale Serve preserves Companion token and device authentication by default (`gateway.auth.allowTailscale=false`). Setup runs `tailscale up`, Serve, reset, logout, and daemon management as root; the `openclaw` account is never made a Tailscale operator. Tailscale's LocalAPI permits read-only operations, such as identity lookup, to local unprivileged clients while reserving mutation for root or an explicitly configured operator. In the setup review, **Trust Tailscale identities for gateway authentication** is an explicit opt-in that writes the auth setting and records consent. Consent alone does not establish working identity authentication: the setup-generated background Serve route is not Core-managed identity ingress. Token and device credentials remain available for Companion pairing and compatibility. Do not enable Funnel for this generated gateway: this workflow supports private tailnet Serve only.
+
+### Upgrade dashboard authentication on an existing gateway
+
+In Connection, select the managed Tailscale gateway, connect with
+`operator.admin`, then choose **Use Tailscale identity for dashboard** from its
+saved-row menu and confirm. This auth-only action requires
+`gateway.tailscale.mode="serve"` and verified Core-owned foreground Serve ingress.
+It reads configuration and checks ingress before changing either Core or local
+trust. Missing or unavailable ingress returns a not-ready message.
+
+The default setup topology has `gateway.tailscale.mode="off"` and root-owned
+`tailscale serve --bg`. It is unsupported by this action, even if Serve forwards
+HTTPS successfully. Ask the gateway administrator to review the installed Core
+version and deployment. The action does not migrate the distro, switch Serve
+ownership, restart services, or change token/device credentials. Do not toggle
+the mode alone and assume that proves compatible ingress.
+
+On supported ingress, the action sends only
+`{"gateway":{"auth":{"allowTailscale":true}}}` with the fresh Core config hash.
+A new local `TrustTailscaleAuth` marker is saved only after Core confirms patch
+acceptance. The success message reports acceptance, not completed asynchronous
+application. Dashboard links separately verify matching applied configuration
+and live ingress before omitting the browser token.
+
+A rejected, timed-out, lost, or canceled response does not create new trust.
+Reconnect and repeat the same action; it remains available after registry reload,
+and its minimal patch is idempotent even if Core accepted the earlier request.
+Cancellation during dispatch waits for the bounded request to finish before
+returning, without saving new trust. A local save failure restores the in-memory
+marker and leaves the same retry available. Existing true consent is preserved
+on ambiguous failures; only authoritative applied config revocation clears it.
+When live identity cannot be verified, links use an independently approved shared
+browser credential or fail closed if none is available.
## Use root instead of sudo
diff --git a/src/OpenClaw.Connection/GatewayConnectionManager.cs b/src/OpenClaw.Connection/GatewayConnectionManager.cs
index 22768dc7a4..a5708c1cca 100644
--- a/src/OpenClaw.Connection/GatewayConnectionManager.cs
+++ b/src/OpenClaw.Connection/GatewayConnectionManager.cs
@@ -57,6 +57,7 @@ public sealed class GatewayConnectionManager :
private readonly ICredentialResolver _credentialResolver;
private readonly IGatewayClientFactory _clientFactory;
private readonly GatewayRegistry _registry;
+ private readonly IGatewayTailscaleAuthLiveVerifier _tailscaleAuthLiveVerifier;
private readonly IOpenClawLogger _logger;
private readonly INativeGatewayRuntime? _nativeGatewayRuntime;
private GatewayRecord? _nativeGatewayRecord;
@@ -142,6 +143,8 @@ public GatewayConnectionManager(
_clientFactory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory));
_registry = registry ?? throw new ArgumentNullException(nameof(registry));
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
+ _tailscaleAuthLiveVerifier = new GatewayTailscaleAuthLiveVerifier(
+ new WslExeCommandRunner(_logger));
_nativeGatewayRuntime = nativeGatewayRuntime;
_identityStore = identityStore;
_nodeConnector = nodeConnector;
@@ -216,6 +219,76 @@ public GatewayConnectionManager(
public IOperatorGatewayClient? OperatorClient => _activeLifecycle?.DataClient;
/// Internal access to the concrete client for auto-approve and other manager-internal operations.
internal OpenClawGatewayClient? ConcreteOperatorClient => _activeLifecycle?.DataClient;
+
+ public async Task EnableTailscaleDashboardAuthAsync(
+ string gatewayId,
+ CancellationToken cancellationToken = default)
+ {
+ await _transitionSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ GatewayTailscaleAuthUpgradeResult result;
+ var client = OperatorClient;
+ if (!string.Equals(_activeGatewayRecordId, gatewayId, StringComparison.Ordinal))
+ {
+ result = new(GatewayTailscaleAuthUpgradeOutcome.NotActive);
+ }
+ else if (client is null)
+ {
+ result = new(GatewayTailscaleAuthUpgradeOutcome.NotConnected);
+ }
+ else
+ {
+ var service = new GatewayTailscaleAuthUpgradeService(
+ _registry,
+ _tailscaleAuthLiveVerifier);
+ result = await service.EnableAsync(
+ gatewayId,
+ new GatewayTailscaleAuthConfigClientAdapter(client),
+ cancellationToken)
+ .ConfigureAwait(false);
+ }
+
+ _diagnostics.Record(
+ "tailscale-auth",
+ $"Dashboard auth upgrade: {result.Outcome}",
+ result.Error);
+ return result;
+ }
+ finally
+ {
+ _transitionSemaphore.Release();
+ }
+ }
+
+ public async Task RevalidateTailscaleDashboardAuthAsync(
+ string gatewayId,
+ CancellationToken cancellationToken = default)
+ {
+ await _transitionSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false);
+ try
+ {
+ if (!string.Equals(_activeGatewayRecordId, gatewayId, StringComparison.Ordinal))
+ return false;
+
+ var client = OperatorClient;
+ if (client is null)
+ return false;
+
+ var service = new GatewayTailscaleAuthUpgradeService(
+ _registry,
+ _tailscaleAuthLiveVerifier);
+ return await service.RevalidateAsync(
+ gatewayId,
+ new GatewayTailscaleAuthConfigClientAdapter(client),
+ cancellationToken)
+ .ConfigureAwait(false);
+ }
+ finally
+ {
+ _transitionSemaphore.Release();
+ }
+ }
public ConnectionDiagnostics Diagnostics => _diagnostics;
internal async Task RequireNativeSetupClientAsync(
diff --git a/src/OpenClaw.Connection/GatewayRecord.cs b/src/OpenClaw.Connection/GatewayRecord.cs
index de142fc582..6fb9a7a7a5 100644
--- a/src/OpenClaw.Connection/GatewayRecord.cs
+++ b/src/OpenClaw.Connection/GatewayRecord.cs
@@ -33,6 +33,12 @@ public sealed record GatewayRecord
/// WSL distro name for gateway records provisioned by SetupEngine.
public string? SetupManagedDistroName { get; init; }
+ ///
+ /// Explicit setup consent or a confirmed, accepted auth upgrade for this managed
+ /// gateway. Dashboard access still requires applied config and live ingress verification.
+ ///
+ public bool TrustTailscaleAuth { get; init; }
+
///
/// Installed MSIX package family owned by the native gateway runtime. Native gateways
/// are non-isolated and must never also carry a setup-managed WSL distro marker.
@@ -121,6 +127,7 @@ rebuilt.SshTunnel is null &&
// Migrate legacy "Local ()" ownership to the explicit durable marker.
SetupManagedDistroName = managedDistroName,
RequiresV2Signature = rebuilt.RequiresV2Signature || existing.RequiresV2Signature,
+ TrustTailscaleAuth = rebuilt.TrustTailscaleAuth || existing.TrustTailscaleAuth,
};
}
else if (existingManagedDistroName is not null)
@@ -130,6 +137,7 @@ rebuilt.SshTunnel is null &&
IsLocal = OpenClaw.Shared.LocalGatewayUrlClassifier.IsLocalGatewayUrl(rebuilt.Url),
SetupManagedDistroName = null,
RequiresV2Signature = false,
+ TrustTailscaleAuth = false,
FriendlyName = ParseLegacyManagedDistroName(result.FriendlyName) is not null
? null
: result.FriendlyName,
diff --git a/src/OpenClaw.Connection/GatewayRegistry.cs b/src/OpenClaw.Connection/GatewayRegistry.cs
index 77cc95d789..1e73e072ea 100644
--- a/src/OpenClaw.Connection/GatewayRegistry.cs
+++ b/src/OpenClaw.Connection/GatewayRegistry.cs
@@ -528,6 +528,9 @@ private static bool GatewayUrlsEquivalent(string? left, string? right)
return false;
}
+ if (AreEquivalentRootUrls(normalizedLeft, leftUri, normalizedRight, rightUri))
+ return true;
+
return string.Equals(leftUri.Scheme, rightUri.Scheme, StringComparison.OrdinalIgnoreCase) &&
leftUri.Port == rightUri.Port &&
IsLoopbackHost(leftUri.Host) &&
@@ -535,6 +538,39 @@ private static bool GatewayUrlsEquivalent(string? left, string? right)
string.Equals(leftUri.PathAndQuery, rightUri.PathAndQuery, StringComparison.Ordinal);
}
+ private static bool AreEquivalentRootUrls(string leftUrl, Uri leftUri, string rightUrl, Uri rightUri) =>
+ string.Equals(leftUri.Scheme, rightUri.Scheme, StringComparison.OrdinalIgnoreCase) &&
+ string.Equals(leftUri.Host, rightUri.Host, StringComparison.OrdinalIgnoreCase) &&
+ leftUri.Port == rightUri.Port &&
+ string.Equals(leftUri.AbsolutePath, "/", StringComparison.Ordinal) &&
+ string.Equals(rightUri.AbsolutePath, "/", StringComparison.Ordinal) &&
+ HasRootPathSpelling(leftUrl) &&
+ HasRootPathSpelling(rightUrl) &&
+ string.Equals(GetQueryAndFragment(leftUrl), GetQueryAndFragment(rightUrl), StringComparison.Ordinal);
+
+ private static bool HasRootPathSpelling(string url)
+ {
+ var schemeSeparator = url.IndexOf("://", StringComparison.Ordinal);
+ if (schemeSeparator < 0)
+ return false;
+
+ var authorityStart = schemeSeparator + 3;
+ var pathOrSuffixStart = url.IndexOfAny(['/', '?', '#'], authorityStart);
+ if (pathOrSuffixStart < 0 || url[pathOrSuffixStart] != '/')
+ return true;
+
+ var suffixStart = url.IndexOfAny(['?', '#'], pathOrSuffixStart);
+ var pathEnd = suffixStart < 0 ? url.Length : suffixStart;
+ return pathEnd == pathOrSuffixStart + 1;
+ }
+
+ private static string GetQueryAndFragment(string url)
+ {
+ var authorityStart = url.IndexOf("://", StringComparison.Ordinal) + 3;
+ var suffixStart = url.IndexOfAny(['?', '#'], authorityStart);
+ return suffixStart < 0 ? string.Empty : url[suffixStart..];
+ }
+
private static bool IsLoopbackHost(string host) =>
host.Equals("localhost", StringComparison.OrdinalIgnoreCase) ||
host.Equals("127.0.0.1", StringComparison.OrdinalIgnoreCase) ||
diff --git a/src/OpenClaw.Connection/GatewayTailscaleAuthUpgrade.cs b/src/OpenClaw.Connection/GatewayTailscaleAuthUpgrade.cs
new file mode 100644
index 0000000000..728f85bde3
--- /dev/null
+++ b/src/OpenClaw.Connection/GatewayTailscaleAuthUpgrade.cs
@@ -0,0 +1,720 @@
+using System.Globalization;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using OpenClaw.Shared;
+
+namespace OpenClaw.Connection;
+
+// Coordinates explicit Tailscale-auth upgrades for eligible managed Gateways.
+// Usage:
+// var result = await upgrade.EnableAsync(gatewayId, client, cancellationToken);
+// var trusted = await upgrade.RevalidateAsync(gatewayId, client, cancellationToken);
+/// Outcomes from a managed Gateway Tailscale-auth upgrade.
+public enum GatewayTailscaleAuthUpgradeOutcome
+{
+ Succeeded,
+ AlreadyEnabled,
+ Ineligible,
+ NotActive,
+ NotConnected,
+ MissingConfigScope,
+ ConfigUnavailable,
+ PatchRejected,
+ PersistenceFailed,
+ UnsupportedTopology,
+ IngressNotReady,
+}
+
+/// The outcome and optional diagnostic from a Tailscale-auth upgrade attempt.
+public sealed record GatewayTailscaleAuthUpgradeResult(
+ GatewayTailscaleAuthUpgradeOutcome Outcome,
+ string? Error = null)
+{
+ /// Whether the upgrade succeeded or the requested trust was already enabled.
+ public bool IsSuccess => Outcome is
+ GatewayTailscaleAuthUpgradeOutcome.Succeeded or
+ GatewayTailscaleAuthUpgradeOutcome.AlreadyEnabled;
+}
+
+/// Eligibility rules for offering a managed Gateway Tailscale-auth upgrade.
+public static class GatewayTailscaleAuthUpgradePolicy
+{
+ /// Whether the record identifies a locally managed Tailscale Gateway.
+ public static bool IsEligible(GatewayRecord? record)
+ {
+ if (record is null ||
+ !record.IsLocal ||
+ record.SshTunnel is not null ||
+ GatewayRecordEditing.ResolveManagedDistroName(record) is null)
+ {
+ return false;
+ }
+
+ return GatewayTopologyClassifier.Classify(record.Url, useSshTunnel: false).DetectedKind ==
+ GatewayKind.Tailscale;
+ }
+
+ /// Whether the upgrade can be offered without replacing existing trust.
+ public static bool CanOffer(GatewayRecord? record) =>
+ record?.TrustTailscaleAuth != true && IsEligible(record);
+}
+
+internal interface IGatewayTailscaleAuthConfigClient
+{
+ IReadOnlyList GrantedOperatorScopes { get; }
+ bool IsConnectedToGateway { get; }
+ long? SessionMutationConnectionEpoch { get; }
+ Task RequestConfigDetailedAsync(int timeoutMs = 15000);
+ Task PatchConfigOnConnectionAsync(
+ JsonElement fullConfig,
+ string? baseHash,
+ long connectionEpoch,
+ int timeoutMs = 15000);
+}
+
+internal sealed class GatewayTailscaleAuthConfigClientAdapter(IOperatorGatewayClient client)
+ : IGatewayTailscaleAuthConfigClient
+{
+ public IReadOnlyList GrantedOperatorScopes => client.GrantedOperatorScopes;
+ public bool IsConnectedToGateway => client.IsConnectedToGateway;
+ public long? SessionMutationConnectionEpoch => client.SessionMutationConnectionEpoch;
+ public Task RequestConfigDetailedAsync(int timeoutMs = 15000) =>
+ client.RequestConfigDetailedAsync(timeoutMs);
+ public Task PatchConfigOnConnectionAsync(
+ JsonElement fullConfig,
+ string? baseHash,
+ long connectionEpoch,
+ int timeoutMs = 15000) =>
+ client.PatchConfigOnConnectionAsync(fullConfig, baseHash, connectionEpoch, timeoutMs);
+}
+
+internal enum GatewayTailscaleAuthLiveState
+{
+ Ready,
+ NotReady,
+ Unavailable,
+}
+
+internal interface IGatewayTailscaleAuthLiveVerifier
+{
+ Task VerifyAsync(
+ GatewayRecord record,
+ int gatewayPort,
+ CancellationToken cancellationToken);
+}
+
+internal sealed class GatewayTailscaleAuthLiveVerifier : IGatewayTailscaleAuthLiveVerifier
+{
+ private static readonly IReadOnlyList StatusCommand =
+ ["/usr/bin/tailscale", "status", "--json"];
+ private static readonly IReadOnlyList ServeStatusCommand =
+ ["/usr/bin/tailscale", "serve", "status", "--json"];
+ private static readonly IReadOnlyList GatewayProcessCommand =
+ ["/usr/bin/systemctl", "--user", "show", "openclaw-gateway", "-p", "MainPID", "--value"];
+
+ private readonly IWslCommandRunner _commandRunner;
+ private readonly TimeSpan? _timeout;
+
+ public GatewayTailscaleAuthLiveVerifier(
+ IWslCommandRunner commandRunner,
+ TimeSpan? timeout = null)
+ {
+ _commandRunner = commandRunner ?? throw new ArgumentNullException(nameof(commandRunner));
+ _timeout = timeout;
+ }
+
+ public async Task VerifyAsync(
+ GatewayRecord record,
+ int gatewayPort,
+ CancellationToken cancellationToken)
+ {
+ if (GatewayRecordEditing.ResolveManagedDistroName(record) is not { } distroName ||
+ !Uri.TryCreate(record.Url, UriKind.Absolute, out var gatewayUri) ||
+ gatewayPort is <= 0 or > 65535)
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
+ if (_timeout is { } probeTimeout)
+ timeout.CancelAfter(probeTimeout);
+
+ WslCommandResult statusResult;
+ try
+ {
+ statusResult = await _commandRunner.RunAsync(
+ BuildRootProbeArguments(distroName, StatusCommand),
+ timeout.Token)
+ .ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+
+ if (!statusResult.Success)
+ return GatewayTailscaleAuthLiveState.Unavailable;
+
+ string dnsName;
+ try
+ {
+ using var status = JsonDocument.Parse(statusResult.StandardOutput);
+ var root = status.RootElement;
+ var backendRunning =
+ root.ValueKind == JsonValueKind.Object &&
+ root.TryGetProperty("BackendState", out var backendState) &&
+ backendState.ValueKind == JsonValueKind.String &&
+ string.Equals(backendState.GetString(), "Running", StringComparison.Ordinal);
+ dnsName =
+ root.ValueKind == JsonValueKind.Object &&
+ root.TryGetProperty("Self", out var self) &&
+ self.ValueKind == JsonValueKind.Object &&
+ self.TryGetProperty("DNSName", out var dnsNameElement) &&
+ dnsNameElement.ValueKind == JsonValueKind.String &&
+ !string.IsNullOrWhiteSpace(dnsNameElement.GetString())
+ ? dnsNameElement.GetString()!.Trim().TrimEnd('.')
+ : string.Empty;
+
+ if (!backendRunning ||
+ !string.Equals(dnsName, gatewayUri.Host.TrimEnd('.'), StringComparison.OrdinalIgnoreCase))
+ {
+ return GatewayTailscaleAuthLiveState.NotReady;
+ }
+ }
+ catch (JsonException)
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+
+ WslCommandResult serveResult;
+ try
+ {
+ serveResult = await _commandRunner.RunAsync(
+ BuildRootProbeArguments(distroName, ServeStatusCommand),
+ timeout.Token)
+ .ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+
+ if (!serveResult.Success ||
+ !TailscaleServeStatusPolicy.TryParse(
+ serveResult.StandardOutput,
+ gatewayPort,
+ gatewayUri,
+ out var serveStatus))
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+
+ if (serveStatus.FunnelEnabled)
+ return GatewayTailscaleAuthLiveState.NotReady;
+ if (serveStatus.ForegroundProxyPort is not { } managedIngressPort)
+ return GatewayTailscaleAuthLiveState.NotReady;
+
+ WslCommandResult ownershipResult;
+ try
+ {
+ var serviceBefore = await _commandRunner.RunInDistroAsync(
+ distroName, GatewayProcessCommand, timeout.Token)
+ .ConfigureAwait(false);
+ if (!serviceBefore.Success ||
+ !int.TryParse(serviceBefore.StandardOutput.Trim(), NumberStyles.None,
+ CultureInfo.InvariantCulture, out var gatewayProcessId) || gatewayProcessId <= 0)
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+ var ownershipScript = BuildManagedIngressOwnershipScript(
+ gatewayPort,
+ managedIngressPort,
+ gatewayProcessId)
+ .Replace("\r", string.Empty, StringComparison.Ordinal);
+ ownershipResult = await _commandRunner.RunWithStandardInputAsync(
+ BuildRootProbeArguments(distroName, ["/bin/bash", "-s"]),
+ ownershipScript,
+ timeout.Token)
+ .ConfigureAwait(false);
+ var serviceAfter = await _commandRunner.RunInDistroAsync(
+ distroName, GatewayProcessCommand, timeout.Token)
+ .ConfigureAwait(false);
+ if (!serviceAfter.Success ||
+ !int.TryParse(serviceAfter.StandardOutput.Trim(), NumberStyles.None,
+ CultureInfo.InvariantCulture, out var gatewayProcessIdAfter) ||
+ gatewayProcessIdAfter != gatewayProcessId)
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch
+ {
+ return GatewayTailscaleAuthLiveState.Unavailable;
+ }
+
+ if (!ownershipResult.Success)
+ return GatewayTailscaleAuthLiveState.Unavailable;
+
+ return ownershipResult.StandardOutput.Trim() switch
+ {
+ "owned" => GatewayTailscaleAuthLiveState.Ready,
+ "not-owned" => GatewayTailscaleAuthLiveState.NotReady,
+ _ => GatewayTailscaleAuthLiveState.Unavailable,
+ };
+ }
+
+ private static IReadOnlyList BuildRootProbeArguments(
+ string distroName,
+ IReadOnlyList command) =>
+ ["-d", distroName, "--user", "root", "--", .. command];
+
+ private static string BuildManagedIngressOwnershipScript(
+ int gatewayPort,
+ int managedIngressPort,
+ int gatewayProcessId)
+ {
+ var script = $$"""
+ pid_before={{gatewayProcessId.ToString(CultureInfo.InvariantCulture)}}
+ main_cgroup=$(/usr/bin/awk -F: '$1 == "0" { print $3 }' "/proc/$pid_before/cgroup" 2>/dev/null)
+ main_start_before=$(/usr/bin/awk '{ print $22 }' "/proc/$pid_before/stat" 2>/dev/null)
+ main_exe=$(/usr/bin/readlink -f "/proc/$pid_before/exe" 2>/dev/null)
+ test -n "$main_cgroup" && test -n "$main_start_before" && test -n "$main_exe" || { /usr/bin/printf unavailable; exit 0; }
+ listener_pattern='(^|[[:space:]])127\.0\.0\.1:({{gatewayPort}}|{{managedIngressPort}})([[:space:]]|$)'
+ listeners_raw_before=$(/usr/bin/ss -H -ltnp 2>/dev/null) || { /usr/bin/printf unavailable; exit 0; }
+ listeners_before=$(/usr/bin/printf '%s\n' "$listeners_raw_before" | /usr/bin/grep -E "$listener_pattern" || true)
+ candidate_count=0
+ matched_pid=''
+ matched_start=''
+ matched_parent=''
+ matched_parent_start=''
+ matched_worker=''
+ matched_worker_start=''
+ for proc in /proc/[0-9]*; do
+ candidate_pid=${proc##*/}
+ candidate_exe=$(/usr/bin/readlink -f "$proc/exe" 2>/dev/null)
+ candidate_cgroup=$(/usr/bin/awk -F: '$1 == "0" { print $3 }' "$proc/cgroup" 2>/dev/null)
+ candidate_start=$(/usr/bin/awk '{ print $22 }' "$proc/stat" 2>/dev/null)
+ candidate_parent=$(/usr/bin/awk '/^PPid:/ { print $2 }' "$proc/status" 2>/dev/null)
+ test "$candidate_exe" = /usr/bin/tailscale && test "$candidate_cgroup" = "$main_cgroup" && test -n "$candidate_start" || continue
+ unset argv
+ declare -a argv=()
+ while IFS= read -r -d '' arg; do argv+=("$arg"); done < "$proc/cmdline" 2>/dev/null
+ test "${#argv[@]}" -eq 5 || continue
+ test "${argv[0]}" = /usr/bin/tailscale && test "${argv[1]}" = serve && test "${argv[2]}" = --yes && test "${argv[3]}" = --bg=false && test "${argv[4]}" = {{managedIngressPort}} || continue
+ route_owner=$candidate_parent
+ parent_exe=$(/usr/bin/readlink -f "/proc/$candidate_parent/exe" 2>/dev/null)
+ if test "$parent_exe" = /usr/bin/sudo; then
+ unset sudo_argv
+ declare -a sudo_argv=()
+ while IFS= read -r -d '' arg; do sudo_argv+=("$arg"); done < "/proc/$candidate_parent/cmdline" 2>/dev/null
+ test "${#sudo_argv[@]}" -eq 7 && test "${sudo_argv[0]}" = sudo && test "${sudo_argv[1]}" = -n && test "${sudo_argv[2]}" = /usr/bin/tailscale && test "${sudo_argv[3]}" = serve && test "${sudo_argv[4]}" = --yes && test "${sudo_argv[5]}" = --bg=false && test "${sudo_argv[6]}" = {{managedIngressPort}} || continue
+ parent_cgroup=$(/usr/bin/awk -F: '$1 == "0" { print $3 }' "/proc/$candidate_parent/cgroup" 2>/dev/null)
+ test "$parent_cgroup" = "$main_cgroup" || continue
+ route_owner=$(/usr/bin/awk '/^PPid:/ { print $2 }' "/proc/$candidate_parent/status" 2>/dev/null)
+ fi
+ worker_exe=$(/usr/bin/readlink -f "/proc/$route_owner/exe" 2>/dev/null)
+ worker_cgroup=$(/usr/bin/awk -F: '$1 == "0" { print $3 }' "/proc/$route_owner/cgroup" 2>/dev/null)
+ worker_parent=$(/usr/bin/awk '/^PPid:/ { print $2 }' "/proc/$route_owner/status" 2>/dev/null)
+ worker_start=$(/usr/bin/awk '{ print $22 }' "/proc/$route_owner/stat" 2>/dev/null)
+ test "$worker_exe" = "$main_exe" && test "$worker_cgroup" = "$main_cgroup" && test "$worker_parent" = "$pid_before" && test -n "$worker_start" || continue
+ unset worker_argv
+ declare -a worker_argv=()
+ while IFS= read -r -d '' arg; do worker_argv+=("$arg"); done < "/proc/$route_owner/cmdline" 2>/dev/null
+ test "${#worker_argv[@]}" -ge 4 || continue
+ worker_script_index=$((${#worker_argv[@]} - 3))
+ case "${worker_argv[$worker_script_index]}" in */dist/infra/tailscale-route-owner.worker.js) ;; *) continue;; esac
+ test "${worker_argv[$((worker_script_index + 1))]}" = --openclaw-tailscale-route-owner || continue
+ expected_direct='{"argv":["/usr/bin/tailscale","serve","--yes","--bg=false","{{managedIngressPort}}"]}'
+ expected_sudo='{"argv":["sudo","-n","/usr/bin/tailscale","serve","--yes","--bg=false","{{managedIngressPort}}"]}'
+ test "${worker_argv[$((worker_script_index + 2))]}" = "$expected_direct" || test "${worker_argv[$((worker_script_index + 2))]}" = "$expected_sudo" || continue
+ candidate_count=$((candidate_count + 1))
+ matched_pid=$candidate_pid
+ matched_start=$candidate_start
+ matched_parent=$candidate_parent
+ matched_parent_start=$(/usr/bin/awk '{ print $22 }' "/proc/$candidate_parent/stat" 2>/dev/null)
+ matched_worker=$route_owner
+ matched_worker_start=$worker_start
+ done
+ main_start_after=$(/usr/bin/awk '{ print $22 }' "/proc/$pid_before/stat" 2>/dev/null)
+ main_exe_after=$(/usr/bin/readlink -f "/proc/$pid_before/exe" 2>/dev/null)
+ listeners_raw_after=$(/usr/bin/ss -H -ltnp 2>/dev/null) || { /usr/bin/printf unavailable; exit 0; }
+ listeners_after=$(/usr/bin/printf '%s\n' "$listeners_raw_after" | /usr/bin/grep -E "$listener_pattern" || true)
+ test "$main_start_before" = "$main_start_after" && test "$main_exe" = "$main_exe_after" && test "$listeners_before" = "$listeners_after" || { /usr/bin/printf unavailable; exit 0; }
+ gateway_owner=$(/usr/bin/printf '%s\n' "$listeners_after" | /usr/bin/grep -E '(^|[[:space:]])127\.0\.0\.1:{{gatewayPort}}([[:space:]]|$)' | /usr/bin/grep -F "pid=$pid_before,")
+ ingress_owner=$(/usr/bin/printf '%s\n' "$listeners_after" | /usr/bin/grep -E '(^|[[:space:]])127\.0\.0\.1:{{managedIngressPort}}([[:space:]]|$)' | /usr/bin/grep -F "pid=$pid_before,")
+ candidate_start_after=$(/usr/bin/awk '{ print $22 }' "/proc/$matched_pid/stat" 2>/dev/null)
+ candidate_parent_after=$(/usr/bin/awk '/^PPid:/ { print $2 }' "/proc/$matched_pid/status" 2>/dev/null)
+ parent_start_after=$(/usr/bin/awk '{ print $22 }' "/proc/$matched_parent/stat" 2>/dev/null)
+ worker_start_after=$(/usr/bin/awk '{ print $22 }' "/proc/$matched_worker/stat" 2>/dev/null)
+ worker_parent_after=$(/usr/bin/awk '/^PPid:/ { print $2 }' "/proc/$matched_worker/status" 2>/dev/null)
+ if test -n "$gateway_owner" && test -n "$ingress_owner" && test "$candidate_count" -eq 1 && test "$matched_start" = "$candidate_start_after" && test "$matched_parent" = "$candidate_parent_after" && test "$matched_parent_start" = "$parent_start_after" && test "$matched_worker_start" = "$worker_start_after" && test "$worker_parent_after" = "$pid_before"; then
+ /usr/bin/printf owned
+ else
+ /usr/bin/printf not-owned
+ fi
+ """;
+ return script;
+ }
+}
+
+/// Applies and revalidates Tailscale-auth trust for the active managed Gateway.
+internal sealed class GatewayTailscaleAuthUpgradeService
+{
+ private static readonly TimeSpan ConfigTimeout = TimeSpan.FromSeconds(15);
+ private readonly GatewayRegistry _registry;
+ private readonly IGatewayTailscaleAuthLiveVerifier? _liveVerifier;
+
+ public GatewayTailscaleAuthUpgradeService(GatewayRegistry registry)
+ : this(registry, liveVerifier: null)
+ {
+ }
+
+ public GatewayTailscaleAuthUpgradeService(
+ GatewayRegistry registry,
+ IGatewayTailscaleAuthLiveVerifier? liveVerifier)
+ {
+ _registry = registry ?? throw new ArgumentNullException(nameof(registry));
+ _liveVerifier = liveVerifier;
+ }
+
+ /// Verifies managed ingress, requests Tailscale auth, and persists accepted trust.
+ /// The active Gateway to upgrade.
+ /// The connection-bound Gateway config client.
+ /// Requests cancellation of the upgrade flow.
+ /// The upgrade outcome.
+ public async Task EnableAsync(
+ string gatewayId,
+ IGatewayTailscaleAuthConfigClient client,
+ CancellationToken cancellationToken)
+ {
+ var record = _registry.GetById(gatewayId);
+ if (!GatewayTailscaleAuthUpgradePolicy.IsEligible(record))
+ return new(GatewayTailscaleAuthUpgradeOutcome.Ineligible);
+
+ if (!string.Equals(_registry.ActiveGatewayId, gatewayId, StringComparison.Ordinal))
+ return new(GatewayTailscaleAuthUpgradeOutcome.NotActive);
+
+ if (!client.IsConnectedToGateway)
+ return new(GatewayTailscaleAuthUpgradeOutcome.NotConnected);
+
+ if (client.SessionMutationConnectionEpoch is not { } connectionEpoch)
+ return new(GatewayTailscaleAuthUpgradeOutcome.ConfigUnavailable, "Gateway connection epoch is unavailable.");
+
+ if (!OperatorScopeHelper.CanReadConfig(client.GrantedOperatorScopes) ||
+ !OperatorScopeHelper.CanWriteConfig(client.GrantedOperatorScopes))
+ {
+ return new(GatewayTailscaleAuthUpgradeOutcome.MissingConfigScope);
+ }
+
+ ConfigSnapshot snapshot;
+ try
+ {
+ snapshot = await ReadConfigAsync(client, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ return new(GatewayTailscaleAuthUpgradeOutcome.ConfigUnavailable, ex.Message);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (!UsesManagedTailscaleServe(snapshot.Root))
+ return new(GatewayTailscaleAuthUpgradeOutcome.UnsupportedTopology);
+
+ if (_liveVerifier is null || !TryGetGatewayPort(snapshot.Root, out var gatewayPort))
+ return new(GatewayTailscaleAuthUpgradeOutcome.IngressNotReady);
+
+ try
+ {
+ if (await _liveVerifier.VerifyAsync(record!, gatewayPort, cancellationToken).ConfigureAwait(false) !=
+ GatewayTailscaleAuthLiveState.Ready)
+ {
+ return new(GatewayTailscaleAuthUpgradeOutcome.IngressNotReady);
+ }
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception ex)
+ {
+ return new(GatewayTailscaleAuthUpgradeOutcome.IngressNotReady, ex.Message);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+
+ if (record!.TrustTailscaleAuth && snapshot.IsApplied && AllowsTailscaleAuth(snapshot.Root))
+ return new(GatewayTailscaleAuthUpgradeOutcome.AlreadyEnabled);
+
+ if (string.IsNullOrWhiteSpace(snapshot.BaseHash))
+ {
+ return new(GatewayTailscaleAuthUpgradeOutcome.ConfigUnavailable, "Config base hash is unavailable.");
+ }
+
+ // Core beta.7 and current main define config.patch as JSON Merge Patch.
+ // Send only the intended leaf: replaying the full snapshot would turn
+ // unrelated null values into deletion markers.
+ var configPatch = CreateAllowTailscalePatch();
+ ConfigPatchResult patch;
+ Task? patchTask = null;
+ try
+ {
+ patchTask = client.PatchConfigOnConnectionAsync(configPatch, snapshot.BaseHash, connectionEpoch);
+ patch = await patchTask.WaitAsync(cancellationToken)
+ .ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ // Dispatch cannot be canceled at the client boundary. Observe its bounded
+ // result before returning so callers never proceed beside an in-flight
+ // mutation. Cancellation does not issue new trust, even if Core accepted
+ // the patch. A later explicit retry safely repeats the idempotent leaf.
+ try
+ {
+ if (patchTask is not null)
+ await patchTask.ConfigureAwait(false);
+ }
+ catch
+ {
+ // A transport failure is ambiguous: Core may have committed.
+ }
+ throw;
+ }
+ catch (Exception ex)
+ {
+ return new(GatewayTailscaleAuthUpgradeOutcome.PatchRejected, ex.Message);
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ if (!patch.Ok)
+ return new(GatewayTailscaleAuthUpgradeOutcome.PatchRejected, patch.Error);
+
+ if (!record.TrustTailscaleAuth)
+ {
+ var changed = false;
+ _registry.Update(gatewayId, current =>
+ {
+ if (!GatewayTailscaleAuthUpgradePolicy.CanOffer(current))
+ return current;
+
+ changed = true;
+ return current with { TrustTailscaleAuth = true };
+ });
+
+ if (!changed)
+ return new(GatewayTailscaleAuthUpgradeOutcome.NotActive);
+
+ try
+ {
+ _registry.Save();
+ }
+ catch (Exception ex)
+ {
+ _registry.Update(gatewayId, current => current with { TrustTailscaleAuth = false });
+ return new(GatewayTailscaleAuthUpgradeOutcome.PersistenceFailed, ex.Message);
+ }
+ }
+
+ // Acceptance is not evidence of asynchronous Core apply or continued ingress
+ // readiness. Dashboard-link creation still performs its live revalidation.
+ return new(GatewayTailscaleAuthUpgradeOutcome.Succeeded);
+ }
+
+ /// Checks whether persisted Tailscale-auth trust still matches Gateway config and ingress.
+ /// The Gateway whose trust is checked.
+ /// The current Gateway config client.
+ /// Cancels config and ingress checks.
+ /// when current config and ingress satisfy the trust policy.
+ public async Task RevalidateAsync(
+ string gatewayId,
+ IGatewayTailscaleAuthConfigClient client,
+ CancellationToken cancellationToken)
+ {
+ var record = _registry.GetById(gatewayId);
+ if (record?.TrustTailscaleAuth != true ||
+ !GatewayTailscaleAuthUpgradePolicy.IsEligible(record) ||
+ !string.Equals(_registry.ActiveGatewayId, gatewayId, StringComparison.Ordinal) ||
+ !client.IsConnectedToGateway ||
+ !OperatorScopeHelper.CanReadConfig(client.GrantedOperatorScopes))
+ {
+ return false;
+ }
+
+ ConfigSnapshot snapshot;
+ try
+ {
+ snapshot = await ReadConfigAsync(client, cancellationToken).ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch
+ {
+ return false;
+ }
+
+ if (!snapshot.IsApplied)
+ return false;
+
+ if (AllowsTailscaleAuth(snapshot.Root))
+ {
+ if (_liveVerifier is null || !TryGetGatewayPort(snapshot.Root, out var gatewayPort))
+ return false;
+
+ try
+ {
+ return await _liveVerifier.VerifyAsync(record, gatewayPort, cancellationToken).ConfigureAwait(false) ==
+ GatewayTailscaleAuthLiveState.Ready;
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+
+ _registry.Update(gatewayId, current => current with { TrustTailscaleAuth = false });
+ try
+ {
+ _registry.Save();
+ }
+ catch
+ {
+ _registry.Update(gatewayId, current => current with { TrustTailscaleAuth = true });
+ }
+ return false;
+ }
+
+ private static async Task ReadConfigAsync(
+ IGatewayTailscaleAuthConfigClient client,
+ CancellationToken cancellationToken)
+ {
+ var timeoutMs = checked((int)ConfigTimeout.TotalMilliseconds);
+ var response = await client.RequestConfigDetailedAsync(timeoutMs)
+ .WaitAsync(cancellationToken)
+ .ConfigureAwait(false);
+ return CaptureSnapshot(response);
+ }
+
+ private static ConfigSnapshot CaptureSnapshot(JsonElement response)
+ {
+ var hasRoot = response.TryGetProperty("sourceConfig", out var root) &&
+ root.ValueKind == JsonValueKind.Object;
+ if (!hasRoot && response.TryGetProperty("resolved", out var resolved) &&
+ resolved.ValueKind == JsonValueKind.Object)
+ {
+ root = resolved;
+ hasRoot = true;
+ }
+
+ if (!hasRoot)
+ throw new InvalidOperationException("Resolved source config is unavailable.");
+ var baseHash = response.TryGetProperty("baseHash", out var baseHashElement) &&
+ baseHashElement.ValueKind == JsonValueKind.String
+ ? baseHashElement.GetString()
+ : response.TryGetProperty("hash", out var hashElement) &&
+ hashElement.ValueKind == JsonValueKind.String
+ ? hashElement.GetString()
+ : null;
+ if (baseHash is null &&
+ response.TryGetProperty("raw", out var rawElement) &&
+ rawElement.ValueKind == JsonValueKind.String &&
+ rawElement.GetString() is { } raw)
+ {
+ baseHash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(raw)));
+ }
+
+ var configRevisionHash = response.TryGetProperty("configRevisionHash", out var revisionElement) &&
+ revisionElement.ValueKind == JsonValueKind.String
+ ? revisionElement.GetString()
+ : null;
+ var appliedConfigHash = response.TryGetProperty("appliedConfigHash", out var appliedElement) &&
+ appliedElement.ValueKind == JsonValueKind.String
+ ? appliedElement.GetString()
+ : null;
+
+ return new(root.Clone(), baseHash, configRevisionHash, appliedConfigHash);
+ }
+
+ private static JsonElement CreateAllowTailscalePatch()
+ {
+ using var document = JsonDocument.Parse("""
+ { "gateway": { "auth": { "allowTailscale": true } } }
+ """);
+ return document.RootElement.Clone();
+ }
+
+ private static bool UsesManagedTailscaleServe(JsonElement config) =>
+ config.ValueKind == JsonValueKind.Object &&
+ config.TryGetProperty("gateway", out var gateway) &&
+ gateway.ValueKind == JsonValueKind.Object &&
+ gateway.TryGetProperty("tailscale", out var tailscale) &&
+ tailscale.ValueKind == JsonValueKind.Object &&
+ tailscale.TryGetProperty("mode", out var mode) &&
+ mode.ValueKind == JsonValueKind.String &&
+ string.Equals(mode.GetString(), "serve", StringComparison.Ordinal);
+
+ private static bool AllowsTailscaleAuth(JsonElement config) =>
+ config.ValueKind == JsonValueKind.Object &&
+ config.TryGetProperty("gateway", out var gateway) &&
+ gateway.ValueKind == JsonValueKind.Object &&
+ gateway.TryGetProperty("auth", out var auth) &&
+ auth.ValueKind == JsonValueKind.Object &&
+ auth.TryGetProperty("allowTailscale", out var allowTailscale) &&
+ allowTailscale.ValueKind is JsonValueKind.True;
+
+ private static bool TryGetGatewayPort(JsonElement config, out int port)
+ {
+ const int defaultGatewayPort = 18789;
+ port = 0;
+ if (config.ValueKind != JsonValueKind.Object ||
+ !config.TryGetProperty("gateway", out var gateway) ||
+ gateway.ValueKind != JsonValueKind.Object)
+ {
+ return false;
+ }
+
+ if (!gateway.TryGetProperty("port", out var gatewayPort))
+ {
+ port = defaultGatewayPort;
+ return true;
+ }
+
+ return gatewayPort.ValueKind == JsonValueKind.Number &&
+ gatewayPort.TryGetInt32(out port) &&
+ port is > 0 and <= 65535;
+ }
+
+ private sealed record ConfigSnapshot(
+ JsonElement Root,
+ string? BaseHash,
+ string? ConfigRevisionHash,
+ string? AppliedConfigHash)
+ {
+ public bool IsApplied =>
+ !string.IsNullOrWhiteSpace(ConfigRevisionHash) &&
+ !string.IsNullOrWhiteSpace(AppliedConfigHash) &&
+ string.Equals(ConfigRevisionHash, AppliedConfigHash, StringComparison.Ordinal);
+ }
+}
diff --git a/src/OpenClaw.Connection/IGatewayConnectionManager.cs b/src/OpenClaw.Connection/IGatewayConnectionManager.cs
index c27a662b50..b1ec966d5c 100644
--- a/src/OpenClaw.Connection/IGatewayConnectionManager.cs
+++ b/src/OpenClaw.Connection/IGatewayConnectionManager.cs
@@ -39,6 +39,15 @@ Task ConnectAsync(string? gatewayId, CancellationToken cancellationToken)
Task RestartSshTunnelAsync(CancellationToken cancellationToken = default) =>
Task.FromResult(false);
Task SwitchGatewayAsync(string gatewayId);
+ Task EnableTailscaleDashboardAuthAsync(
+ string gatewayId,
+ CancellationToken cancellationToken = default) =>
+ Task.FromResult(new GatewayTailscaleAuthUpgradeResult(
+ GatewayTailscaleAuthUpgradeOutcome.NotConnected));
+ Task RevalidateTailscaleDashboardAuthAsync(
+ string gatewayId,
+ CancellationToken cancellationToken = default) =>
+ Task.FromResult(false);
void SetGatewayConnectionIntent(string gatewayId, bool shouldBeConnected);
bool IsAutomaticReconnectAllowed(string gatewayId);
diff --git a/src/OpenClaw.Connection/OperatorScopeHelper.cs b/src/OpenClaw.Connection/OperatorScopeHelper.cs
index 6520fcb74b..80c7f42e48 100644
--- a/src/OpenClaw.Connection/OperatorScopeHelper.cs
+++ b/src/OpenClaw.Connection/OperatorScopeHelper.cs
@@ -16,8 +16,7 @@ public static bool CanReadConfig(IReadOnlyList grantedScopes) =>
HasScope(grantedScopes, ReadScope);
public static bool CanWriteConfig(IReadOnlyList grantedScopes) =>
- HasAdminScope(grantedScopes) ||
- HasScope(grantedScopes, WriteScope);
+ HasAdminScope(grantedScopes);
public static bool HasAdminScope(IReadOnlyList grantedScopes) =>
HasScope(grantedScopes, AdminScope);
diff --git a/src/OpenClaw.Connection/WslCommandRunner.cs b/src/OpenClaw.Connection/WslCommandRunner.cs
index 5bdcdef51e..5e443194ed 100644
--- a/src/OpenClaw.Connection/WslCommandRunner.cs
+++ b/src/OpenClaw.Connection/WslCommandRunner.cs
@@ -25,6 +25,18 @@ Task RunAsync(
CancellationToken cancellationToken = default,
IReadOnlyDictionary? environment = null);
+ Task RunWithStandardInputAsync(
+ IReadOnlyList arguments,
+ string standardInput,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null) =>
+ cancellationToken.IsCancellationRequested
+ ? Task.FromCanceled(cancellationToken)
+ : Task.FromResult(new WslCommandResult(
+ -1,
+ string.Empty,
+ "This WSL command runner does not support standard input."));
+
Task> ListDistrosAsync(CancellationToken cancellationToken = default);
Task TerminateDistroAsync(string name, CancellationToken cancellationToken = default);
@@ -36,6 +48,19 @@ Task RunInDistroAsync(
CancellationToken cancellationToken = default,
IReadOnlyDictionary? environment = null,
string? standardInput = null);
+
+ Task RunInDistroWithStandardInputAsync(
+ string name,
+ IReadOnlyList command,
+ string standardInput,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null) =>
+ cancellationToken.IsCancellationRequested
+ ? Task.FromCanceled(cancellationToken)
+ : Task.FromResult(new WslCommandResult(
+ -1,
+ string.Empty,
+ "This WSL command runner does not support standard input."));
}
///
@@ -88,6 +113,21 @@ public Task RunInDistroAsync(
standardInput);
}
+ public Task RunWithStandardInputAsync(
+ IReadOnlyList arguments,
+ string standardInput,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null) =>
+ RunProcessAsync("wsl.exe", arguments, cancellationToken, environment, standardInput);
+
+ public Task RunInDistroWithStandardInputAsync(
+ string name,
+ IReadOnlyList command,
+ string standardInput,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null)
+ => RunInDistroAsync(name, command, cancellationToken, environment, standardInput);
+
public Task TerminateDistroAsync(string name, CancellationToken cancellationToken = default) =>
RunAsync(["--terminate", name], cancellationToken);
@@ -173,6 +213,7 @@ private async Task RunProcessAsync(
var stderrTask = process.StandardError.ReadToEndAsync(timeoutCts.Token);
bool timedOut = false;
+ OperationCanceledException? cancellationException = null;
try
{
if (standardInput is not null)
@@ -208,17 +249,27 @@ await process.StandardInput.WriteAsync(
// slopwatch-ignore: SW003 Shutdown cancellation or disposal is expected and the caller already preserves the safe state.
try { process.Kill(entireProcessTree: true); } catch { }
}
- catch (OperationCanceledException)
+ catch (OperationCanceledException ex)
{
// slopwatch-ignore: SW003 Shutdown cancellation or disposal is expected and the caller already preserves the safe state.
try { process.Kill(entireProcessTree: true); } catch { }
- throw;
+ cancellationException = ex;
+ }
+
+ if (timedOut || cancellationException is not null)
+ {
+ using var exitCts = new CancellationTokenSource(TimeSpan.FromSeconds(5));
+ try { await process.WaitForExitAsync(exitCts.Token).ConfigureAwait(false); } catch { }
}
string stdout, stderr;
try { stdout = await stdoutTask; } catch { stdout = string.Empty; }
try { stderr = await stderrTask; } catch { stderr = string.Empty; }
+ cancellationToken.ThrowIfCancellationRequested();
+ if (cancellationException is not null)
+ throw cancellationException;
+
return timedOut
? new WslCommandResult(-1, stdout, "wsl.exe timed out", TimedOut: true)
: new WslCommandResult(process.ExitCode, stdout, stderr);
diff --git a/src/OpenClaw.SetupEngine/PairOperatorStep.cs b/src/OpenClaw.SetupEngine/PairOperatorStep.cs
index 2f2a51abfc..b0ab067764 100644
--- a/src/OpenClaw.SetupEngine/PairOperatorStep.cs
+++ b/src/OpenClaw.SetupEngine/PairOperatorStep.cs
@@ -12,6 +12,8 @@ namespace OpenClaw.SetupEngine;
public sealed class PairOperatorStep : SetupStep
{
+ private const string AllowTailscaleConfigKey = "gateway.auth.allowTailscale";
+
public override string Id => "pair-operator";
public override string DisplayName => "Pair operator connection";
public override RetryPolicy Retry => new(MaxAttempts: 3, InitialDelay: TimeSpan.FromSeconds(3));
@@ -49,6 +51,7 @@ public override async Task ExecuteAsync(SetupContext ctx, Cancellati
BootstrapToken = ctx.BootstrapToken,
IsLocal = true,
SetupManagedDistroName = ctx.DistroName,
+ TrustTailscaleAuth = ResolveEffectiveTailscaleAuthTrust(ctx.Config),
LastConnected = DateTime.UtcNow
};
@@ -170,6 +173,15 @@ record = registry.AddOrUpdate(record);
}
}
+ private static bool ResolveEffectiveTailscaleAuthTrust(SetupConfig config)
+ {
+ if (!config.Tailscale.Enabled || !config.Tailscale.TrustTailscaleAuth)
+ return false;
+
+ return config.Gateway.ExtraConfig?.TryGetValue(AllowTailscaleConfigKey, out var value) != true ||
+ bool.TryParse(value, out var enabled) && enabled;
+ }
+
internal static async Task EnsurePairingEndpointTrustedAsync(
SetupContext ctx,
CancellationToken cancellationToken,
diff --git a/src/OpenClaw.SetupEngine/TailscaleSetupSteps.cs b/src/OpenClaw.SetupEngine/TailscaleSetupSteps.cs
index 67044d1ef6..314a6e7699 100644
--- a/src/OpenClaw.SetupEngine/TailscaleSetupSteps.cs
+++ b/src/OpenClaw.SetupEngine/TailscaleSetupSteps.cs
@@ -139,15 +139,21 @@ private static bool HasGatewayWebProxy(JsonElement root, int port)
foreach (var webEndpoint in web.EnumerateObject())
{
- if (!webEndpoint.Value.TryGetProperty("Handlers", out var handlers) || handlers.ValueKind != JsonValueKind.Object)
+ if (webEndpoint.Value.ValueKind != JsonValueKind.Object ||
+ !webEndpoint.Value.TryGetProperty("Handlers", out var handlers) ||
+ handlers.ValueKind != JsonValueKind.Object)
+ {
continue;
+ }
foreach (var handler in handlers.EnumerateObject())
{
if (handler.Value.ValueKind != JsonValueKind.Object ||
!handler.Value.TryGetProperty("Proxy", out var proxy) ||
proxy.ValueKind != JsonValueKind.String)
+ {
continue;
+ }
if (IsLoopbackGatewayProxy(proxy.GetString(), port))
return true;
@@ -157,9 +163,6 @@ private static bool HasGatewayWebProxy(JsonElement root, int port)
return false;
}
- // Serve status represents Funnel as AllowFunnel on current Tailscale
- // versions. Accept the legacy Funnel spelling too so a version change
- // cannot silently turn a public endpoint into an accepted setup state.
private static bool HasEnabledFunnel(JsonElement root)
{
foreach (var property in root.EnumerateObject())
@@ -176,11 +179,10 @@ private static bool HasEnabledFunnel(JsonElement root)
JsonValueKind.True => true,
JsonValueKind.False or JsonValueKind.Null or JsonValueKind.Undefined => false,
JsonValueKind.Array => value.EnumerateArray().Any(ContainsEnabledFunnelValue),
- JsonValueKind.Object => value.EnumerateObject().Any(property => ContainsEnabledFunnelValue(property.Value)),
- // A non-empty string is a configured public endpoint in older status
- // documents. Be conservative: setup must never accept it as private.
+ JsonValueKind.Object => value.EnumerateObject().Any(property =>
+ ContainsEnabledFunnelValue(property.Value)),
JsonValueKind.String => !string.IsNullOrWhiteSpace(value.GetString()),
- _ => false
+ _ => false,
};
private static bool IsLoopbackGatewayProxy(string? proxy, int port) =>
diff --git a/src/OpenClaw.Shared/Capabilities/AppCapability.cs b/src/OpenClaw.Shared/Capabilities/AppCapability.cs
index 51020e9315..78c67c6008 100644
--- a/src/OpenClaw.Shared/Capabilities/AppCapability.cs
+++ b/src/OpenClaw.Shared/Capabilities/AppCapability.cs
@@ -46,7 +46,7 @@ public class AppCapability : NodeCapabilityBase
public Func? SettingsSetHandler;
public Func
internal sealed record ConnectionPagePlan
{
+ public static string TailscaleAuthFailureMessageResourceKey(
+ GatewayTailscaleAuthUpgradeOutcome outcome) => outcome switch
+ {
+ GatewayTailscaleAuthUpgradeOutcome.Ineligible => "ConnectionPage_TailscaleDashboardAuthFailureIneligible",
+ GatewayTailscaleAuthUpgradeOutcome.NotActive => "ConnectionPage_TailscaleDashboardAuthFailureNotActive",
+ GatewayTailscaleAuthUpgradeOutcome.NotConnected => "ConnectionPage_TailscaleDashboardAuthFailureNotConnected",
+ GatewayTailscaleAuthUpgradeOutcome.MissingConfigScope => "ConnectionPage_TailscaleDashboardAuthFailureMissingConfigScope",
+ GatewayTailscaleAuthUpgradeOutcome.ConfigUnavailable => "ConnectionPage_TailscaleDashboardAuthFailureConfigUnavailable",
+ GatewayTailscaleAuthUpgradeOutcome.PatchRejected => "ConnectionPage_TailscaleDashboardAuthFailurePatchRejected",
+ GatewayTailscaleAuthUpgradeOutcome.PersistenceFailed => "ConnectionPage_TailscaleDashboardAuthFailurePersistenceFailed",
+ GatewayTailscaleAuthUpgradeOutcome.UnsupportedTopology => "ConnectionPage_TailscaleDashboardAuthFailureUnsupportedTopology",
+ GatewayTailscaleAuthUpgradeOutcome.IngressNotReady => "ConnectionPage_TailscaleDashboardAuthFailureIngressNotReady",
+ _ => "ConnectionPage_TailscaleDashboardAuthFailureGeneric",
+ };
+
public ConnectionPageMode Mode { get; init; } = ConnectionPageMode.Welcome;
// ─── Status strip ───
diff --git a/src/OpenClaw.Tray.WinUI/Services/DashboardBrowser.cs b/src/OpenClaw.Tray.WinUI/Services/DashboardBrowser.cs
index 6498bf565b..030bb11da9 100644
--- a/src/OpenClaw.Tray.WinUI/Services/DashboardBrowser.cs
+++ b/src/OpenClaw.Tray.WinUI/Services/DashboardBrowser.cs
@@ -1,10 +1,5 @@
// Final hand-off of a credential-bearing Gateway Dashboard URL to Windows.
//
-// Usage (App.CreateDashboardLauncher):
-// var browser = new DashboardBrowser(
-// async url => await Launcher.LaunchUriAsync(new Uri(url)), Logger.Info);
-// new GatewayDashboardLauncher(..., browser.OpenAsync, ...);
-//
// Ordinary runs pass the URL straight to Windows. Gateway fixture runs never reach a real
// browser: the launch is logged with a redacted URL and reported as opened, so full-app
// tests can observe that dispatch happened (or did not) without leaking the fixture token.
diff --git a/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs b/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs
index 83171b7945..a377cceb5a 100644
--- a/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs
+++ b/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLauncher.cs
@@ -1,32 +1,93 @@
-using OpenClaw.Connection;
using OpenClaw.SetupEngine;
-using OpenClawTray.Helpers;
using System.ComponentModel;
using System.Runtime.InteropServices;
namespace OpenClawTray.Services;
-/// Uses the normal Dashboard credential path without setup completion authority.
internal sealed class GatewayDashboardLauncher(
Func ensureTunnel,
- Func resolveCredential,
+ Func resolveRequest,
+ GatewayDashboardLinkService linkService,
Func> launchBrowser,
- Action reportFailure,
- Action? reportOpened = null)
+ Action reportLinkFailure,
+ Action reportFailure,
+ Action? reportOpened = null,
+ Action? reportRevalidationWarning = null)
{
internal const string FailureNotificationId = "setup-dashboard-launch";
- public async Task OpenAsync(string? path = null, Action? authorizeDispatch = null)
+
+ public async Task OpenAsync(
+ string? path = null,
+ Action? authorizeDispatch = null,
+ CancellationToken cancellationToken = default)
{
+ cancellationToken.ThrowIfCancellationRequested();
+ GatewayDashboardLinkRequest? request;
try
{
if (!ensureTunnel())
throw new InvalidOperationException("The Gateway tunnel is unavailable.");
- var credential = resolveCredential()
- ?? throw new InvalidOperationException("The Gateway credential is unavailable.");
- var url = GatewayDashboardUrlBuilder.Build(credential.GatewayUrl, path, credential.Token,
- !credential.IsBootstrapToken && credential.Source == CredentialResolver.SourceSharedGatewayToken);
+ request = resolveRequest(path);
+ }
+ catch (Exception ex) when (IsExpectedLaunchFailure(ex))
+ {
+ reportFailure(null);
+ return false;
+ }
+
+ if (request is null)
+ {
+ reportFailure(null);
+ return false;
+ }
+
+ return await PrepareAndLaunchAsync(
+ request,
+ validateBeforeLaunch: null,
+ authorizeDispatch,
+ cancellationToken);
+ }
+
+ internal Task OpenSavedAsync(
+ GatewayDashboardLinkRequest request,
+ Func> validateBeforeLaunch,
+ CancellationToken cancellationToken = default,
+ Action? authorizeDispatch = null)
+ {
+ ArgumentNullException.ThrowIfNull(request);
+ ArgumentNullException.ThrowIfNull(validateBeforeLaunch);
+ return PrepareAndLaunchAsync(request, validateBeforeLaunch, authorizeDispatch, cancellationToken);
+ }
+
+ private async Task PrepareAndLaunchAsync(
+ GatewayDashboardLinkRequest request,
+ Func>? validateBeforeLaunch,
+ Action? authorizeDispatch,
+ CancellationToken cancellationToken)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ var result = await linkService.BuildAsync(request, cancellationToken);
+ cancellationToken.ThrowIfCancellationRequested();
+ if (result.RevalidationError is not null)
+ reportRevalidationWarning?.Invoke(result.RevalidationError);
+
+ if (!result.Success)
+ {
+ reportLinkFailure(result);
+ reportFailure(result.Error);
+ return false;
+ }
+
+ cancellationToken.ThrowIfCancellationRequested();
+ if (result.BrowserCredentialIncluded && validateBeforeLaunch is not null &&
+ !await validateBeforeLaunch(result))
+ return false;
+ cancellationToken.ThrowIfCancellationRequested();
+
+ try
+ {
authorizeDispatch?.Invoke();
- if (!await launchBrowser(url))
+ if (!await launchBrowser(result.Url!))
throw new InvalidOperationException("Windows did not open the Dashboard.");
}
catch (SetupNativeOwnershipException)
@@ -35,15 +96,16 @@ public async Task OpenAsync(string? path = null, Action? authorizeDispatch
}
catch (Exception ex) when (IsExpectedLaunchFailure(ex))
{
- // Browser failures can include the full credential-bearing URL. Do not log them.
- reportFailure();
+ // Browser failures can include a credential-bearing URL. Do not log them.
+ reportFailure(null);
return false;
}
+
reportOpened?.Invoke();
return true;
}
private static bool IsExpectedLaunchFailure(Exception error) =>
error is InvalidOperationException or IOException or UnauthorizedAccessException or
- ArgumentException or Win32Exception or COMException;
+ ArgumentException or FormatException or Win32Exception or COMException;
}
diff --git a/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLinkService.cs b/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLinkService.cs
new file mode 100644
index 0000000000..3f5e3bb375
--- /dev/null
+++ b/src/OpenClaw.Tray.WinUI/Services/GatewayDashboardLinkService.cs
@@ -0,0 +1,112 @@
+using OpenClawTray.Helpers;
+
+namespace OpenClawTray.Services;
+
+// Builds Dashboard links with current Tailscale trust and credential requirements.
+// Usage:
+// var result = await links.BuildAsync(request, cancellationToken);
+/// Inputs used to build a Gateway Dashboard link.
+public sealed record GatewayDashboardLinkRequest(
+ string GatewayUrl,
+ string? Path,
+ string? BrowserCredential,
+ bool AppendBrowserCredential,
+ string? TailscaleGatewayId = null);
+
+/// The Dashboard link and credential or revalidation result.
+public sealed record GatewayDashboardLinkResult(
+ string? Url,
+ bool TrustTailscaleAuth,
+ string? Error = null,
+ string? RevalidationError = null,
+ bool BrowserCredentialIncluded = false)
+{
+ public bool Success => Url is not null && Error is null;
+}
+
+/// Builds Dashboard URLs, revalidating trust when a Tailscale Gateway ID is supplied.
+public sealed class GatewayDashboardLinkService
+{
+ internal const string NoBrowserCompatibleCredentialKey =
+ "DashboardLink_NoBrowserCompatibleCredential";
+ internal const string RevalidationFailedKey =
+ "DashboardLink_TailscaleRevalidationFailed";
+
+ private readonly Func> _revalidateTailscaleAuth;
+ private readonly Func _localize;
+
+ public GatewayDashboardLinkService(
+ Func> revalidateTailscaleAuth,
+ Func localize)
+ {
+ _revalidateTailscaleAuth = revalidateTailscaleAuth
+ ?? throw new ArgumentNullException(nameof(revalidateTailscaleAuth));
+ _localize = localize ?? throw new ArgumentNullException(nameof(localize));
+ }
+
+ /// Revalidates Tailscale trust when applicable and builds a browser-compatible URL.
+ /// The Gateway URL, path, and available browser credential.
+ /// Cancels trust revalidation.
+ /// The built link or the reason a compatible link could not be created.
+ public async Task BuildAsync(
+ GatewayDashboardLinkRequest request,
+ CancellationToken cancellationToken = default)
+ {
+ var trustTailscaleAuth = false;
+ string? revalidationError = null;
+
+ if (!string.IsNullOrWhiteSpace(request.TailscaleGatewayId))
+ {
+ try
+ {
+ trustTailscaleAuth = await _revalidateTailscaleAuth(
+ request.TailscaleGatewayId,
+ cancellationToken)
+ .ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
+ {
+ throw;
+ }
+ catch (Exception)
+ {
+ revalidationError = _localize(RevalidationFailedKey);
+ }
+ }
+
+ if (!string.IsNullOrWhiteSpace(request.TailscaleGatewayId) &&
+ !trustTailscaleAuth &&
+ (!request.AppendBrowserCredential || string.IsNullOrWhiteSpace(request.BrowserCredential)))
+ {
+ return new GatewayDashboardLinkResult(
+ Url: null,
+ TrustTailscaleAuth: false,
+ Error: _localize(NoBrowserCompatibleCredentialKey),
+ RevalidationError: revalidationError);
+ }
+
+ if (!GatewayDashboardUrlBuilder.TryBuild(
+ request.GatewayUrl,
+ request.Path,
+ request.BrowserCredential,
+ request.AppendBrowserCredential && !trustTailscaleAuth,
+ out var url,
+ out var urlError,
+ trustTailscaleAuth))
+ {
+ return new GatewayDashboardLinkResult(
+ Url: null,
+ TrustTailscaleAuth: trustTailscaleAuth,
+ Error: urlError,
+ RevalidationError: revalidationError);
+ }
+
+ var browserCredentialIncluded = GatewayDashboardUrlBuilder.HasSharedTokenFragment(url);
+
+ return new GatewayDashboardLinkResult(
+ url,
+ trustTailscaleAuth,
+ RevalidationError: revalidationError,
+ BrowserCredentialIncluded: browserCredentialIncluded);
+ }
+}
diff --git a/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs b/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs
index 942a7dd022..9e5409f5ab 100644
--- a/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs
+++ b/src/OpenClaw.Tray.WinUI/Services/IWindowManager.cs
@@ -42,7 +42,7 @@ internal interface IWindowManager
/// Shows the Local AI setup flow.
Task ShowLocalAiSetupAsync();
Task ShowGatewayWizardAsync();
- Task ShowDashboardLaunchFailureAsync(Action? retry);
+ Task ShowDashboardLaunchFailureAsync(Action? retry, string? localizedReason = null);
Task ShowNativeSetupAsync(OpenClaw.SetupEngine.SetupNativeCompletion completion, CancellationToken ct);
Task ShowNativeSetupPreparingAsync(OpenClaw.SetupEngine.GatewayAiSetupCompletion proof,
Func> verify, CancellationToken ct);
diff --git a/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs b/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs
index 64f01148f6..dcaf59b174 100644
--- a/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs
+++ b/src/OpenClaw.Tray.WinUI/Services/WindowManager.cs
@@ -143,11 +143,14 @@ public void InitializeRuntimeAnchor()
private bool _dashboardFailureVisible;
- public async Task ShowDashboardLaunchFailureAsync(Action? retry)
+ public async Task ShowDashboardLaunchFailureAsync(Action? retry, string? localizedReason = null)
{
if (_isShuttingDown || _dashboardFailureVisible)
return;
- var message = LocalizationHelper.GetString("Onboarding_DashboardLaunchFailed");
+ var guidance = LocalizationHelper.GetString("Onboarding_DashboardLaunchFailed");
+ var message = string.IsNullOrWhiteSpace(localizedReason)
+ ? guidance
+ : $"{localizedReason}{Environment.NewLine}{guidance}";
_callbacks.GetAppNotificationService()?.Show(new AppNotification
{
Id = GatewayDashboardLauncher.FailureNotificationId,
diff --git a/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw
index 3147581ee4..2c0aee7cce 100644
--- a/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw
+++ b/src/OpenClaw.Tray.WinUI/Strings/en-us/Resources.resw
@@ -5003,6 +5003,60 @@ Open Channels in the web dashboard.
Open dashboard
+
+ Use Tailscale identity for dashboard
+
+
+ Use Tailscale identity for dashboard?
+
+
+ This requests Tailscale identity authentication on a gateway with gateway-managed foreground Tailscale Serve. Your saved token, device identity, WSL distro, and pairing remain unchanged. This action does not change Serve.
+
+
+ Enable
+
+
+ Tailscale dashboard identity enabled.
+
+
+ The gateway accepted the Tailscale identity setting. Dashboard links will verify that it is applied and ready before omitting the token.
+
+
+ This action requires gateway-managed foreground Tailscale Serve. Setup's background Serve is not supported. Ask the gateway administrator to review the deployment. No setting was changed.
+
+
+ Gateway-managed Tailscale ingress is not ready or could not be verified. Check the gateway and Tailscale connection, then retry. No setting was changed.
+
+
+ This gateway is no longer a managed Tailscale gateway. Refresh the gateway list and try again.
+
+
+ Select this gateway as active, then try again.
+
+
+ Connect to this gateway, then try again.
+
+
+ Reconnect with operator.admin access. Ask the gateway administrator if that permission is unavailable.
+
+
+ The gateway configuration could not be read. Reconnect to the gateway and try again.
+
+
+ The gateway did not confirm the change. Reconnect and retry. Retrying safely reapplies only the same Tailscale setting.
+
+
+ The local Tailscale trust setting could not be saved. Check access to the OpenClaw Tray data folder, then retry.
+
+
+ Tailscale dashboard identity could not be enabled. Reconnect to the gateway and try again.
+
+
+ No browser-compatible gateway credential is available
+
+
+ Tailscale dashboard authentication revalidation failed
+
Options for {0}
@@ -5526,7 +5580,7 @@ Open Channels in the web dashboard.
Connect to a gateway before saving config.
- This operator token does not have operator.write permission, so config changes cannot be saved.
+ This operator token does not have operator.admin permission, so config changes cannot be saved.
Config not loaded
@@ -5607,7 +5661,7 @@ Open Channels in the web dashboard.
This operator token lacks operator.read permission, so the gateway config cannot be loaded here.
- This operator token can read config but lacks operator.write permission. You can inspect and validate drafts, but Save is disabled.
+ This operator token can read config but lacks operator.admin permission. You can inspect and validate drafts, but Save is disabled.
No unsaved changes.
@@ -5634,7 +5688,7 @@ Open Channels in the web dashboard.
Config unavailable: missing operator.read
- Read-only: missing operator.write
+ Read-only: missing operator.admin
Fix validation errors before saving
diff --git a/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw
index 42129c9a42..f8b934eab4 100644
--- a/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw
+++ b/src/OpenClaw.Tray.WinUI/Strings/fr-fr/Resources.resw
@@ -4995,6 +4995,60 @@ Ouvrir Canaux dans le tableau de bord web.
Ouvrir le tableau de bord
+
+ Utiliser l’identité Tailscale pour le tableau de bord
+
+
+ Utiliser l’identité Tailscale pour le tableau de bord ?
+
+
+ Cela demande l’authentification par identité Tailscale sur une passerelle qui gère Tailscale Serve au premier plan. Votre jeton enregistré, l’identité de l’appareil, la distribution WSL et l’association restent inchangés. Cette action ne modifie pas Serve.
+
+
+ Activer
+
+
+ L’identité Tailscale est activée pour le tableau de bord.
+
+
+ La passerelle a accepté le paramètre d’identité Tailscale. Les liens du tableau de bord vérifieront qu’il est appliqué et opérationnel avant d’omettre le jeton.
+
+
+ Cette action nécessite Tailscale Serve au premier plan, géré par la passerelle. Le mode Serve en arrière-plan créé par l’installation n’est pas pris en charge. Demandez à l’administrateur de la passerelle de vérifier le déploiement. Aucun paramètre n’a été modifié.
+
+
+ Le point d’entrée Tailscale géré par la passerelle n’est pas prêt ou n’a pas pu être vérifié. Vérifiez la passerelle et la connexion Tailscale, puis réessayez. Aucun paramètre n’a été modifié.
+
+
+ Cette passerelle n’est plus une passerelle Tailscale gérée. Actualisez la liste des passerelles et réessayez.
+
+
+ Sélectionnez cette passerelle comme passerelle active, puis réessayez.
+
+
+ Connectez-vous à cette passerelle, puis réessayez.
+
+
+ Reconnectez-vous avec l’autorisation operator.admin. Demandez-la à l’administrateur de la passerelle si elle n’est pas disponible.
+
+
+ Impossible de lire la configuration de la passerelle. Reconnectez-vous à la passerelle et réessayez.
+
+
+ La passerelle n’a pas confirmé la modification. Reconnectez-vous et réessayez. Une nouvelle tentative réapplique uniquement le même paramètre Tailscale en toute sécurité.
+
+
+ Impossible d’enregistrer localement le paramètre de confiance Tailscale. Vérifiez l’accès au dossier de données OpenClaw Tray, puis réessayez.
+
+
+ Impossible d’activer l’identité Tailscale pour le tableau de bord. Reconnectez-vous à la passerelle et réessayez.
+
+
+ Aucun identifiant de passerelle compatible avec le navigateur n’est disponible
+
+
+ La revalidation de l’authentification Tailscale du tableau de bord a échoué
+
Options pour {0}
@@ -5518,7 +5572,7 @@ Ouvrir Canaux dans le tableau de bord web.
Connectez-vous à une passerelle avant d'enregistrer la configuration.
- Ce jeton opérateur ne dispose pas de l'autorisation operator.write ; les modifications de configuration ne peuvent donc pas être enregistrées.
+ Ce jeton opérateur ne dispose pas de l'autorisation operator.admin ; les modifications de configuration ne peuvent donc pas être enregistrées.
Configuration non chargée
@@ -5599,7 +5653,7 @@ Ouvrir Canaux dans le tableau de bord web.
Ce jeton opérateur ne dispose pas de l'autorisation operator.read ; la configuration de la passerelle ne peut donc pas être chargée ici.
- Ce jeton opérateur peut lire la configuration, mais ne dispose pas de l'autorisation operator.write. Vous pouvez inspecter et valider les brouillons, mais Enregistrer est désactivé.
+ Ce jeton opérateur peut lire la configuration, mais ne dispose pas de l'autorisation operator.admin. Vous pouvez inspecter et valider les brouillons, mais Enregistrer est désactivé.
Aucune modification non enregistrée.
@@ -5626,7 +5680,7 @@ Ouvrir Canaux dans le tableau de bord web.
Configuration indisponible : operator.read manquant
- Lecture seule : operator.write manquant
+ Lecture seule : operator.admin manquant
Corrigez les erreurs de validation avant d'enregistrer
diff --git a/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw
index d7f061b2bb..e9d7bff3e2 100644
--- a/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw
+++ b/src/OpenClaw.Tray.WinUI/Strings/nl-nl/Resources.resw
@@ -4996,6 +4996,60 @@ Open Kanalen in het webdashboard.
Dashboard openen
+
+ Tailscale-identiteit gebruiken voor het dashboard
+
+
+ Tailscale-identiteit gebruiken voor het dashboard?
+
+
+ Hiermee vraagt u verificatie via Tailscale-identiteit aan op een gateway die Tailscale Serve op de voorgrond beheert. Uw opgeslagen token, apparaatidentiteit, WSL-distributie en koppeling blijven ongewijzigd. Deze actie wijzigt Serve niet.
+
+
+ Inschakelen
+
+
+ Tailscale-identiteit voor het dashboard is ingeschakeld.
+
+
+ De gateway heeft de instelling voor Tailscale-identiteit geaccepteerd. Dashboardlinks controleren of deze is toegepast en gereed is voordat het token wordt weggelaten.
+
+
+ Deze actie vereist Tailscale Serve op de voorgrond, beheerd door de gateway. Serve op de achtergrond uit de installatie wordt niet ondersteund. Vraag de gatewaybeheerder om de implementatie te controleren. Er is geen instelling gewijzigd.
+
+
+ De door de gateway beheerde Tailscale-toegang is niet gereed of kon niet worden geverifieerd. Controleer de gateway en de Tailscale-verbinding en probeer het opnieuw. Er is geen instelling gewijzigd.
+
+
+ Deze gateway is niet langer een beheerde Tailscale-gateway. Vernieuw de gatewaylijst en probeer het opnieuw.
+
+
+ Stel deze gateway in als actief en probeer het opnieuw.
+
+
+ Maak verbinding met deze gateway en probeer het opnieuw.
+
+
+ Maak opnieuw verbinding met de machtiging operator.admin. Vraag de gatewaybeheerder om deze toe te kennen als deze ontbreekt.
+
+
+ De gatewayconfiguratie kon niet worden gelezen. Maak opnieuw verbinding met de gateway en probeer het opnieuw.
+
+
+ De gateway heeft de wijziging niet bevestigd. Maak opnieuw verbinding en probeer het opnieuw. Een nieuwe poging past veilig alleen dezelfde Tailscale-instelling opnieuw toe.
+
+
+ De lokale instelling voor Tailscale-vertrouwen kon niet worden opgeslagen. Controleer de toegang tot de gegevensmap van OpenClaw Tray en probeer het opnieuw.
+
+
+ Tailscale-identiteit kon niet worden ingeschakeld. Maak opnieuw verbinding met de gateway en probeer het opnieuw.
+
+
+ Er is geen gatewayreferentie beschikbaar die geschikt is voor de browser
+
+
+ Herverificatie van Tailscale-authenticatie voor het dashboard is mislukt
+
Opties voor {0}
@@ -5519,7 +5573,7 @@ Open Kanalen in het webdashboard.
Maak verbinding met een gateway voordat u de configuratie opslaat.
- Dit operatortoken heeft geen operator.write-machtiging, dus configuratiewijzigingen kunnen niet worden opgeslagen.
+ Dit operatortoken heeft geen operator.admin-machtiging, dus configuratiewijzigingen kunnen niet worden opgeslagen.
Configuratie niet geladen
@@ -5600,7 +5654,7 @@ Open Kanalen in het webdashboard.
Dit operatortoken mist de operator.read-machtiging, dus de gatewayconfiguratie kan hier niet worden geladen.
- Dit operatortoken kan de configuratie lezen, maar mist de operator.write-machtiging. U kunt concepten bekijken en valideren, maar Opslaan is uitgeschakeld.
+ Dit operatortoken kan de configuratie lezen, maar mist de operator.admin-machtiging. U kunt concepten bekijken en valideren, maar Opslaan is uitgeschakeld.
Geen niet-opgeslagen wijzigingen.
@@ -5627,7 +5681,7 @@ Open Kanalen in het webdashboard.
Configuratie niet beschikbaar: operator.read ontbreekt
- Alleen-lezen: operator.write ontbreekt
+ Alleen-lezen: operator.admin ontbreekt
Los validatiefouten op voordat u opslaat
diff --git a/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw
index 27aafb20d6..1c469aa99e 100644
--- a/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw
+++ b/src/OpenClaw.Tray.WinUI/Strings/pt-br/Resources.resw
@@ -4972,6 +4972,60 @@ Abrir Canais no painel web.
Abrir painel
+
+ Usar identidade Tailscale para o painel
+
+
+ Usar a identidade do Tailscale no painel?
+
+
+ Isso solicita autenticação pela identidade do Tailscale em um gateway que gerencia o Tailscale Serve em primeiro plano. O token salvo, a identidade do dispositivo, a distribuição WSL e o pareamento permanecem inalterados. Esta ação não altera o Serve.
+
+
+ Ativar
+
+
+ Identidade do Tailscale para o painel ativada.
+
+
+ O gateway aceitou a configuração de identidade do Tailscale. Os links do painel verificarão se ela foi aplicada e está pronta antes de omitir o token.
+
+
+ Esta ação requer o Tailscale Serve em primeiro plano, gerenciado pelo gateway. O Serve em segundo plano criado pela instalação não é compatível. Peça ao administrador do gateway para revisar a implantação. Nenhuma configuração foi alterada.
+
+
+ A entrada Tailscale gerenciada pelo gateway não está pronta ou não pôde ser verificada. Verifique o gateway e a conexão Tailscale e tente novamente. Nenhuma configuração foi alterada.
+
+
+ Este gateway não é mais um gateway Tailscale gerenciado. Atualize a lista de gateways e tente novamente.
+
+
+ Defina este gateway como ativo e tente novamente.
+
+
+ Conecte-se a este gateway e tente novamente.
+
+
+ Reconecte-se com a permissão operator.admin. Se ela não estiver disponível, peça ao administrador do gateway que a conceda.
+
+
+ Não foi possível ler a configuração do gateway. Reconecte-se ao gateway e tente novamente.
+
+
+ O gateway não confirmou a alteração. Reconecte-se e tente novamente. Uma nova tentativa reaplica com segurança apenas a mesma configuração do Tailscale.
+
+
+ Não foi possível salvar localmente a configuração de confiança do Tailscale. Verifique o acesso à pasta de dados do OpenClaw Tray e tente novamente.
+
+
+ Não foi possível habilitar a identidade Tailscale. Reconecte-se ao gateway e tente novamente.
+
+
+ Nenhuma credencial de gateway compatível com o navegador está disponível
+
+
+ Falha na revalidação da autenticação do painel pelo Tailscale
+
Opções de {0}
@@ -5495,7 +5549,7 @@ Abrir Canais no painel web.
Conecte-se a um Gateway antes de salvar a configuração.
- Este token de operador não tem permissão operator.write, então as alterações de configuração não podem ser salvas.
+ Este token de operador não tem permissão operator.admin, então as alterações de configuração não podem ser salvas.
Configuração não carregada
@@ -5576,7 +5630,7 @@ Abrir Canais no painel web.
Este token de operador não tem permissão operator.read, então a configuração do Gateway não pode ser carregada aqui.
- Este token de operador pode ler a configuração, mas não tem permissão operator.write. Você pode inspecionar e validar rascunhos, mas Salvar está desativado.
+ Este token de operador pode ler a configuração, mas não tem permissão operator.admin. Você pode inspecionar e validar rascunhos, mas Salvar está desativado.
Nenhuma alteração não salva.
@@ -5603,7 +5657,7 @@ Abrir Canais no painel web.
Configuração indisponível: operator.read ausente
- Somente leitura: operator.write ausente
+ Somente leitura: operator.admin ausente
Corrija os erros de validação antes de salvar
diff --git a/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw
index 8ba82d96da..af67f9a080 100644
--- a/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw
+++ b/src/OpenClaw.Tray.WinUI/Strings/zh-cn/Resources.resw
@@ -4995,6 +4995,60 @@
打开仪表板
+
+ 使用 Tailscale 身份访问仪表板
+
+
+ 使用 Tailscale 身份访问仪表板?
+
+
+ 这将向自行管理前台 Tailscale Serve 的网关请求 Tailscale 身份认证。已保存的令牌、设备身份、WSL 发行版和配对信息均保持不变。此操作不会更改 Serve。
+
+
+ 启用
+
+
+ 已启用仪表板的 Tailscale 身份认证。
+
+
+ 网关已接受 Tailscale 身份设置。仪表板链接将在确认设置已应用且就绪后才省略令牌。
+
+
+ 此操作需要由网关管理的前台 Tailscale Serve。不支持安装程序创建的后台 Serve。请让网关管理员检查部署。未更改任何设置。
+
+
+ 由网关管理的 Tailscale 入口尚未就绪或无法验证。请检查网关和 Tailscale 连接后重试。未更改任何设置。
+
+
+ 此网关已不再是受管理的 Tailscale 网关。请刷新网关列表后重试。
+
+
+ 请将此网关设为当前活动网关后重试。
+
+
+ 请先连接到此网关,然后重试。
+
+
+ 请使用具有 operator.admin 权限的连接重新连接。若无法获得此权限,请联系网关管理员。
+
+
+ 无法读取网关配置。请重新连接网关后重试。
+
+
+ 网关未确认此更改。请重新连接后重试。重试只会安全地重新应用同一项 Tailscale 设置。
+
+
+ 无法在本地保存 Tailscale 信任设置。请检查 OpenClaw Tray 数据文件夹的访问权限后重试。
+
+
+ 无法启用 Tailscale 仪表板身份认证。请重新连接网关后重试。
+
+
+ 没有可供浏览器使用的网关凭据
+
+
+ 重新验证仪表板的 Tailscale 身份认证失败
+
{0} 的选项
@@ -5518,7 +5572,7 @@
保存配置前请先连接到网关。
- 此操作员令牌没有 operator.write 权限,因此无法保存配置更改。
+ 此操作员令牌没有 operator.admin 权限,因此无法保存配置更改。
配置未加载
@@ -5599,7 +5653,7 @@
此操作员令牌缺少 operator.read 权限,因此无法在此处加载网关配置。
- 此操作员令牌可以读取配置,但缺少 operator.write 权限。你可以检查并验证草稿,但“保存”已禁用。
+ 此操作员令牌可以读取配置,但缺少 operator.admin 权限。你可以检查并验证草稿,但“保存”已禁用。
没有未保存的更改。
@@ -5626,7 +5680,7 @@
配置不可用:缺少 operator.read
- 只读:缺少 operator.write
+ 只读:缺少 operator.admin
保存前请修复验证错误
diff --git a/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw b/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw
index 89b3a4f6f2..8914b1bfb5 100644
--- a/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw
+++ b/src/OpenClaw.Tray.WinUI/Strings/zh-tw/Resources.resw
@@ -4995,6 +4995,60 @@
開啟儀表板
+
+ 使用 Tailscale 身分存取儀表板
+
+
+ 使用 Tailscale 身分存取儀表板?
+
+
+ 這會向自行管理前景 Tailscale Serve 的閘道要求 Tailscale 身分驗證。已儲存的權杖、裝置身分、WSL 發行版本和配對資訊均維持不變。此操作不會變更 Serve。
+
+
+ 啟用
+
+
+ 已啟用儀表板的 Tailscale 身分驗證。
+
+
+ 閘道已接受 Tailscale 身分設定。儀表板連結會在確認設定已套用且就緒後才省略權杖。
+
+
+ 此操作需要由閘道管理的前景 Tailscale Serve。不支援安裝程式建立的背景 Serve。請讓閘道管理員檢查部署。未變更任何設定。
+
+
+ 由閘道管理的 Tailscale 入口尚未就緒或無法驗證。請檢查閘道和 Tailscale 連線後重試。未變更任何設定。
+
+
+ 此閘道已不再是受管理的 Tailscale 閘道。請重新整理閘道清單後再試一次。
+
+
+ 請將此閘道設為目前作用中的閘道,然後再試一次。
+
+
+ 請先連線到此閘道,然後再試一次。
+
+
+ 請使用具備 operator.admin 權限的連線重新連線。若無法取得此權限,請聯絡閘道管理員。
+
+
+ 無法讀取閘道設定。請重新連線至閘道後再試一次。
+
+
+ 閘道未確認這項變更。請重新連線後重試。重試只會安全地重新套用同一項 Tailscale 設定。
+
+
+ 無法在本機儲存 Tailscale 信任設定。請檢查 OpenClaw Tray 資料資料夾的存取權限後再試一次。
+
+
+ 無法啟用 Tailscale 儀表板身分驗證。請重新連線至閘道後再試一次。
+
+
+ 沒有可供瀏覽器使用的閘道認證
+
+
+ 重新驗證儀表板的 Tailscale 身分驗證失敗
+
{0} 的選項
@@ -5518,7 +5572,7 @@
儲存設定前請先連線到閘道。
- 此操作員權杖沒有 operator.write 權限,因此無法儲存設定變更。
+ 此操作員權杖沒有 operator.admin 權限,因此無法儲存設定變更。
設定未載入
@@ -5599,7 +5653,7 @@
此操作員權杖缺少 operator.read 權限,因此無法在此載入閘道設定。
- 此操作員權杖可以讀取設定,但缺少 operator.write 權限。您可以檢查並驗證草稿,但「儲存」已停用。
+ 此操作員權杖可以讀取設定,但缺少 operator.admin 權限。您可以檢查並驗證草稿,但「儲存」已停用。
沒有未儲存的變更。
@@ -5626,7 +5680,7 @@
設定無法使用:缺少 operator.read
- 唯讀:缺少 operator.write
+ 唯讀:缺少 operator.admin
儲存前請修正驗證錯誤
diff --git a/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs b/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs
index c7df832d40..06564e572f 100644
--- a/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs
+++ b/tests/OpenClaw.Connection.Tests/GatewayConnectionManagerTests.cs
@@ -7,6 +7,7 @@
using OpenClaw.Connection;
using OpenClaw.Connection.NativeGateway;
using OpenClaw.TestSupport;
+using OpenClaw.TestSupport.Gateway;
namespace OpenClaw.Connection.Tests;
@@ -2907,7 +2908,7 @@ public async Task ConnectWithSharedTokenAsync_RevalidatesDurableTokensUnderTrans
tunnel.AllowStart.SetResult(true);
await connectTask.WaitAsync(TimeSpan.FromSeconds(2));
- var result = await replaceTask.WaitAsync(TimeSpan.FromSeconds(10));
+ var result = await replaceTask.WaitAsync(TimeSpan.FromSeconds(20));
Assert.Equal(SetupCodeOutcome.ConnectionFailed, result.Outcome);
Assert.Null(_registry.GetById("gw-1")?.SharedGatewayToken);
@@ -3644,6 +3645,70 @@ public async Task DiagnosticEvent_Fires_OnCredentialResolution()
Assert.Contains(events, e => e.Category == "credential");
}
+ [Fact]
+ public async Task TailscaleDashboardAuthUnsupportedTopology_RecordsOutcomeWithoutPatch()
+ {
+ const string fixtureToken = "fixture-operator-token";
+ const string gatewayId = "tailscale-gateway";
+ using var data = new TempDirectory("openclaw-tailscale-auth-test-");
+ await using var fixture = await FixtureGatewayServer.StartAsync(
+ GatewayScenario.CreateNativeSetup((_, _) => new { ok = true }),
+ fixtureToken);
+
+ var registry = new GatewayRegistry(data.Path);
+ registry.AddOrUpdate(new GatewayRecord
+ {
+ Id = gatewayId,
+ Url = "wss://openclaw.tailnet.ts.net",
+ IsLocal = true,
+ SetupManagedDistroName = "OpenClawGateway",
+ });
+ registry.SetActive(gatewayId);
+ var resolver = new MockCredentialResolver
+ {
+ OperatorCredential = new GatewayCredential(fixtureToken, false, "fixture"),
+ };
+ var factory = new FixtureGatewayClientFactory(fixture.Endpoint.ToString());
+ await using var manager = new GatewayConnectionManager(
+ resolver, factory, registry, NullLogger.Instance);
+
+ await manager.ConnectAsync(gatewayId);
+ try
+ {
+ await fixture.HandshakeCompleted.WaitAsync(StepTimeout);
+ }
+ catch (TimeoutException ex)
+ {
+ var snapshot = manager.CurrentSnapshot;
+ var requests = string.Join(", ", fixture.Requests.Select(request => $"{request.Method}={request.Outcome}"));
+ var diagnostics = string.Join(" | ", manager.Diagnostics.GetAll().Select(entry => $"{entry.Category}: {entry.Message}; {entry.Detail}"));
+ throw new TimeoutException(
+ $"Fixture handshake failed. Operator={snapshot.OperatorState}; error={snapshot.OperatorError}; " +
+ $"errorKind={snapshot.OperatorErrorKind}; protocol={snapshot.OperatorProtocolCompatibility}; " +
+ $"clientCreated={factory.RequestedGatewayUrl is not null}; gatewayReady={manager.OperatorClient?.IsConnectedToGateway}; " +
+ $"connections={fixture.ConnectionCount}; sharedConnects={fixture.SharedCredentialConnects}; " +
+ $"deviceRejections={fixture.DeviceTokenRejections}; requests={requests}; diagnostics={diagnostics}", ex);
+ }
+ await WaitUntilAsync(() => manager.OperatorClient is
+ { IsConnectedToGateway: true, HasHandshakeSnapshot: true });
+
+ Assert.Equal("wss://openclaw.tailnet.ts.net", factory.RequestedGatewayUrl);
+ Assert.Contains("operator.admin", manager.OperatorClient!.GrantedOperatorScopes);
+
+ var result = await manager.EnableTailscaleDashboardAuthAsync(gatewayId);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.UnsupportedTopology, result.Outcome);
+ Assert.Null(result.Error);
+ Assert.Contains(fixture.Requests, request => request.Method == "config.get" && request.Outcome == "ok");
+ Assert.DoesNotContain(fixture.Requests, request => request.Method == "config.patch");
+ var upgradeEvents = manager.Diagnostics.GetAll()
+ .Where(entry => entry.Category == "tailscale-auth")
+ .ToArray();
+ var diagnostic = Assert.Single(upgradeEvents);
+ Assert.Equal("Dashboard auth upgrade: UnsupportedTopology", diagnostic.Message);
+ Assert.Null(diagnostic.Detail);
+ }
+
[Fact]
public async Task Dispose_CleansUp()
{
@@ -6117,6 +6182,23 @@ public IGatewayClientLifecycle Create(string gatewayUrl, GatewayCredential crede
}
}
+ private sealed class FixtureGatewayClientFactory(string fixtureEndpoint) : IGatewayClientFactory
+ {
+ private readonly GatewayClientFactory _inner = new();
+
+ public string? RequestedGatewayUrl { get; private set; }
+
+ public IGatewayClientLifecycle Create(
+ string gatewayUrl,
+ GatewayCredential credential,
+ string identityPath,
+ IOpenClawLogger logger)
+ {
+ RequestedGatewayUrl = gatewayUrl;
+ return _inner.Create(fixtureEndpoint, credential, identityPath, logger);
+ }
+ }
+
private sealed class ThrowingWriteFileSystem : IFileSystem
{
public bool FileExists(string path) => File.Exists(path);
diff --git a/tests/OpenClaw.Connection.Tests/GatewayRegistryTests.cs b/tests/OpenClaw.Connection.Tests/GatewayRegistryTests.cs
index b4e36292ef..6890c12e09 100644
--- a/tests/OpenClaw.Connection.Tests/GatewayRegistryTests.cs
+++ b/tests/OpenClaw.Connection.Tests/GatewayRegistryTests.cs
@@ -360,6 +360,34 @@ public void FindByUrl_IsCaseInsensitive()
Assert.NotNull(found);
}
+ [Theory]
+ [InlineData("wss://Gateway.Example.com/", "wss://gateway.example.com")]
+ [InlineData("wss://gateway.example.com:443/?token=a#device", "wss://gateway.example.com?token=a#device")]
+ public void FindByUrl_TreatsEquivalentRemoteRootPathSpellingsAsSameEndpoint(string storedUrl, string lookupUrl)
+ {
+ _registry.AddOrUpdate(MakeRecord("gw-remote", storedUrl));
+
+ Assert.Equal("gw-remote", _registry.FindByUrl(lookupUrl)?.Id);
+ Assert.Equal("gw-remote", Assert.Single(_registry.FindAllByUrl(lookupUrl)).Id);
+ }
+
+ [Theory]
+ [InlineData("wss://gateway.example.com/?token=old", "wss://gateway.example.com?token=new")]
+ [InlineData("wss://gateway.example.com/?token=a", "wss://gateway.example.com?token=A")]
+ [InlineData("wss://gateway.example.com/#old", "wss://gateway.example.com#new")]
+ [InlineData("wss://gateway.example.com/#Device", "wss://gateway.example.com#device")]
+ [InlineData("wss://gateway.example.com:8443/", "wss://gateway.example.com")]
+ [InlineData("wss://gateway.example.com:8443/", "ws://gateway.example.com:8443")]
+ [InlineData("wss://gateway-one.example.com/", "wss://gateway-two.example.com")]
+ [InlineData("wss://gateway.example.com/workspace/", "wss://gateway.example.com/workspace")]
+ [InlineData("wss://gateway.example.com/nested/..", "wss://gateway.example.com/")]
+ public void FindByUrl_DoesNotMergeRootSlashUrlsAcrossEndpointBoundaries(string storedUrl, string lookupUrl)
+ {
+ _registry.AddOrUpdate(MakeRecord("gw-remote", storedUrl));
+
+ Assert.Null(_registry.FindByUrl(lookupUrl));
+ }
+
[Fact]
public void FindByUrl_TreatsLoopbackLocalhostAnd127AsSameGateway()
{
diff --git a/tests/OpenClaw.Connection.Tests/GatewayTailscaleAuthLiveVerifierTests.cs b/tests/OpenClaw.Connection.Tests/GatewayTailscaleAuthLiveVerifierTests.cs
new file mode 100644
index 0000000000..6774df551b
--- /dev/null
+++ b/tests/OpenClaw.Connection.Tests/GatewayTailscaleAuthLiveVerifierTests.cs
@@ -0,0 +1,1001 @@
+using System.Diagnostics;
+using System.Text;
+using System.Text.Json;
+
+namespace OpenClaw.Connection.Tests;
+
+public sealed class GatewayTailscaleAuthLiveVerifierTests
+{
+ private static readonly TimeSpan StepTimeout =
+ int.TryParse(Environment.GetEnvironmentVariable("OPENCLAW_TEST_GATEWAY_STEP_TIMEOUT_SECONDS"), out var seconds) && seconds > 0
+ ? TimeSpan.FromSeconds(seconds) : TimeSpan.FromSeconds(15);
+
+ [Theory]
+ [MemberData(nameof(StatusResults))]
+ public async Task VerifyAsync_ClassifiesStatusResult(
+ WslCommandResult commandResult,
+ string expected,
+ int expectedProbeCalls)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ServeStatus()
+ : commandResult));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(expected, result.ToString());
+ Assert.Equal("OpenClawGateway", runner.DistroName);
+ Assert.Equal(["/usr/bin/tailscale", "status", "--json"], runner.Commands[0]);
+ Assert.Equal(
+ ["-d", "OpenClawGateway", "--user", "root", "--", "/usr/bin/tailscale", "status", "--json"],
+ runner.HostArguments[0]);
+ Assert.Equal(expectedProbeCalls, runner.ProbeCalls);
+ if (expectedProbeCalls == 2)
+ {
+ Assert.Equal(["/usr/bin/tailscale", "serve", "status", "--json"], runner.Commands[1]);
+ Assert.Equal(
+ ["-d", "OpenClawGateway", "--user", "root", "--", "/usr/bin/tailscale", "serve", "status", "--json"],
+ runner.HostArguments[1]);
+ }
+ }
+
+ [Fact]
+ public async Task VerifyAsync_RecordWithoutManagedDistroIsUnavailableWithoutCommand()
+ {
+ var runner = new FakeWslCommandRunner((_, _, _) =>
+ Task.FromResult(RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(
+ ManagedRecord() with { SetupManagedDistroName = null, FriendlyName = null },
+ 18789,
+ CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ Assert.Equal(0, runner.ProbeCalls);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_RunnerFailureIsUnavailable()
+ {
+ var runner = new FakeWslCommandRunner((_, _, _) =>
+ Task.FromException(new InvalidOperationException("wsl unavailable")));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_DefaultPreservesRunnerBudgetForHealthySlowProbes()
+ {
+ var runner = new FakeWslCommandRunner(async (_, command, cancellationToken) =>
+ {
+ if (command.SequenceEqual(["/usr/bin/tailscale", "status", "--json"]))
+ // test-timing-exception: Deliberate probe latency crosses the former deadline; this is not a readiness wait.
+ await Task.Delay(TimeSpan.FromSeconds(5.1), cancellationToken);
+ return command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: 35225)
+ : command.FirstOrDefault() == "/bin/bash"
+ ? new WslCommandResult(0, "owned", "")
+ : RunningStatus();
+ });
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner);
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None)
+ .WaitAsync(StepTimeout);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Ready, result);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_TimeoutIsUnavailable()
+ {
+ var runner = new FakeWslCommandRunner(async (_, _, cancellationToken) =>
+ {
+ await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
+ throw new InvalidOperationException("unreachable");
+ });
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromMilliseconds(20));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_CallerCancellationPropagates()
+ {
+ var runner = new FakeWslCommandRunner(async (_, _, cancellationToken) =>
+ {
+ await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken);
+ throw new InvalidOperationException("unreachable");
+ });
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+
+ await Assert.ThrowsAnyAsync(() =>
+ verifier.VerifyAsync(ManagedRecord(), 18789, cancellation.Token));
+ }
+
+ [Fact]
+ public async Task StandardInputCompatibilityDefault_PropagatesPreCancellation()
+ {
+ IWslCommandRunner runner = new LegacyWslCommandRunner();
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+
+ await Assert.ThrowsAnyAsync(() =>
+ runner.RunInDistroWithStandardInputAsync(
+ "OpenClawGateway",
+ ["/bin/bash", "-s"],
+ "exit 0",
+ cancellation.Token));
+ }
+
+ [Fact]
+ public async Task ExplicitArgumentStandardInputCompatibilityDefault_FailsClosed()
+ {
+ IWslCommandRunner runner = new LegacyWslCommandRunner();
+
+ var result = await runner.RunWithStandardInputAsync(
+ ["-d", "OpenClawGateway", "--user", "root", "--", "/bin/bash", "-s"], "exit 0");
+
+ Assert.False(result.Success);
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+ await Assert.ThrowsAnyAsync(() => runner.RunWithStandardInputAsync(
+ ["-d", "OpenClawGateway", "--user", "root", "--", "/bin/bash", "-s"], "exit 0", cancellation.Token));
+ }
+
+ [Theory]
+ [InlineData("other.tail.example.", 18789, false, "NotReady")]
+ [InlineData("host.tail.example.", 19999, false, "NotReady")]
+ [InlineData("host.tail.example.", 18789, true, "NotReady")]
+ public async Task VerifyAsync_FailsClosedWhenEndpointOrServeRouteDoesNotMatch(
+ string dnsName,
+ int proxyPort,
+ bool funnelEnabled,
+ string expected)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ServeStatus(proxyPort: proxyPort, funnelEnabled: funnelEnabled)
+ : Status("Running", dnsName)));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(expected, result.ToString());
+ }
+
+ [Fact]
+ public async Task VerifyAsync_UnrelatedServeHostIsNotReady()
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ServeStatus(host: "other.tail.example")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.NotReady, result);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_AcceptsCurrentForegroundServeStatusShape()
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus()
+ : command.FirstOrDefault() == "/bin/bash"
+ ? new WslCommandResult(0, "owned", "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Ready, result);
+ Assert.Equal(5, runner.ProbeCalls);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_AcceptsManagedForegroundIngressOwnedByGatewayService()
+ {
+ const int managedIngressPort = 35225;
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: managedIngressPort)
+ : command.FirstOrDefault() == "/bin/bash"
+ ? new WslCommandResult(0, "owned", "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Ready, result);
+ Assert.Equal(5, runner.ProbeCalls);
+ Assert.Equal("/bin/bash", runner.Commands[3][0]);
+ Assert.Equal("-s", runner.Commands[3][1]);
+ Assert.Equal(
+ ["-d", "OpenClawGateway", "--", "/usr/bin/systemctl", "--user", "show", "openclaw-gateway", "-p", "MainPID", "--value"],
+ runner.HostArguments[2]);
+ Assert.Equal(["-d", "OpenClawGateway", "--user", "root", "--", "/bin/bash", "-s"], runner.HostArguments[3]);
+ Assert.Equal(runner.HostArguments[2], runner.HostArguments[4]);
+ Assert.Single(runner.StandardInputs);
+ var script = runner.StandardInputs[0];
+ Assert.DoesNotContain('\r', script);
+ Assert.Contains(":18789", script, StringComparison.Ordinal);
+ Assert.Contains(":35225", script, StringComparison.Ordinal);
+ Assert.Contains("/proc/$pid_before/cgroup", script, StringComparison.Ordinal);
+ Assert.Contains("--bg=false", script, StringComparison.Ordinal);
+ Assert.Contains("tailscale-route-owner.worker.js", script, StringComparison.Ordinal);
+ Assert.Contains("--openclaw-tailscale-route-owner", script, StringComparison.Ordinal);
+ Assert.Contains("/proc/$matched_pid/stat", script, StringComparison.Ordinal);
+ Assert.Contains("candidate_count\" -eq 1", script, StringComparison.Ordinal);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_RejectsForegroundIngressNotOwnedByGatewayService()
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: 35225)
+ : command.FirstOrDefault() == "/bin/bash"
+ ? new WslCommandResult(0, "not-owned", "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.NotReady, result);
+ }
+
+ [Theory]
+ [InlineData("plain", "Ready")]
+ [InlineData("node-options", "Ready")]
+ [InlineData("trailing-argument", "NotReady")]
+ [InlineData("wrong-worker", "NotReady")]
+ [InlineData("wrong-marker", "NotReady")]
+ [InlineData("wrong-payload", "NotReady")]
+ [InlineData("wrong-parent", "NotReady")]
+ [InlineData("wrong-executable", "NotReady")]
+ [InlineData("wrong-cgroup", "NotReady")]
+ [InlineData("duplicate-owner", "NotReady")]
+ [InlineData("sudo-route", "Ready")]
+ [InlineData("sudo-trailing-argument", "NotReady")]
+ [InlineData("sudo-wrong-parent", "NotReady")]
+ public async Task VerifyAsync_ExecutesForegroundOwnershipProbe(string scenario, string expected)
+ {
+ using var fixture = new ManagedIngressProcessFixture(scenario);
+ FakeWslCommandRunner? runner = null;
+ runner = new FakeWslCommandRunner((_, command, cancellationToken) =>
+ command.Contains("serve", StringComparer.Ordinal)
+ ? Task.FromResult(ForegroundServeStatus(proxyPort: 35225))
+ : command.FirstOrDefault() == "/bin/bash"
+ ? fixture.RunAsync(runner!.StandardInputs.Single(), cancellationToken, runner.PrivilegedStandardInput)
+ : Task.FromResult(RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, StepTimeout);
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(expected, result.ToString());
+ }
+
+ [Fact]
+ public async Task VerifyAsync_ServiceRestartDuringPrivilegedInspectionIsUnavailable()
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: 35225)
+ : command.FirstOrDefault() == "/bin/bash"
+ ? new WslCommandResult(0, "owned", "")
+ : RunningStatus()));
+ runner.ServiceResults.Enqueue(new WslCommandResult(0, "101\n", ""));
+ runner.ServiceResults.Enqueue(new WslCommandResult(0, "202\n", ""));
+
+ var result = await new GatewayTailscaleAuthLiveVerifier(runner).VerifyAsync(
+ ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ Assert.Equal(runner.HostArguments[2], runner.HostArguments[4]);
+ Assert.DoesNotContain("root", runner.HostArguments[4]);
+ }
+
+ [Theory]
+ [InlineData("0")]
+ [InlineData("-1")]
+ [InlineData("2147483648")]
+ [InlineData("101\n202")]
+ [InlineData("101; exit 0")]
+ public async Task VerifyAsync_InvalidServiceProcessDoesNotDispatchPrivilegedInspection(string processId)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: 35225)
+ : RunningStatus()));
+ runner.ServiceResults.Enqueue(new WslCommandResult(0, processId, ""));
+
+ var result = await new GatewayTailscaleAuthLiveVerifier(runner).VerifyAsync(
+ ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ Assert.False(runner.PrivilegedStandardInput);
+ Assert.Empty(runner.StandardInputs);
+ }
+
+ [Theory]
+ [InlineData(0, "unavailable")]
+ [InlineData(0, "unexpected")]
+ [InlineData(1, "")]
+ public async Task VerifyAsync_FailsClosedWhenManagedIngressOwnershipIsUnavailable(
+ int exitCode,
+ string output)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: 35225)
+ : command.FirstOrDefault() == "/bin/bash"
+ ? new WslCommandResult(exitCode, output, "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_RejectsManagedForegroundIngressWhenFunnelIsEnabled()
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: 35225, funnelEnabled: true)
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.NotReady, result);
+ Assert.Equal(2, runner.ProbeCalls);
+ }
+
+ [Fact]
+ public async Task VerifyAsync_RejectsForegroundLocalhostProxyOutsideCoreContract()
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ForegroundServeStatus(proxyPort: 35225, proxyHost: "localhost")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.NotReady, result);
+ Assert.Equal(2, runner.ProbeCalls);
+ }
+
+ [Theory]
+ [MemberData(nameof(UnsafeForegroundServeStatuses))]
+ public async Task VerifyAsync_FailsClosedForUnsafeForegroundServeStatus(
+ string foreground,
+ string expected)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? new WslCommandResult(0, $"{{\"Foreground\":{foreground}}}", "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(expected, result.ToString());
+ Assert.Equal(2, runner.ProbeCalls);
+ }
+
+ [Theory]
+ [InlineData(8443, "", "NotReady")]
+ [InlineData(443, "/unrelated", "NotReady")]
+ [InlineData(443, "/app/..", "NotReady")]
+ [InlineData(443, "\\backend", "NotReady")]
+ [InlineData(443, "?target=other", "NotReady")]
+ [InlineData(443, "#fragment", "NotReady")]
+ public async Task VerifyAsync_RequiresExactPublicEndpointAndCoreRootProxy(
+ int endpointPort,
+ string proxySuffix,
+ string expected)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ServeStatus(endpointPort: endpointPort, proxySuffix: proxySuffix)
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(expected, result.ToString());
+ }
+
+ [Theory]
+ [InlineData("user:password@")]
+ [InlineData("@")]
+ public async Task VerifyAsync_RejectsProxyUserInfo(string proxyUserInfo)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? ServeStatus(proxyUserInfo: proxyUserInfo)
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.NotReady, result);
+ }
+
+ [Theory]
+ [InlineData("http://host.tail.example:443")]
+ [InlineData("https://user@host.tail.example:443")]
+ [InlineData("https://@host.tail.example:443")]
+ [InlineData("https://host.tail.example:443/path")]
+ [InlineData("https://host.tail.example:443/app/..")]
+ [InlineData("https://host.tail.example:443\\app")]
+ [InlineData("https://host.tail.example:443?query=1")]
+ [InlineData("https://host.tail.example:443#fragment")]
+ public async Task VerifyAsync_RejectsNonCanonicalServeEndpoint(string endpoint)
+ {
+ var endpointJson = JsonSerializer.Serialize(endpoint);
+ var serveJson = $$"""
+ {
+ "Web": {
+ {{endpointJson}}: {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:18789" } }
+ }
+ }
+ }
+ """;
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? new WslCommandResult(0, serveJson, "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.NotReady, result);
+ }
+
+ [Theory]
+ [InlineData("[]")]
+ [InlineData("null")]
+ [InlineData("{\"Web\":[]}")]
+ [InlineData("{\"Web\":{\"host.tail.example:443\":[]}}")]
+ public async Task VerifyAsync_StructurallyUnexpectedServeStatusIsUnavailable(string serveJson)
+ {
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? new WslCommandResult(0, serveJson, "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ }
+
+ [Theory]
+ [InlineData("[]")]
+ [InlineData("42")]
+ [InlineData("{\"Proxy\":42}")]
+ public async Task VerifyAsync_MalformedSiblingHandlerIsUnavailable(string malformedHandler)
+ {
+ var serveJson = $$"""
+ {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": {
+ "/": { "Proxy": "http://127.0.0.1:18789" },
+ "/bad": {{malformedHandler}}
+ }
+ }
+ }
+ }
+ """;
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? new WslCommandResult(0, serveJson, "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.Unavailable, result);
+ }
+
+ [Theory]
+ [InlineData("\"AllowFunnel\": false, \"Funnel\": true", "NotReady")]
+ [InlineData("\"AllowFunnel\": 42", "Unavailable")]
+ [InlineData("\"Funnel\": [false, {\"legacy\": true}]", "NotReady")]
+ public async Task VerifyAsync_EvaluatesEveryFunnelAliasAndRejectsUnknownShapes(
+ string funnelProperties,
+ string expected)
+ {
+ var serveJson = $$"""
+ {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:18789" } }
+ }
+ },
+ {{funnelProperties}}
+ }
+ """;
+ var runner = new FakeWslCommandRunner((_, command, _) => Task.FromResult(
+ command.Contains("serve", StringComparer.Ordinal)
+ ? new WslCommandResult(0, serveJson, "")
+ : RunningStatus()));
+ var verifier = new GatewayTailscaleAuthLiveVerifier(runner, TimeSpan.FromSeconds(1));
+
+ var result = await verifier.VerifyAsync(ManagedRecord(), 18789, CancellationToken.None);
+
+ Assert.Equal(expected, result.ToString());
+ }
+
+ public static TheoryData StatusResults => new()
+ {
+ { RunningStatus(), "NotReady", 2 },
+ { Status("NeedsLogin", "host.tail.example."), "NotReady", 1 },
+ { Status("Stopped", "host.tail.example."), "NotReady", 1 },
+ { Status("Running", ""), "NotReady", 1 },
+ { new WslCommandResult(0, "{}", ""), "NotReady", 1 },
+ { new WslCommandResult(0, "not-json", ""), "Unavailable", 1 },
+ { new WslCommandResult(1, "", "tailscaled unavailable"), "Unavailable", 1 },
+ };
+
+ public static TheoryData UnsafeForegroundServeStatuses => new()
+ {
+ { "[]", "Unavailable" },
+ { "{\"config-id\":[]}", "Unavailable" },
+ {
+ """
+ {
+ "config-id": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:18789" } }
+ }
+ },
+ "AllowFunnel": true
+ }
+ }
+ """,
+ "NotReady"
+ },
+ {
+ """
+ {
+ "gateway": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:18789" } }
+ }
+ }
+ },
+ "funnel": { "AllowFunnel": true }
+ }
+ """,
+ "NotReady"
+ },
+ {
+ """
+ {
+ "gateway": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:18789" } }
+ }
+ }
+ },
+ "malformed": []
+ }
+ """,
+ "Unavailable"
+ },
+ {
+ """
+ {
+ "first": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:35225" } }
+ }
+ }
+ },
+ "second": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:35225" } }
+ }
+ }
+ }
+ }
+ """,
+ "Unavailable"
+ },
+ {
+ """
+ {
+ "first": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:35225" } }
+ }
+ }
+ },
+ "second": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:35226" } }
+ }
+ }
+ }
+ }
+ """,
+ "Unavailable"
+ },
+ {
+ """
+ {
+ "first": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:35225" } }
+ }
+ }
+ },
+ "second": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://10.0.0.1:35226" } }
+ }
+ }
+ }
+ }
+ """,
+ "NotReady"
+ },
+ {
+ """
+ {
+ "literal": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:35225" } }
+ }
+ }
+ },
+ "localhost": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://localhost:35225" } }
+ }
+ }
+ }
+ }
+ """,
+ "NotReady"
+ },
+ {
+ """
+ {
+ "literal": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://127.0.0.1:35225" } }
+ }
+ }
+ },
+ "localhost": {
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://localhost:35226" } }
+ }
+ }
+ }
+ }
+ """,
+ "NotReady"
+ },
+ };
+
+ private static WslCommandResult RunningStatus() => Status("Running", "host.tail.example.");
+
+ private static WslCommandResult ServeStatus(
+ string host = "host.tail.example",
+ int endpointPort = 443,
+ int proxyPort = 18789,
+ string proxySuffix = "",
+ string proxyUserInfo = "",
+ bool funnelEnabled = false)
+ {
+ var proxyJson = JsonSerializer.Serialize(
+ $"http://{proxyUserInfo}127.0.0.1:{proxyPort}{proxySuffix}");
+ return new(
+ 0,
+ $$"""
+ {
+ "Web": {
+ "{{host}}:{{endpointPort}}": {
+ "Handlers": { "/": { "Proxy": {{proxyJson}} } }
+ }
+ },
+ "AllowFunnel": { "{{host}}:{{endpointPort}}": {{funnelEnabled.ToString().ToLowerInvariant()}} }
+ }
+ """,
+ "");
+ }
+
+ private static WslCommandResult ForegroundServeStatus(
+ int proxyPort = 18789,
+ bool funnelEnabled = false,
+ string proxyHost = "127.0.0.1") =>
+ new(
+ 0,
+ $$"""
+ {
+ "Foreground": {
+ "75980230dda8b0e0": {
+ "TCP": { "443": { "HTTPS": true } },
+ "Web": {
+ "host.tail.example:443": {
+ "Handlers": { "/": { "Proxy": "http://{{proxyHost}}:{{proxyPort}}" } }
+ }
+ },
+ "AllowFunnel": {{funnelEnabled.ToString().ToLowerInvariant()}}
+ }
+ }
+ }
+ """,
+ "");
+
+ private static WslCommandResult Status(string backendState, string dnsName) =>
+ new(
+ 0,
+ $"{{\"BackendState\":\"{backendState}\",\"Self\":{{\"DNSName\":\"{dnsName}\"}}}}",
+ "");
+
+ private static GatewayRecord ManagedRecord() => new()
+ {
+ Id = "gateway-1",
+ Url = "wss://host.tail.example",
+ IsLocal = true,
+ SetupManagedDistroName = "OpenClawGateway",
+ TrustTailscaleAuth = true,
+ };
+
+ private sealed class ManagedIngressProcessFixture : IDisposable
+ {
+ private readonly string _root = Path.Combine(Path.GetTempPath(), "openclaw-ingress-" + Guid.NewGuid().ToString("N"));
+
+ public ManagedIngressProcessFixture(string scenario)
+ {
+ Directory.CreateDirectory(_root);
+ const string node = "/usr/bin/node";
+ const string cgroup = "/user.slice/openclaw-gateway.service";
+ WriteProcess(101, 1, node, cgroup, scenario == "node-options"
+ ? [node, "--max-old-space-size=12043", "--stack-size=984", "/gateway/dist/index.js", "gateway"]
+ : [node, "/gateway/dist/index.js", "gateway"]);
+ string[] workerArguments = scenario == "node-options"
+ ? [node, "--max-old-space-size=12043", "--stack-size=984"]
+ : [node];
+ var sudoRoute = scenario.StartsWith("sudo-", StringComparison.Ordinal);
+ workerArguments = [.. workerArguments,
+ scenario == "wrong-worker" ? "/other/worker.js" : "/gateway/dist/infra/tailscale-route-owner.worker.js",
+ scenario == "wrong-marker" ? "--other-owner" : "--openclaw-tailscale-route-owner",
+ scenario == "wrong-payload" ? "{\"argv\":[\"/usr/bin/tailscale\",\"serve\",\"--yes\",\"--bg=false\",\"19999\"]}"
+ : sudoRoute
+ ? "{\"argv\":[\"sudo\",\"-n\",\"/usr/bin/tailscale\",\"serve\",\"--yes\",\"--bg=false\",\"35225\"]}"
+ : "{\"argv\":[\"/usr/bin/tailscale\",\"serve\",\"--yes\",\"--bg=false\",\"35225\"]}"];
+ if (scenario == "trailing-argument")
+ workerArguments = [.. workerArguments, "extra"];
+ WriteProcess(102, scenario == "wrong-parent" ? 999 : 101,
+ scenario == "wrong-executable" ? "/other/node" : node,
+ scenario == "wrong-cgroup" ? "/other.service" : cgroup, workerArguments);
+ string[] routeArguments = ["/usr/bin/tailscale", "serve", "--yes", "--bg=false", "35225"];
+ if (sudoRoute)
+ {
+ string[] sudoArguments = ["sudo", "-n", .. routeArguments];
+ if (scenario == "sudo-trailing-argument")
+ sudoArguments = [.. sudoArguments, "extra"];
+ WriteProcess(103, scenario == "sudo-wrong-parent" ? 999 : 102, "/usr/bin/sudo", cgroup, sudoArguments);
+ WriteProcess(104, 103, "/usr/bin/tailscale", cgroup, routeArguments);
+ File.WriteAllText(Path.Combine(_root, "privileged"), "yes");
+ }
+ else
+ WriteProcess(103, 102, "/usr/bin/tailscale", cgroup, routeArguments);
+ if (scenario == "duplicate-owner")
+ WriteProcess(104, 102, "/usr/bin/tailscale", cgroup, routeArguments);
+ File.WriteAllText(Path.Combine(_root, "listeners"),
+ "LISTEN 0 128 127.0.0.1:18789 0.0.0.0:* users:((\"node\",pid=101,fd=1))\n" +
+ "LISTEN 0 128 127.0.0.1:35225 0.0.0.0:* users:((\"node\",pid=101,fd=2))\n");
+ }
+
+ private void WriteProcess(int pid, int parent, string executable, string cgroup, string[] arguments)
+ {
+ var directory = Path.Combine(_root, pid.ToString());
+ Directory.CreateDirectory(directory);
+ File.WriteAllText(Path.Combine(directory, "cmdline"), string.Join('\0', arguments) + '\0', new UTF8Encoding(false));
+ File.WriteAllText(Path.Combine(directory, "exe"), executable);
+ File.WriteAllText(Path.Combine(directory, "cgroup"), "0::" + cgroup + "\n");
+ File.WriteAllText(Path.Combine(directory, "status"), $"PPid:\t{parent}\n");
+ File.WriteAllText(Path.Combine(directory, "stat"), string.Join(' ', Enumerable.Repeat("1", 21).Append(pid.ToString())));
+ }
+
+ public async Task RunAsync(
+ string script, CancellationToken cancellationToken, bool privilegedInspection = false)
+ {
+ var bash = OperatingSystem.IsWindows()
+ ? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Git", "bin", "bash.exe")
+ : "/bin/bash";
+ Assert.True(File.Exists(bash), $"Ownership probe regression requires Bash at {bash}.");
+ var start = new ProcessStartInfo(bash)
+ {
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardInput = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ };
+ start.ArgumentList.Add("-s");
+ var root = _root.Replace('\\', '/');
+ if (OperatingSystem.IsWindows())
+ root = "/" + char.ToLowerInvariant(root[0]) + root[2..];
+ var fixtureScript = "fixture_proc='" + root.Replace("'", "'\\''") + "'\n" +
+ "fixture_systemctl() { printf 101; }\n" +
+ "fixture_ss() { test -r \"$fixture_proc/listeners\" || return 1; printf '%s\\n' \"$(< \"$fixture_proc/listeners\")\"; }\n" +
+ "fixture_privileged=" + (privilegedInspection ? "yes" : "no") + "\n" +
+ "fixture_readlink() { if test -f \"$fixture_proc/privileged\" && test \"$fixture_privileged\" != yes; then case \"$1\" in */103/exe|*/104/exe) return 1;; esac; fi; test -r \"$1\" || return 1; printf '%s' \"$(< \"$1\")\"; }\n" +
+ script.Replace("for proc in /proc/[0-9]*; do", "for proc in \"$fixture_proc\"/[0-9]*; do", StringComparison.Ordinal)
+ .Replace("/proc/", "$fixture_proc/", StringComparison.Ordinal)
+ .Replace("/usr/bin/systemctl", "fixture_systemctl", StringComparison.Ordinal)
+ .Replace("/usr/bin/ss", "fixture_ss", StringComparison.Ordinal)
+ .Replace("/usr/bin/readlink -f", "fixture_readlink", StringComparison.Ordinal);
+ using var process = Process.Start(start)!;
+ var output = process.StandardOutput.ReadToEndAsync(cancellationToken);
+ var error = process.StandardError.ReadToEndAsync(cancellationToken);
+ try
+ {
+ await process.StandardInput.WriteAsync(fixtureScript.AsMemory(), cancellationToken);
+ process.StandardInput.Close();
+ await process.WaitForExitAsync(cancellationToken);
+ return new WslCommandResult(process.ExitCode, await output, await error);
+ }
+ finally
+ {
+ if (!process.HasExited)
+ process.Kill(entireProcessTree: true);
+ }
+ }
+
+ public void Dispose() => Directory.Delete(_root, recursive: true);
+ }
+
+ private sealed class FakeWslCommandRunner(
+ Func, CancellationToken, Task> runInDistro)
+ : IWslCommandRunner
+ {
+ public int ProbeCalls { get; private set; }
+ public string? DistroName { get; private set; }
+ public List> Commands { get; } = [];
+ public List> HostArguments { get; } = [];
+ public List StandardInputs { get; } = [];
+ public bool PrivilegedStandardInput { get; private set; }
+ public Queue ServiceResults { get; } = [];
+
+ public Task RunInDistroAsync(
+ string name,
+ IReadOnlyList command,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null,
+ string? standardInput = null)
+ {
+ if (standardInput is not null)
+ StandardInputs.Add(standardInput);
+ ProbeCalls++;
+ DistroName = name;
+ Commands.Add(command);
+ HostArguments.Add(["-d", name, "--", .. command]);
+ if (command.FirstOrDefault() == "/usr/bin/systemctl")
+ return Task.FromResult(ServiceResults.Count > 0 ? ServiceResults.Dequeue() : new WslCommandResult(0, "101\n", ""));
+ return runInDistro(name, command, cancellationToken);
+ }
+
+ public Task RunInDistroWithStandardInputAsync(
+ string name,
+ IReadOnlyList command,
+ string standardInput,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null)
+ {
+ return RunInDistroAsync(name, command, cancellationToken, environment, standardInput);
+ }
+
+ public Task RunAsync(
+ IReadOnlyList arguments,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null)
+ {
+ HostArguments.Add(arguments);
+ Assert.True(arguments.Count >= 6);
+ Assert.Equal("-d", arguments[0]);
+ Assert.Equal("--user", arguments[2]);
+ Assert.Equal("root", arguments[3]);
+ Assert.Equal("--", arguments[4]);
+ ProbeCalls++;
+ DistroName = arguments[1];
+ var command = arguments.Skip(5).ToArray();
+ Commands.Add(command);
+ return runInDistro(DistroName, command, cancellationToken);
+ }
+
+ public Task RunWithStandardInputAsync(
+ IReadOnlyList arguments,
+ string standardInput,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null)
+ {
+ StandardInputs.Add(standardInput);
+ PrivilegedStandardInput = arguments.Count >= 6 && arguments[2] == "--user" && arguments[3] == "root";
+ return RunAsync(arguments, cancellationToken, environment);
+ }
+
+ public Task> ListDistrosAsync(
+ CancellationToken cancellationToken = default) =>
+ throw new NotSupportedException();
+
+ public Task TerminateDistroAsync(
+ string name,
+ CancellationToken cancellationToken = default) =>
+ throw new NotSupportedException();
+
+ public Task UnregisterDistroAsync(
+ string name,
+ CancellationToken cancellationToken = default) =>
+ throw new NotSupportedException();
+ }
+
+ private sealed class LegacyWslCommandRunner : IWslCommandRunner
+ {
+ public Task RunAsync(
+ IReadOnlyList arguments,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null) =>
+ throw new NotSupportedException();
+
+ public Task> ListDistrosAsync(
+ CancellationToken cancellationToken = default) =>
+ throw new NotSupportedException();
+
+ public Task TerminateDistroAsync(
+ string name,
+ CancellationToken cancellationToken = default) =>
+ throw new NotSupportedException();
+
+ public Task UnregisterDistroAsync(
+ string name,
+ CancellationToken cancellationToken = default) =>
+ throw new NotSupportedException();
+
+ public Task RunInDistroAsync(
+ string name,
+ IReadOnlyList command,
+ CancellationToken cancellationToken = default,
+ IReadOnlyDictionary? environment = null,
+ string? standardInput = null) =>
+ throw new NotSupportedException();
+ }
+}
diff --git a/tests/OpenClaw.Connection.Tests/GatewayTailscaleAuthUpgradeTests.cs b/tests/OpenClaw.Connection.Tests/GatewayTailscaleAuthUpgradeTests.cs
new file mode 100644
index 0000000000..53bcf975be
--- /dev/null
+++ b/tests/OpenClaw.Connection.Tests/GatewayTailscaleAuthUpgradeTests.cs
@@ -0,0 +1,1124 @@
+using System.Text.Json;
+using OpenClaw.Shared;
+using OpenClaw.TestSupport;
+
+namespace OpenClaw.Connection.Tests;
+
+public sealed class GatewayTailscaleAuthUpgradeTests : IDisposable
+{
+ private static readonly TimeSpan StepTimeout =
+ int.TryParse(Environment.GetEnvironmentVariable("OPENCLAW_TEST_GATEWAY_STEP_TIMEOUT_SECONDS"), out var seconds) && seconds > 0
+ ? TimeSpan.FromSeconds(seconds) : TimeSpan.FromSeconds(15);
+
+ private readonly TempDirectory _temp = new();
+
+ [Fact]
+ public async Task EnableAsync_PersistsRecordOnlyAfterCoreAcceptance()
+ {
+ var registry = CreateRegistry();
+ var client = new FakeConfigClient(Config(allowTailscale: false));
+ registry.Save();
+ bool? trustedBeforeAcceptance = null;
+ bool? couldRetryBeforeAcceptance = null;
+ client.BeforePatch = () =>
+ {
+ trustedBeforeAcceptance = registry.GetActive()!.TrustTailscaleAuth;
+ var beforeAcceptance = new GatewayRegistry(_temp.Path);
+ beforeAcceptance.Load();
+ couldRetryBeforeAcceptance = GatewayTailscaleAuthUpgradePolicy.CanOffer(beforeAcceptance.GetActive());
+ };
+ var service = new GatewayTailscaleAuthUpgradeService(
+ registry, new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready));
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.Succeeded, result.Outcome);
+ Assert.False(trustedBeforeAcceptance);
+ Assert.True(couldRetryBeforeAcceptance);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", registry.GetActive()!.SharedGatewayToken);
+ Assert.Equal(1, client.PatchCalls);
+ Assert.Equal("base-1", client.PatchBaseHash);
+ Assert.True(client.PatchedConfig!.Value
+ .GetProperty("gateway")
+ .GetProperty("auth")
+ .GetProperty("allowTailscale")
+ .GetBoolean());
+ Assert.False(client.PatchedConfig.Value.TryGetProperty("unrelated", out _));
+
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", reloaded.GetActive()!.SharedGatewayToken);
+ }
+
+ [Theory]
+ [InlineData("off", "UnsupportedTopology")]
+ [InlineData("serve", "IngressNotReady")]
+ public async Task EnableAsync_SetupBackgroundServe_DoesNotPatchOrPersistTrust(
+ string mode, string expectedOutcome)
+ {
+ var registry = CreateRegistry();
+ registry.Save();
+ var originalRegistry = File.ReadAllText(_temp.Combine("gateways.json"));
+ using var config = JsonDocument.Parse($$"""
+ {
+ "sourceConfig": {
+ "gateway": {
+ "port": 18789,
+ "bind": "loopback",
+ "auth": { "mode": "token", "token": "test-token-placeholder", "allowTailscale": false },
+ "tailscale": { "mode": "{{mode}}" },
+ "trustedProxies": ["127.0.0.1"]
+ }
+ },
+ "baseHash": "setup-config",
+ "configRevisionHash": "setup-config",
+ "appliedConfigHash": "setup-config"
+ }
+ """);
+ var client = new FakeConfigClient(config.RootElement.Clone());
+ var verifier = new GatewayTailscaleAuthLiveVerifier(new BackgroundServeCommandRunner());
+ var service = new GatewayTailscaleAuthUpgradeService(registry, verifier);
+
+ Assert.Equal(GatewayTailscaleAuthLiveState.NotReady,
+ await verifier.VerifyAsync(registry.GetActive()!, 18789, CancellationToken.None));
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(expectedOutcome, result.Outcome.ToString());
+ Assert.Equal(0, client.PatchCalls);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(originalRegistry, File.ReadAllText(_temp.Combine("gateways.json")));
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(GatewayTailscaleAuthUpgradePolicy.CanOffer(reloaded.GetActive()));
+ }
+
+ [Theory]
+ [InlineData(false, "not-ready")]
+ [InlineData(true, "not-ready")]
+ [InlineData(false, "unavailable")]
+ [InlineData(true, "unavailable")]
+ [InlineData(false, "exception")]
+ [InlineData(true, "exception")]
+ [InlineData(false, "missing-verifier")]
+ [InlineData(true, "missing-verifier")]
+ public async Task EnableAsync_UnverifiedIngress_DoesNotPatchOrChangeTrust(
+ bool previouslyTrusted, string probeResult)
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = previouslyTrusted });
+ registry.Save();
+ var originalRegistry = File.ReadAllText(_temp.Combine("gateways.json"));
+ var client = new FakeConfigClient(Config(allowTailscale: previouslyTrusted));
+ var verifier = probeResult == "missing-verifier" ? null : new FakeLiveVerifier(probeResult switch
+ {
+ "not-ready" => GatewayTailscaleAuthLiveState.NotReady,
+ "unavailable" => GatewayTailscaleAuthLiveState.Unavailable,
+ _ => (object)new IOException("probe failed"),
+ });
+ var service = new GatewayTailscaleAuthUpgradeService(registry, verifier);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.IngressNotReady, result.Outcome);
+ Assert.Equal(0, client.PatchCalls);
+ Assert.Equal(previouslyTrusted, registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(originalRegistry, File.ReadAllText(_temp.Combine("gateways.json")));
+ }
+
+ [Fact]
+ public async Task EnableAsync_CoreAlreadyEnabled_RequiresAcceptedIdempotentPatch()
+ {
+ var registry = CreateRegistry();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.Succeeded, result.Outcome);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.PatchCalls);
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.AlreadyEnabled,
+ (await service.EnableAsync("gateway-1", client, CancellationToken.None)).Outcome);
+ Assert.Equal(1, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task EnableAsync_PersistedMarkerRevalidatesLiveCoreState()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: false));
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.Succeeded, result.Outcome);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.ConfigRequests);
+ Assert.Equal(1, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task EnableAsync_PersistedMarkerAndLiveCoreStateReturnAlreadyEnabled()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.AlreadyEnabled, result.Outcome);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.ConfigRequests);
+ Assert.Equal(0, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task EnableAsync_PersistedMarkerDoesNotRequirePatchHashWhenCoreAllowsTailscale()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true, includeBaseHash: false));
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.AlreadyEnabled, result.Outcome);
+ Assert.Equal(0, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task EnableAsync_PersistedButUnappliedGrant_DoesNotReportAlreadyEnabled()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true, appliedRevision: "revision-old"))
+ {
+ PatchResult = new ConfigPatchResult { Ok = false, Error = "application pending" },
+ };
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.PatchRejected, result.Outcome);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", registry.GetActive()!.SharedGatewayToken);
+ }
+
+ [Fact]
+ public async Task EnableAsync_MissingBaseHash_FailsClosedBeforePatch()
+ {
+ var registry = CreateRegistry();
+ var client = new FakeConfigClient(Config(allowTailscale: false, includeBaseHash: false));
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.ConfigUnavailable, result.Outcome);
+ Assert.Equal(0, client.PatchCalls);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ }
+
+ [Fact]
+ public async Task EnableAsync_PatchRejected_LeavesRecordAndCredentialsUntouched()
+ {
+ var registry = CreateRegistry();
+ var client = new FakeConfigClient(Config(allowTailscale: false))
+ {
+ PatchResult = new ConfigPatchResult
+ {
+ Ok = false,
+ Error = "rejected",
+ IsGatewayRejection = true,
+ },
+ };
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.PatchRejected, result.Outcome);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", registry.GetActive()!.SharedGatewayToken);
+ }
+
+ [Theory]
+ [InlineData(false, "timeout")]
+ [InlineData(false, "exception")]
+ [InlineData(false, "rejection")]
+ [InlineData(true, "timeout")]
+ [InlineData(true, "exception")]
+ [InlineData(true, "rejection")]
+ public async Task EnableAsync_UnconfirmedPatch_PreservesExistingTrustAndNewOptInRetry(
+ bool previouslyTrusted, string failure)
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = previouslyTrusted });
+ registry.Save();
+ var originalRegistry = File.ReadAllText(_temp.Combine("gateways.json"));
+ var client = new FakeConfigClient(Config(allowTailscale: false))
+ {
+ PatchResult = new ConfigPatchResult
+ {
+ Ok = false,
+ Error = "unconfirmed patch",
+ IsGatewayRejection = failure == "rejection",
+ },
+ PatchError = failure == "exception" ? new IOException("response lost") : null,
+ };
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.PatchRejected, result.Outcome);
+ Assert.Equal(previouslyTrusted, registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", registry.GetActive()!.SharedGatewayToken);
+ Assert.Equal(originalRegistry, File.ReadAllText(_temp.Combine("gateways.json")));
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.Equal(!previouslyTrusted, GatewayTailscaleAuthUpgradePolicy.CanOffer(reloaded.GetActive()));
+ Assert.Equal(previouslyTrusted, reloaded.GetActive()!.TrustTailscaleAuth);
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task EnableAsync_ConfigTimeoutBeforeDispatchPreservesRetryAndTrust(bool previouslyTrusted)
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = previouslyTrusted });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: false))
+ {
+ ConfigError = new TimeoutException("config read timed out"),
+ };
+ var result = await CreateReadyService(registry).EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.ConfigUnavailable, result.Outcome);
+ Assert.Equal(0, client.PatchCalls);
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.Equal(previouslyTrusted, reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(!previouslyTrusted, GatewayTailscaleAuthUpgradePolicy.CanOffer(reloaded.GetActive()));
+ }
+
+ [Theory]
+ [InlineData(false)]
+ [InlineData(true)]
+ public async Task EnableAsync_WithoutAdminScope_DoesNotRequestPatchOrPersistMarker(bool hasWriteScope)
+ {
+ var registry = CreateRegistry();
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: false))
+ {
+ Scopes = hasWriteScope ? ["operator.read", "operator.write"] : ["operator.read"],
+ };
+ var service = new GatewayTailscaleAuthUpgradeService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.MissingConfigScope, result.Outcome);
+ Assert.Equal(0, client.ConfigRequests);
+ Assert.Equal(0, client.PatchCalls);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.False(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", reloaded.GetActive()!.SharedGatewayToken);
+ }
+
+ [Fact]
+ public async Task EnableAsync_SaveFailure_RestoresInMemoryMarker()
+ {
+ var registry = CreateRegistry(new FailOnSecondWriteFileSystem());
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.PersistenceFailed, result.Outcome);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", registry.GetActive()!.SharedGatewayToken);
+ Assert.Equal(1, client.PatchCalls);
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(GatewayTailscaleAuthUpgradePolicy.CanOffer(reloaded.GetActive()));
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.Succeeded,
+ (await service.EnableAsync("gateway-1", client, CancellationToken.None)).Outcome);
+ reloaded.Load();
+ Assert.True(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(2, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_CoreStillAllowsTailscale_KeepsMarkerAndReturnsTrue()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.True(trusted);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.ConfigRequests);
+ Assert.Equal(0, client.PatchCalls);
+ Assert.Equal(1, liveVerifier.Calls);
+ Assert.Equal(18789, liveVerifier.LastGatewayPort);
+ }
+
+ [Theory]
+ [InlineData("sourceConfig")]
+ [InlineData("resolved")]
+ public async Task RevalidateAsync_UsesResolvedSourceForGrantAndProbePort(string sourceProperty)
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ using var response = JsonDocument.Parse($$"""
+ {
+ "parsed": { "gateway": { "port": 18789, "auth": { "allowTailscale": false } } },
+ "{{sourceProperty}}": { "gateway": { "port": 19876, "auth": { "allowTailscale": true } } },
+ "hash": "root-and-includes-cas",
+ "configRevisionHash": "revision-new",
+ "appliedConfigHash": "revision-new"
+ }
+ """);
+ var client = new FakeConfigClient(response.RootElement.Clone());
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.True(trusted);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(19876, liveVerifier.LastGatewayPort);
+ Assert.Equal(1, liveVerifier.Calls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_MissingResolvedSourcePreservesMarkerAndSkipsProbe()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ using var response = JsonDocument.Parse("""
+ {
+ "parsed": { "gateway": { "port": 19876, "auth": { "allowTailscale": true } } },
+ "configRevisionHash": "revision-new",
+ "appliedConfigHash": "revision-new"
+ }
+ """);
+ var client = new FakeConfigClient(response.RootElement.Clone());
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(0, liveVerifier.Calls);
+ }
+
+ [Fact]
+ public async Task EnableAsync_UsesResolvedSourceAndPreservesCoreCasHash()
+ {
+ var registry = CreateRegistry();
+ using var response = JsonDocument.Parse("""
+ {
+ "parsed": { "gateway": { "auth": { "allowTailscale": true } } },
+ "sourceConfig": { "gateway": { "auth": { "allowTailscale": false }, "tailscale": { "mode": "serve" } } },
+ "hash": "root-and-includes-cas",
+ "configRevisionHash": "revision-new",
+ "appliedConfigHash": "revision-new"
+ }
+ """);
+ var client = new FakeConfigClient(response.RootElement.Clone());
+ var service = CreateReadyService(registry);
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.Succeeded, result.Outcome);
+ Assert.Equal(1, client.PatchCalls);
+ Assert.Equal("root-and-includes-cas", client.PatchBaseHash);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_OmittedGatewayPort_UsesCoreDefault()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true, includeGatewayPort: false));
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.True(trusted);
+ Assert.Equal(18789, liveVerifier.LastGatewayPort);
+ }
+
+ [Theory]
+ [InlineData("parsed", "\"configRevisionHash\":\"revision-new\",\"appliedConfigHash\":\"revision-old\"")]
+ [InlineData("config", "\"configRevisionHash\":\"revision-new\",\"appliedConfigHash\":\"revision-old\"")]
+ [InlineData("parsed", "\"configRevisionHash\":\"revision-new\",\"appliedConfigHash\":null")]
+ [InlineData("parsed", "\"configRevisionHash\":null,\"appliedConfigHash\":null")]
+ [InlineData("parsed", "\"configRevisionHash\":\"revision-new\"")]
+ [InlineData("parsed", "\"appliedConfigHash\":\"revision-new\"")]
+ [InlineData("parsed", "\"configRevisionHash\":\"\",\"appliedConfigHash\":\"\"")]
+ [InlineData("parsed", "\"configRevisionHash\":true,\"appliedConfigHash\":true")]
+ [InlineData("parsed", "\"configRevisionHash\":\"revision-new\",\"appliedConfigHash\":\"REVISION-NEW\"")]
+ [InlineData("parsed", "\"hash\":\"revision-new\",\"appliedConfigHash\":\"revision-new\"")]
+ public async Task RevalidateAsync_UnprovenAppliedRevision_PreservesMarkerAndCredential(
+ string documentProperty,
+ string revisionProperties)
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ using var response = JsonDocument.Parse($$"""
+ {
+ "{{documentProperty}}": { "gateway": { "auth": { "allowTailscale": true } } },
+ "sourceConfig": { "gateway": { "auth": { "allowTailscale": true } } },
+ {{revisionProperties}}
+ }
+ """);
+ var client = new FakeConfigClient(response.RootElement.Clone());
+ var service = new GatewayTailscaleAuthUpgradeService(
+ registry, new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready));
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", reloaded.GetActive()!.SharedGatewayToken);
+ }
+
+ [Fact]
+ public async Task EnableAsync_AmbiguousAdoptionCanRetryAfterReloadBeforeAppliedRevisionConverges()
+ {
+ var registry = CreateRegistry();
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: false))
+ {
+ PatchResult = new ConfigPatchResult { Ok = false, Error = "response lost" },
+ };
+ var service = CreateReadyService(registry);
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.PatchRejected, result.Outcome);
+
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(GatewayTailscaleAuthUpgradePolicy.CanOffer(reloaded.GetActive()));
+ service = CreateReadyService(reloaded);
+ client.ConfigResponse = Config(allowTailscale: true, appliedRevision: "revision-old");
+ client.PatchResult = new ConfigPatchResult { Ok = true };
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.Succeeded,
+ (await service.EnableAsync("gateway-1", client, CancellationToken.None)).Outcome);
+ var pending = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+ client.ConfigResponse = Config(allowTailscale: true);
+ var applied = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(pending);
+ Assert.True(applied);
+ Assert.True(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", reloaded.GetActive()!.SharedGatewayToken);
+ Assert.Equal(2, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_UnappliedDisableRetainsMarkerUntilApplied()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: false, appliedRevision: "revision-old"));
+ var service = new GatewayTailscaleAuthUpgradeService(registry);
+
+ Assert.False(await service.RevalidateAsync("gateway-1", client, CancellationToken.None));
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(reloaded.GetActive()!.TrustTailscaleAuth);
+ client.ConfigResponse = Config(allowTailscale: false);
+ Assert.False(await service.RevalidateAsync("gateway-1", client, CancellationToken.None));
+ reloaded.Load();
+ Assert.False(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", reloaded.GetActive()!.SharedGatewayToken);
+ }
+
+ [Theory]
+ [InlineData("0")]
+ [InlineData("65536")]
+ [InlineData("\"18789\"")]
+ public async Task RevalidateAsync_InvalidExplicitGatewayPort_FailsClosed(string gatewayPort)
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(ConfigWithGatewayPort(gatewayPort));
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.Equal(0, liveVerifier.Calls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_CoreAllowsWithoutLiveVerifier_PreservesMarkerAndTokenAndReturnsFalse()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var service = new GatewayTailscaleAuthUpgradeService(registry);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", registry.GetActive()!.SharedGatewayToken);
+ Assert.Equal(1, client.ConfigRequests);
+
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", reloaded.GetActive()!.SharedGatewayToken);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_CoreAllowsButLiveForwardedIdentityIsUnavailable_KeepsMarkerAndReturnsFalse()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.NotReady);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.ConfigRequests);
+ Assert.Equal(1, liveVerifier.Calls);
+
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.True(reloaded.GetActive()!.TrustTailscaleAuth);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_LiveVerifierFailure_KeepsMarkerAndReturnsFalse()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var liveVerifier = new FakeLiveVerifier(new InvalidOperationException("live probe unavailable"));
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, liveVerifier.Calls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_LiveVerifierRecovery_ReturnsTrueWithoutReissuingMarker()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var liveVerifier = new FakeLiveVerifier(
+ GatewayTailscaleAuthLiveState.Unavailable,
+ GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var unavailable = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+ var recovered = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(unavailable);
+ Assert.True(recovered);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(2, client.ConfigRequests);
+ Assert.Equal(2, liveVerifier.Calls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_ConfigFailurePreservesMarkerAndSkipsLiveVerifier()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: true))
+ {
+ ConfigError = new InvalidOperationException("config unavailable"),
+ };
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.True(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.ConfigRequests);
+ Assert.Equal(0, liveVerifier.Calls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_OmittedExplicitGrantClearsMarker()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(ImplicitServeConfig());
+ var service = new GatewayTailscaleAuthUpgradeService(registry);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.ConfigRequests);
+ Assert.Equal(0, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_CoreDisablesTailscale_ClearsPersistedMarkerAndReturnsFalse()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: false));
+ var liveVerifier = new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready);
+ var service = new GatewayTailscaleAuthUpgradeService(registry, liveVerifier);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal("test-token-placeholder", registry.GetActive()!.SharedGatewayToken);
+ Assert.Equal(0, client.PatchCalls);
+ Assert.Equal(0, liveVerifier.Calls);
+
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.False(reloaded.GetActive()!.TrustTailscaleAuth);
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_CallerCancellationRemainsCancellation()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = true });
+ var client = new FakeConfigClient(Config(allowTailscale: true)) { EmitConfig = false };
+ var service = new GatewayTailscaleAuthUpgradeService(registry);
+ using var cancellation = new CancellationTokenSource();
+ cancellation.Cancel();
+
+ await Assert.ThrowsAnyAsync(() =>
+ service.RevalidateAsync("gateway-1", client, cancellation.Token));
+ }
+
+ [Fact]
+ public async Task EnableAsync_CancellationAfterConfigReadDoesNotMutateOrPatch()
+ {
+ using var cancellation = new CancellationTokenSource();
+ var registry = CreateRegistry();
+ var client = new FakeConfigClient(Config(allowTailscale: false))
+ {
+ AfterConfig = cancellation.Cancel,
+ };
+ var service = new GatewayTailscaleAuthUpgradeService(registry);
+
+ await Assert.ThrowsAnyAsync(() =>
+ service.EnableAsync("gateway-1", client, cancellation.Token));
+
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(0, client.PatchCalls);
+ }
+
+ [Fact]
+ public async Task EnableAsync_ConnectionChangeAfterConfigReadDoesNotDispatchPatch()
+ {
+ var registry = CreateRegistry();
+ var client = new FakeConfigClient(Config(allowTailscale: false));
+ client.AfterConfig = () => client.SessionMutationConnectionEpoch = 2;
+ var service = new GatewayTailscaleAuthUpgradeService(
+ registry, new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready));
+
+ var result = await service.EnableAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.Equal(GatewayTailscaleAuthUpgradeOutcome.PatchRejected, result.Outcome);
+ Assert.Equal(1, client.PatchOnConnectionCalls);
+ Assert.Equal(1, client.RequestedPatchConnectionEpoch);
+ Assert.Equal(0, client.PatchCalls);
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ }
+
+ [Fact]
+ public async Task EnableAsync_CancellationAfterIngressProbeDoesNotPersistOrDispatch()
+ {
+ using var cancellation = new CancellationTokenSource();
+ var registry = CreateRegistry();
+ registry.Save();
+ var client = new FakeConfigClient(Config(allowTailscale: false));
+ var service = new GatewayTailscaleAuthUpgradeService(
+ registry, new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready)
+ {
+ AfterVerify = cancellation.Cancel,
+ });
+
+ await Assert.ThrowsAnyAsync(() =>
+ service.EnableAsync("gateway-1", client, cancellation.Token));
+
+ Assert.False(registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(0, client.PatchCalls);
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.False(reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.True(GatewayTailscaleAuthUpgradePolicy.CanOffer(reloaded.GetActive()));
+ }
+
+ [Theory]
+ [InlineData(false, "accepted")]
+ [InlineData(false, "rejected")]
+ [InlineData(false, "unknown")]
+ [InlineData(false, "exception")]
+ [InlineData(true, "accepted")]
+ [InlineData(true, "rejected")]
+ [InlineData(true, "unknown")]
+ [InlineData(true, "exception")]
+ public async Task EnableAsync_CancellationDuringPatchDrainsWithoutChangingTrust(
+ bool previouslyTrusted, string completion)
+ {
+ using var cancellation = new CancellationTokenSource();
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with { TrustTailscaleAuth = previouslyTrusted });
+ registry.Save();
+ var originalRegistry = File.ReadAllText(_temp.Combine("gateways.json"));
+ var patchCompletion = new TaskCompletionSource(
+ TaskCreationOptions.RunContinuationsAsynchronously);
+ var client = new FakeConfigClient(Config(allowTailscale: false))
+ {
+ PatchCompletion = patchCompletion,
+ };
+ var service = CreateReadyService(registry);
+
+ var enableTask = service.EnableAsync("gateway-1", client, cancellation.Token);
+ await client.PatchStarted.Task.WaitAsync(StepTimeout);
+ cancellation.Cancel();
+
+ Assert.False(enableTask.IsCompleted);
+ Assert.Equal(originalRegistry, File.ReadAllText(_temp.Combine("gateways.json")));
+ if (completion == "exception")
+ patchCompletion.SetException(new IOException("response lost"));
+ else
+ patchCompletion.SetResult(new ConfigPatchResult
+ {
+ Ok = completion == "accepted",
+ IsGatewayRejection = completion == "rejected",
+ });
+ await Assert.ThrowsAnyAsync(() => enableTask);
+ Assert.True(patchCompletion.Task.IsCompleted);
+ Assert.Equal(previouslyTrusted, registry.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(1, client.PatchCalls);
+ Assert.Equal(originalRegistry, File.ReadAllText(_temp.Combine("gateways.json")));
+ var reloaded = new GatewayRegistry(_temp.Path);
+ reloaded.Load();
+ Assert.Equal(previouslyTrusted, reloaded.GetActive()!.TrustTailscaleAuth);
+ Assert.Equal(!previouslyTrusted, GatewayTailscaleAuthUpgradePolicy.CanOffer(reloaded.GetActive()));
+ }
+
+ [Fact]
+ public async Task RevalidateAsync_EditedNonTailscaleEndpointDoesNotTrustMarker()
+ {
+ var registry = CreateRegistry();
+ registry.Update("gateway-1", current => current with
+ {
+ Url = "wss://gateway.example.test",
+ TrustTailscaleAuth = true,
+ });
+ var client = new FakeConfigClient(Config(allowTailscale: true));
+ var service = new GatewayTailscaleAuthUpgradeService(registry);
+
+ var trusted = await service.RevalidateAsync("gateway-1", client, CancellationToken.None);
+
+ Assert.False(trusted);
+ Assert.Equal(0, client.ConfigRequests);
+ }
+
+ [Theory]
+ [MemberData(nameof(IneligibleRecords))]
+ public void CanOffer_RejectsRecordsOutsideManagedTailnetBoundary(GatewayRecord record) =>
+ Assert.False(GatewayTailscaleAuthUpgradePolicy.CanOffer(record));
+
+ public static TheoryData IneligibleRecords => new()
+ {
+ ManagedRecord() with { IsLocal = false },
+ ManagedRecord() with { SetupManagedDistroName = null },
+ ManagedRecord() with { SshTunnel = new SshTunnelConfig("user", "host", 18789, 18789) },
+ ManagedRecord() with { Url = "ws://127.0.0.1:18789" },
+ ManagedRecord() with { Url = "wss://gateway.example.test" },
+ };
+
+ public void Dispose() => _temp.Dispose();
+
+ private GatewayRegistry CreateRegistry(IFileSystem? fileSystem = null)
+ {
+ var registry = new GatewayRegistry(_temp.Path, fileSystem);
+ registry.AddOrUpdate(ManagedRecord());
+ registry.SetActive("gateway-1");
+ return registry;
+ }
+
+ private static GatewayRecord ManagedRecord() => new()
+ {
+ Id = "gateway-1",
+ Url = "wss://openclaw-host.tail1234.ts.net",
+ IsLocal = true,
+ SetupManagedDistroName = "OpenClawGateway",
+ SharedGatewayToken = "test-token-placeholder",
+ };
+
+ private static GatewayTailscaleAuthUpgradeService CreateReadyService(GatewayRegistry registry) =>
+ new(registry, new FakeLiveVerifier(GatewayTailscaleAuthLiveState.Ready));
+
+ private static JsonElement Config(
+ bool allowTailscale,
+ bool includeBaseHash = true,
+ bool includeGatewayPort = true,
+ string appliedRevision = "revision-new")
+ {
+ using var document = JsonDocument.Parse($$"""
+ {
+ "parsed": {
+ "gateway": {
+ {{(includeGatewayPort ? "\"port\": 18789," : "")}}
+ "tailscale": { "mode": "serve" },
+ "auth": { "allowTailscale": {{allowTailscale.ToString().ToLowerInvariant()}} }
+ },
+ "unrelated": "keep"
+ },
+ "sourceConfig": {
+ "gateway": {
+ {{(includeGatewayPort ? "\"port\": 18789," : "")}}
+ "tailscale": { "mode": "serve" },
+ "auth": { "allowTailscale": {{allowTailscale.ToString().ToLowerInvariant()}} }
+ },
+ "unrelated": "keep"
+ },
+ "configRevisionHash": "revision-new",
+ "appliedConfigHash": "{{appliedRevision}}"{{(includeBaseHash ? ",\n \"baseHash\": \"base-1\"" : "")}}
+ }
+ """);
+ return document.RootElement.Clone();
+ }
+
+ private static JsonElement ConfigWithGatewayPort(string gatewayPort)
+ {
+ using var document = JsonDocument.Parse($$"""
+ {
+ "parsed": {
+ "gateway": {
+ "port": {{gatewayPort}},
+ "auth": { "allowTailscale": true }
+ }
+ },
+ "sourceConfig": {
+ "gateway": {
+ "port": {{gatewayPort}},
+ "auth": { "allowTailscale": true }
+ }
+ },
+ "configRevisionHash": "revision-new",
+ "appliedConfigHash": "revision-new"
+ }
+ """);
+ return document.RootElement.Clone();
+ }
+
+ private static JsonElement ImplicitServeConfig()
+ {
+ using var document = JsonDocument.Parse("""
+ {
+ "parsed": {
+ "gateway": {
+ "auth": { "mode": "token" },
+ "tailscale": { "mode": "serve" }
+ }
+ },
+ "sourceConfig": {
+ "gateway": {
+ "auth": { "mode": "token" },
+ "tailscale": { "mode": "serve" }
+ }
+ },
+ "baseHash": "base-1",
+ "configRevisionHash": "revision-new",
+ "appliedConfigHash": "revision-new"
+ }
+ """);
+ return document.RootElement.Clone();
+ }
+
+ private sealed class FakeConfigClient(JsonElement config) : IGatewayTailscaleAuthConfigClient
+ {
+ public JsonElement ConfigResponse { get; set; } = config;
+ public IReadOnlyList Scopes { get; set; } = ["operator.admin"];
+ public IReadOnlyList GrantedOperatorScopes => Scopes;
+ public bool IsConnectedToGateway { get; set; } = true;
+ public long? SessionMutationConnectionEpoch { get; set; } = 1;
+ public int ConfigRequests { get; private set; }
+ public int PatchCalls { get; private set; }
+ public int PatchOnConnectionCalls { get; private set; }
+ public string? PatchBaseHash { get; private set; }
+ public long? RequestedPatchConnectionEpoch { get; private set; }
+ public JsonElement? PatchedConfig { get; private set; }
+ public ConfigPatchResult PatchResult { get; set; } = new() { Ok = true };
+ public Exception? ConfigError { get; set; }
+ public Exception? PatchError { get; set; }
+ public bool EmitConfig { get; set; } = true;
+ public Action? AfterConfig { get; set; }
+ public Action? BeforePatch { get; set; }
+ public TaskCompletionSource? PatchCompletion { get; set; }
+ public TaskCompletionSource PatchStarted { get; } = new(
+ TaskCreationOptions.RunContinuationsAsynchronously);
+
+ public Task RequestConfigDetailedAsync(int timeoutMs = 15000)
+ {
+ ConfigRequests++;
+ if (ConfigError is not null)
+ return Task.FromException(ConfigError);
+
+ var result = EmitConfig
+ ? Task.FromResult(ConfigResponse.Clone())
+ : new TaskCompletionSource().Task;
+ AfterConfig?.Invoke();
+ return result;
+ }
+
+ public Task PatchConfigDetailedAsync(
+ JsonElement fullConfig,
+ string? baseHash,
+ int timeoutMs = 15000)
+ {
+ BeforePatch?.Invoke();
+ PatchCalls++;
+ PatchBaseHash = baseHash;
+ PatchedConfig = fullConfig.Clone();
+ PatchStarted.TrySetResult();
+ if (PatchError is not null)
+ return Task.FromException(PatchError);
+ return PatchCompletion?.Task ?? Task.FromResult(PatchResult);
+ }
+
+ public Task PatchConfigOnConnectionAsync(
+ JsonElement fullConfig,
+ string? baseHash,
+ long connectionEpoch,
+ int timeoutMs = 15000)
+ {
+ PatchOnConnectionCalls++;
+ RequestedPatchConnectionEpoch = connectionEpoch;
+ return SessionMutationConnectionEpoch == connectionEpoch
+ ? PatchConfigDetailedAsync(fullConfig, baseHash, timeoutMs)
+ : Task.FromException(
+ new InvalidOperationException("The Gateway connection changed before the request could be sent."));
+ }
+ }
+
+ private sealed class FailOnSecondWriteFileSystem : IFileSystem
+ {
+ private readonly RealFileSystem _inner = new();
+ private int _writes;
+
+ public bool FileExists(string path) => _inner.FileExists(path);
+ public string ReadAllText(string path) => _inner.ReadAllText(path);
+ public void WriteAllText(string path, string content)
+ {
+ if (Interlocked.Increment(ref _writes) == 2)
+ throw new IOException("trust-marker write failed");
+ _inner.WriteAllText(path, content);
+ }
+ public void CreateDirectory(string path) => _inner.CreateDirectory(path);
+ public bool DirectoryExists(string path) => _inner.DirectoryExists(path);
+ public void CopyFile(string source, string destination, bool overwrite) =>
+ _inner.CopyFile(source, destination, overwrite);
+ public void DeleteFile(string path) => _inner.DeleteFile(path);
+ }
+
+ private sealed class FakeLiveVerifier : IGatewayTailscaleAuthLiveVerifier
+ {
+ private readonly Queue