From 56fcc6e9390e224080e1e465f2ecbc99885b0b6b Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:46:37 -0500 Subject: [PATCH] fix(adminui): #973 /fleet/diagnostics only dials Up driver members or enabled ClusterNodes; client refuses non-host:port targets Closes the A-1 SSRF: ?node= / the typed box resolved straight into an Akka ActorSelection, so any signed-in user could make the admin node open a remoting association to an arbitrary host:port. Page policy stays AuthenticatedRead (same tier as /fleet and /hosts). Akka untrusted-mode audit recorded in docs/security.md as an open follow-up. --- docs/security.md | 8 + .../Clients/FleetDiagnosticsClient.cs | 21 +- .../Clients/FleetDiagnosticsTargets.cs | 81 ++++++ .../Components/Pages/FleetDiagnostics.razor | 54 +++- .../FleetDiagnosticsSsrfTests.cs | 262 ++++++++++++++++++ 5 files changed, 415 insertions(+), 11 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsTargets.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/FleetDiagnosticsSsrfTests.cs diff --git a/docs/security.md b/docs/security.md index 5a707880a..74c3d9f7e 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1791,6 +1791,14 @@ Responses: `202 Accepted` (`{ outcome, deploymentId, revisionHash }`) when a dep **Outcome unknown (lmxopcua#949).** The trigger waits 10 s for the admin singleton. A slow compose (one gate run took 10.5 s) can outlast that and still create and apply the deployment, so a timeout is **not** reported as a failure: the id is pre-allocated before the ask and the response is `202 Accepted` with `{ "outcome": "OutcomeUnknown", "deploymentId": "", "message": "…" }` and `Location: /api/deployments/`. Poll that resource: `200` means the deployment exists (and carries exactly that id); `404` for a couple of minutes means it was not created and the trigger can be repeated (a repeat while the original compose is still running answers `409` naming the same id). Scripts must therefore check `outcome`, not just the 2xx status. The AdminUI Deployments page shows the same case as "could not be confirmed … may still be created", with the id. The admin singleton logs a Warning with the per-phase timings (`dispatch`, `in-flight-check`, `snapshot-begin+compose-lock`, `snapshot-read`, `validate`, `compose`, `save+commit`), timed from the singleton's receipt of the request, for any deploy slower than 3 s. Since lmxopcua#955 the compose reads under SNAPSHOT isolation (serialised against other composes by an app lock), not SERIALIZABLE: a concurrent AdminUI edit neither waits for a running deploy nor holds it, and the two can no longer deadlock (under SERIALIZABLE a cross-table edit made the deploy wait ~5 s per deadlock-monitor cycle or fail with "StartDeployment failed on the server"). An edit that commits after the deploy's snapshot is simply in the next deployment. Set the secret via `Security:DeployApiKey` (env `Security__DeployApiKey`) on admin nodes only; treat it like any deploy credential (rotate, keep out of source). +### `/fleet/diagnostics` dials only known nodes (#973 / review A-1) + +The page used to feed `?node=` (or the typed host:port box) straight into an Akka `ActorSelection`, so any signed-in user could make the admin node open an outbound remoting association to an arbitrary `host:port`. The target now resolves server-side through `FleetDiagnosticsTargets.Resolve` against a closed set: **Up driver-role cluster members ∪ `Host:AkkaPort` of every enabled `ClusterNode`**. Anything else renders "Unknown node … no connection was attempted" and never reaches `IFleetDiagnosticsClient`; the value dialled is the canonical member string, not the caller's text. Peer nodes for the cluster-wide Faulted tile go through the same check. `FleetDiagnosticsClient` independently refuses any value that is not a plain `host:port` (`FleetDiagnosticsTargets.IsWellFormed`; `/`, `@`, whitespace, `?`, port outside 1..65535) before building the address. + +The page policy stays `AuthenticatedRead`: `/fleet` and `/hosts`, which link to it and show the same driver-health data, are the same tier, and with the closed set a Viewer can no longer steer the admin node's outbound connections. + +**Open (not fixed here): Akka remoting is not hardened.** The embedded HOCON (`Cluster/Resources/akka.conf`) sets no `akka.remote.untrusted-mode` / `trusted-selection-paths`, and `WithRemoting` configures no TLS. Untrusted mode is not a drop-in switch on a cluster node (it blocks the system messages and `/system/...` selections that cluster gossip, DistributedPubSub and singletons rely on), so it needs its own design — see the follow-up issue. + --- ## Mesh gRPC ingress is `AllowAnonymous` by design diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs index 71169d818..80f6f1a6c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs @@ -42,6 +42,18 @@ public sealed class FleetDiagnosticsClient : IFleetDiagnosticsClient /// public async Task GetDiagnosticsAsync(NodeId nodeId, CancellationToken ct) { + // Defence in depth (#973 / A-1): the page resolves the target against the closed member set, but this + // client is the one place that builds the address, so it refuses anything that is not a plain host:port + // (a '/' or '@' would re-target the actor path) BEFORE an ActorSelection — and so an outbound + // association — can exist. + if (!FleetDiagnosticsTargets.IsWellFormed(nodeId.Value)) + { + _log.LogWarning( + "Fleet diagnostics refused node {NodeId}: not a plain host:port; no connection attempted", + nodeId.Value); + return Empty(nodeId); + } + try { // Inside the try: a malformed node value makes ActorSelection throw, and that must degrade to @@ -57,11 +69,10 @@ public sealed class FleetDiagnosticsClient : IFleetDiagnosticsClient _log.LogWarning(ex, "Fleet diagnostics for node {NodeId} unavailable (no answer within {Timeout}s); returning an empty snapshot", nodeId.Value, AskTimeout.TotalSeconds); - return new NodeDiagnosticsSnapshot( - nodeId, - CurrentRevision: null, - Drivers: Array.Empty(), - AsOfUtc: DateTime.UtcNow); + return Empty(nodeId); } } + + private static NodeDiagnosticsSnapshot Empty(NodeId nodeId) => + new(nodeId, CurrentRevision: null, Drivers: Array.Empty(), AsOfUtc: DateTime.UtcNow); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsTargets.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsTargets.cs new file mode 100644 index 000000000..839052c63 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsTargets.cs @@ -0,0 +1,81 @@ +using System.Text.RegularExpressions; +using Microsoft.EntityFrameworkCore; +using ZB.MOM.WW.OtOpcUa.Configuration; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients; + +/// +/// The closed set of nodes /fleet/diagnostics may dial (#973 / review A-1). +/// +/// +/// +/// The page used to pass ?node= (or the typed box) straight into an Akka +/// ActorSelection; Ask on a remote selection makes Akka.Remote open an outbound +/// association to whatever host:port is named, so any signed-in user could make the admin node +/// dial an arbitrary endpoint (SSRF into the control plane). The target is now resolved server-side +/// against a closed set — Up driver-role cluster members ∪ Host:AkkaPort of every enabled +/// ClusterNode row — and the dialled string is the canonical member, never the caller's +/// text. is the second, independent layer that +/// applies to whatever it is handed. +/// +/// +public static class FleetDiagnosticsTargets +{ + // host:port where host is a DNS name / IPv4 literal. No '/', '@', whitespace, '[' or '?' — anything that + // could re-target the actor path or smuggle a second address into the akka.tcp URI. (IPv6 literals are + // not representable in the NodeId host:port form the fleet uses.) + private static readonly Regex WellFormed = new( + @"^[A-Za-z0-9._-]{1,253}:\d{1,5}$", + RegexOptions.Compiled | RegexOptions.CultureInvariant, + TimeSpan.FromMilliseconds(100)); + + /// True when is a plain host:port with a port in 1..65535. + /// The candidate node id. + /// when it is safe to interpolate into an akka.tcp:// address. + public static bool IsWellFormed(string? value) + { + if (string.IsNullOrEmpty(value) || value.Length > 260) return false; + if (!WellFormed.IsMatch(value)) return false; + var port = int.Parse(value[(value.LastIndexOf(':') + 1)..], System.Globalization.CultureInfo.InvariantCulture); + return port is >= 1 and <= 65535; + } + + /// The Host:AkkaPort dial target of every enabled ClusterNode row. + /// The config DB context. + /// Cancellation token. + /// Dial targets (only the well-formed ones). + public static async Task> LoadEnabledNodeTargetsAsync( + OtOpcUaConfigDbContext db, CancellationToken ct = default) + { + ArgumentNullException.ThrowIfNull(db); + var rows = await db.ClusterNodes.AsNoTracking() + .Where(n => n.Enabled) + .Select(n => new { n.Host, n.AkkaPort }) + .ToListAsync(ct); + return rows.Select(r => $"{r.Host}:{r.AkkaPort}").Where(IsWellFormed).ToList(); + } + + /// + /// Resolves a requested node against the closed set. + /// + /// The raw ?node= / typed value. + /// Up driver-role cluster members (host:port). + /// Enabled ClusterNode Host:AkkaPort targets. + /// + /// The canonical allowed value (as it appears in the set, not the caller's casing), or + /// when is not a member — the caller must then not dial. + /// + public static string? Resolve( + string? requested, IEnumerable upDriverMembers, IEnumerable enabledNodeTargets) + { + var wanted = requested?.Trim(); + if (!IsWellFormed(wanted)) return null; + foreach (var candidate in upDriverMembers.Concat(enabledNodeTargets)) + { + if (IsWellFormed(candidate) && string.Equals(candidate, wanted, StringComparison.OrdinalIgnoreCase)) + return candidate; + } + + return null; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/FleetDiagnostics.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/FleetDiagnostics.razor index 6f1a7ec14..5e975ddd8 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/FleetDiagnostics.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/FleetDiagnostics.razor @@ -4,7 +4,10 @@ its live child set + each child's last-published health; the "running from cache" flag is the one fact /hosts cannot show (a node booted from its artifact cache looks healthy but is frozen). Reach it as /fleet/diagnostics?node= (the NodeId shown on /fleet and /hosts), or pick - a driver-role member from the selector. *@ + a driver-role member from the selector. The target is resolved against a closed set (Up driver members + plus enabled ClusterNode Host:AkkaPort) — anything else is refused without dialling (#973 / A-1). + Policy stays AuthenticatedRead: /fleet and /hosts, which link here and show the same data, are the same + tier, and with the closed set a Viewer can no longer steer the admin node's outbound connections. *@ @attribute [Authorize(Policy = AdminUiPolicies.AuthenticatedRead)] @rendermode RenderMode.InteractiveServer @using Microsoft.EntityFrameworkCore @@ -37,7 +40,7 @@ { } - @if (!string.IsNullOrEmpty(_selectedNode) && !_members.Contains(_selectedNode)) + @if (!string.IsNullOrEmpty(_selectedNode) && !_members.Contains(_selectedNode, StringComparer.OrdinalIgnoreCase)) { } @@ -60,7 +63,14 @@ -@if (string.IsNullOrEmpty(_selectedNode)) +@if (!string.IsNullOrEmpty(_rejectedNode)) +{ + +} +else if (string.IsNullOrEmpty(_selectedNode)) {
Pick a driver-role node to fetch its driver diagnostics. The node answers from its own @@ -177,6 +187,9 @@ else private IReadOnlyList _members = Array.Empty(); private string _selectedNode = ""; + // A ?node= / typed value that is not in the closed set: shown to the user, never dialled. + private string _rejectedNode = ""; + private IReadOnlyList _enabledNodeTargets = Array.Empty(); private string _typedNode = ""; private NodeDiagnosticsSnapshot? _snapshot; private IReadOnlyDictionary _displayNames = new Dictionary(); @@ -200,14 +213,39 @@ else .OrderBy(s => s, StringComparer.OrdinalIgnoreCase) .ToList(); var requested = Node?.Trim() ?? ""; - if (!string.Equals(requested, _selectedNode, StringComparison.Ordinal)) + var key = _rejectedNode.Length > 0 ? _rejectedNode : _selectedNode; + if (!string.Equals(requested, key, StringComparison.Ordinal)) { - _selectedNode = requested; _snapshot = null; + _selectedNode = ""; + _rejectedNode = ""; + if (requested.Length > 0) + { + _enabledNodeTargets = await LoadEnabledNodeTargetsAsync(); + // Resolve to the CANONICAL member string: the dialled value is never the caller's text. + var resolved = FleetDiagnosticsTargets.Resolve(requested, _members, _enabledNodeTargets); + if (resolved is null) _rejectedNode = requested; + else _selectedNode = resolved; + } + if (!string.IsNullOrEmpty(_selectedNode)) await LoadAsync(); } } + // ConfigDb hiccup: fall back to the Up members alone (a stricter set, never a looser one). + private async Task> LoadEnabledNodeTargetsAsync() + { + try + { + await using var db = await DbFactory.CreateDbContextAsync(_cts.Token); + return await FleetDiagnosticsTargets.LoadEnabledNodeTargetsAsync(db, _cts.Token); + } + catch (Exception ex) when (ex is not OperationCanceledException and not ObjectDisposedException) + { + return Array.Empty(); + } + } + private Task OnNodeSelected(ChangeEventArgs e) { var value = e.Value?.ToString() ?? ""; @@ -275,7 +313,11 @@ else } var snapshots = new List { selected }; - var peers = nodeIds.Where(n => !string.Equals(n, selected.NodeId.Value, StringComparison.OrdinalIgnoreCase)).ToList(); + // Peers come from ClusterNode.NodeId rows; only those that are in the closed set are dialled. + var peers = nodeIds + .Where(n => !string.Equals(n, selected.NodeId.Value, StringComparison.OrdinalIgnoreCase)) + .Where(n => FleetDiagnosticsTargets.Resolve(n, _members, _enabledNodeTargets) is not null) + .ToList(); var peerSnapshots = await Task.WhenAll(peers.Select(FetchPeerAsync)); snapshots.AddRange(peerSnapshots.OfType()); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/FleetDiagnosticsSsrfTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/FleetDiagnosticsSsrfTests.cs new file mode 100644 index 000000000..081e013f5 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/FleetDiagnosticsSsrfTests.cs @@ -0,0 +1,262 @@ +using System.Reflection; +using Akka.Actor; +using Bunit; +using Microsoft.AspNetCore.Components; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.Clients; +using ZB.MOM.WW.OtOpcUa.Cluster; +using ZB.MOM.WW.OtOpcUa.Commons.Interfaces; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using FleetDiagnosticsPage = ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.FleetDiagnostics; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests; + +/// +/// #973 / review A-1: /fleet/diagnostics must not let a caller make the admin node dial an arbitrary +/// host:port. The target resolves against Up driver members ∪ enabled ClusterNode Host:AkkaPort, and +/// independently refuses anything that is not a plain host:port. +/// +[Trait("Category", "Unit")] +public sealed class FleetDiagnosticsSsrfTests : BunitContext +{ + // ---- pure resolver ------------------------------------------------------------------------------------- + + [Theory] + [InlineData("host-a:4053")] + [InlineData("10.0.0.5:4053")] + [InlineData("node_a.plant.local:1")] + [InlineData("host:65535")] + public void Plain_host_port_is_well_formed(string value) => FleetDiagnosticsTargets.IsWellFormed(value).ShouldBeTrue(); + + [Theory] + [InlineData("")] + [InlineData("host-a")] + [InlineData("host-a:0")] + [InlineData("host-a:65536")] + [InlineData("host-a:4053/user/x")] + [InlineData("otopcua@host-a:4053")] + [InlineData("evil:4053/user/x:1")] + [InlineData("host a:4053")] + [InlineData("host-a:4053 ")] + [InlineData("[::1]:4053")] + [InlineData("host-a:4053?x=1")] + public void Anything_that_could_retarget_the_actor_path_is_not_well_formed(string value) => + FleetDiagnosticsTargets.IsWellFormed(value).ShouldBeFalse(); + + [Fact] + public void Resolve_accepts_a_member_and_returns_its_canonical_casing_and_rejects_a_stranger() + { + string[] up = ["Node-A:4053"]; + string[] enabled = ["node-b:4053"]; + + FleetDiagnosticsTargets.Resolve("node-a:4053", up, enabled).ShouldBe("Node-A:4053"); // positive control + FleetDiagnosticsTargets.Resolve(" node-b:4053 ", up, enabled).ShouldBe("node-b:4053"); // ClusterNode row, not Up + FleetDiagnosticsTargets.Resolve("evil.example:4053", up, enabled).ShouldBeNull(); + FleetDiagnosticsTargets.Resolve("node-a:4053/user/x", up, enabled).ShouldBeNull(); + FleetDiagnosticsTargets.Resolve("node-a:4054", up, enabled).ShouldBeNull(); // right host, wrong port + FleetDiagnosticsTargets.Resolve(null, up, enabled).ShouldBeNull(); + } + + [Fact] + public async Task Only_enabled_cluster_nodes_contribute_a_dial_target() + { + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString("N")).Options; + await using (var seed = new OtOpcUaConfigDbContext(options)) + { + seed.ClusterNodes.AddRange(Node("n1", "plc-host-1", 4053, true), Node("n2", "plc-host-2", 4060, false)); + await seed.SaveChangesAsync(Xunit.TestContext.Current.CancellationToken); + } + + await using var db = new OtOpcUaConfigDbContext(options); + var targets = await FleetDiagnosticsTargets.LoadEnabledNodeTargetsAsync(db, Xunit.TestContext.Current.CancellationToken); + targets.ShouldBe(["plc-host-1:4053"]); + } + + // ---- client defence in depth --------------------------------------------------------------------------- + + [Theory] + [InlineData("127.0.0.1:4053/user/other")] + [InlineData("a@127.0.0.1:4053")] + [InlineData("127.0.0.1")] + public async Task Client_refuses_a_malformed_target_without_building_an_address(string value) + { + var log = new CapturingLogger(); + using var system = ActorSystem.Create("ssrf-client-" + Guid.NewGuid().ToString("N")[..6]); + var client = new FleetDiagnosticsClient(system, Options.Create(new AkkaClusterOptions()), log); + + var snapshot = await client.GetDiagnosticsAsync(NodeId.Parse(value), Xunit.TestContext.Current.CancellationToken); + + snapshot.Drivers.ShouldBeEmpty(); + log.Messages.ShouldHaveSingleItem().ShouldContain("no connection attempted"); + } + + [Fact] + public async Task Client_lets_a_well_formed_target_past_the_guard() + { + // Positive control for the test above: the refusal message is specific to the guard, not what every + // empty snapshot logs. A well-formed target proceeds to the Ask (which fails/times out locally here). + var log = new CapturingLogger(); + using var system = ActorSystem.Create("ssrf-client-" + Guid.NewGuid().ToString("N")[..6]); + var client = new FleetDiagnosticsClient(system, Options.Create(new AkkaClusterOptions()), log); + + await client.GetDiagnosticsAsync(NodeId.Parse("127.0.0.1:4053"), Xunit.TestContext.Current.CancellationToken); + + log.Messages.ShouldHaveSingleItem().ShouldContain("unavailable"); + log.Messages.ShouldNotContain(m => m.Contains("no connection attempted")); + } + + // ---- page ---------------------------------------------------------------------------------------------- + + [Fact] + public async Task Page_does_not_dial_a_node_that_is_not_a_member_and_says_so() + { + var spy = Configure(["node-a:4053"], enabledRows: [Node("n-b", "node-b", 4053, true)]); + + var cut = RenderAt("evil.example:4053"); + await Task.Yield(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Unknown node")); // the resolve path has completed + cut.Markup.ShouldContain("no connection was attempted"); + spy.Dialled.ShouldBeEmpty(); + } + + [Fact] + public async Task Page_does_not_dial_a_path_injection_that_starts_with_a_member() + { + var spy = Configure(["node-a:4053"], enabledRows: []); + + var cut = RenderAt("node-a:4053/user/x"); + await Task.Yield(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Unknown node")); + spy.Dialled.ShouldBeEmpty(); + } + + [Fact] + public void Page_dials_an_up_member_using_the_canonical_member_string() + { + var spy = Configure(["Node-A:4053"], enabledRows: []); + + RenderAt("node-a:4053"); + + spy.Dialled.ShouldContain("Node-A:4053"); + spy.Dialled.ShouldNotContain("node-a:4053"); + } + + [Fact] + public void Page_dials_an_enabled_cluster_node_that_is_not_up() + { + var spy = Configure(["node-a:4053"], enabledRows: [Node("n-b", "node-b", 4053, true)]); + + RenderAt("node-b:4053"); + + spy.Dialled.ShouldContain("node-b:4053"); + } + + [Fact] + public async Task Page_does_not_dial_a_disabled_cluster_node() + { + var spy = Configure(["node-a:4053"], enabledRows: [Node("n-b", "node-b", 4053, false)]); + + var cut = RenderAt("node-b:4053"); + await Task.Yield(); + + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Unknown node")); + spy.Dialled.ShouldBeEmpty(); + } + + [Fact] + public void Page_keeps_its_error_boundary_and_read_policy() + { + var razor = AdminUiSource.Read("Components", "Pages", "FleetDiagnostics.razor"); + razor.ShouldContain(""); + razor.ShouldContain(""); + // Decision #973: stays at the same tier as /fleet and /hosts (see the page header comment). + razor.ShouldContain("AdminUiPolicies.AuthenticatedRead"); + } + + // ---- fixtures ------------------------------------------------------------------------------------------ + + private static ClusterNode Node(string id, string host, int akkaPort, bool enabled) => new() + { + NodeId = id, ClusterId = "MAIN", Host = host, AkkaPort = akkaPort, Enabled = enabled, + ApplicationUri = $"urn:test:{id}", CreatedBy = "test", + }; + + // ?node= is a [SupplyParameterFromQuery]: bUnit only supplies it through the NavigationManager. + private IRenderedComponent RenderAt(string node) + { + var nav = Services.GetRequiredService(); + nav.NavigateTo(nav.GetUriWithQueryParameter("node", node)); + return Render(); + } + + private SpyClient Configure(string[] upMembers, ClusterNode[] enabledRows) + { + AddAuthorization().SetAuthorized("fixture"); + var options = new DbContextOptionsBuilder() + .UseInMemoryDatabase(Guid.NewGuid().ToString("N")).Options; + using (var seed = new OtOpcUaConfigDbContext(options)) + { + seed.ClusterNodes.AddRange(enabledRows); + seed.SaveChanges(); + } + + var spy = new SpyClient(); + Services.AddSingleton(spy); + Services.AddSingleton>(new InMemoryFactory(options)); + var roles = DispatchProxy.Create(); + ((RoleProxy)(object)roles).Members = upMembers.Select(m => new NodeId(m)).ToList(); + Services.AddSingleton(roles); + return spy; + } + + private sealed class SpyClient : IFleetDiagnosticsClient + { + public List Dialled { get; } = new(); + + public Task GetDiagnosticsAsync(NodeId nodeId, CancellationToken ct) + { + lock (Dialled) Dialled.Add(nodeId.Value); + return Task.FromResult(new NodeDiagnosticsSnapshot( + nodeId, null, Array.Empty(), DateTime.UtcNow)); + } + } + + private sealed class InMemoryFactory(DbContextOptions options) + : IDbContextFactory + { + public OtOpcUaConfigDbContext CreateDbContext() => new(options); + } + + public class RoleProxy : DispatchProxy + { + public IReadOnlyList Members { get; set; } = Array.Empty(); + + protected override object? Invoke(MethodInfo? method, object?[]? args) => + method!.Name == "MembersWithRole" ? Members : throw new NotSupportedException(method.Name); + } + + private sealed class CapturingLogger : ILogger + { + public List Messages { get; } = new(); + + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) + { + lock (Messages) Messages.Add(formatter(state, exception)); + } + } +}