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.
This commit is contained in:
@@ -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": "<id>", "message": "…" }` and `Location: /api/deployments/<id>`. 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
|
||||
|
||||
@@ -42,6 +42,18 @@ public sealed class FleetDiagnosticsClient : IFleetDiagnosticsClient
|
||||
/// <inheritdoc />
|
||||
public async Task<NodeDiagnosticsSnapshot> 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<DriverInstanceDiagnostics>(),
|
||||
AsOfUtc: DateTime.UtcNow);
|
||||
return Empty(nodeId);
|
||||
}
|
||||
}
|
||||
|
||||
private static NodeDiagnosticsSnapshot Empty(NodeId nodeId) =>
|
||||
new(nodeId, CurrentRevision: null, Drivers: Array.Empty<DriverInstanceDiagnostics>(), AsOfUtc: DateTime.UtcNow);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Clients;
|
||||
|
||||
/// <summary>
|
||||
/// The closed set of nodes <c>/fleet/diagnostics</c> may dial (#973 / review A-1).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The page used to pass <c>?node=</c> (or the typed box) straight into an Akka
|
||||
/// <c>ActorSelection</c>; <c>Ask</c> on a remote selection makes Akka.Remote open an outbound
|
||||
/// association to whatever <c>host:port</c> 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 ∪ <c>Host:AkkaPort</c> of every enabled
|
||||
/// <c>ClusterNode</c> row — and the dialled string is the <i>canonical member</i>, never the caller's
|
||||
/// text. <see cref="IsWellFormed"/> is the second, independent layer that
|
||||
/// <see cref="FleetDiagnosticsClient"/> applies to whatever it is handed.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
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));
|
||||
|
||||
/// <summary>True when <paramref name="value"/> is a plain <c>host:port</c> with a port in 1..65535.</summary>
|
||||
/// <param name="value">The candidate node id.</param>
|
||||
/// <returns><see langword="true"/> when it is safe to interpolate into an <c>akka.tcp://</c> address.</returns>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>The <c>Host:AkkaPort</c> dial target of every enabled <c>ClusterNode</c> row.</summary>
|
||||
/// <param name="db">The config DB context.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>Dial targets (only the well-formed ones).</returns>
|
||||
public static async Task<IReadOnlyList<string>> 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();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Resolves a requested node against the closed set.
|
||||
/// </summary>
|
||||
/// <param name="requested">The raw <c>?node=</c> / typed value.</param>
|
||||
/// <param name="upDriverMembers">Up driver-role cluster members (<c>host:port</c>).</param>
|
||||
/// <param name="enabledNodeTargets">Enabled <c>ClusterNode</c> <c>Host:AkkaPort</c> targets.</param>
|
||||
/// <returns>
|
||||
/// The canonical allowed value (as it appears in the set, not the caller's casing), or
|
||||
/// <see langword="null"/> when <paramref name="requested"/> is not a member — the caller must then not dial.
|
||||
/// </returns>
|
||||
public static string? Resolve(
|
||||
string? requested, IEnumerable<string> upDriverMembers, IEnumerable<string> 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;
|
||||
}
|
||||
}
|
||||
@@ -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=<host:port> (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 @@
|
||||
{
|
||||
<option value="@member">@member</option>
|
||||
}
|
||||
@if (!string.IsNullOrEmpty(_selectedNode) && !_members.Contains(_selectedNode))
|
||||
@if (!string.IsNullOrEmpty(_selectedNode) && !_members.Contains(_selectedNode, StringComparer.OrdinalIgnoreCase))
|
||||
{
|
||||
<option value="@_selectedNode">@_selectedNode (not an Up member)</option>
|
||||
}
|
||||
@@ -60,7 +63,14 @@
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@if (string.IsNullOrEmpty(_selectedNode))
|
||||
@if (!string.IsNullOrEmpty(_rejectedNode))
|
||||
{
|
||||
<section class="panel notice rise" role="alert" style="animation-delay:.02s">
|
||||
Unknown node <span class="mono">@_rejectedNode</span> — it is not an Up driver member or an enabled
|
||||
cluster node, so no connection was attempted. Pick a node from the list.
|
||||
</section>
|
||||
}
|
||||
else if (string.IsNullOrEmpty(_selectedNode))
|
||||
{
|
||||
<section class="panel notice rise" style="animation-delay:.02s">
|
||||
Pick a driver-role node to fetch its driver diagnostics. The node answers from its own
|
||||
@@ -177,6 +187,9 @@ else
|
||||
|
||||
private IReadOnlyList<string> _members = Array.Empty<string>();
|
||||
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<string> _enabledNodeTargets = Array.Empty<string>();
|
||||
private string _typedNode = "";
|
||||
private NodeDiagnosticsSnapshot? _snapshot;
|
||||
private IReadOnlyDictionary<string, string> _displayNames = new Dictionary<string, string>();
|
||||
@@ -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<IReadOnlyList<string>> 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<string>();
|
||||
}
|
||||
}
|
||||
|
||||
private Task OnNodeSelected(ChangeEventArgs e)
|
||||
{
|
||||
var value = e.Value?.ToString() ?? "";
|
||||
@@ -275,7 +313,11 @@ else
|
||||
}
|
||||
|
||||
var snapshots = new List<NodeDiagnosticsSnapshot> { 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<NodeDiagnosticsSnapshot>());
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// #973 / review A-1: <c>/fleet/diagnostics</c> must not let a caller make the admin node dial an arbitrary
|
||||
/// <c>host:port</c>. The target resolves against Up driver members ∪ enabled ClusterNode Host:AkkaPort, and
|
||||
/// <see cref="FleetDiagnosticsClient"/> independently refuses anything that is not a plain host:port.
|
||||
/// </summary>
|
||||
[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<OtOpcUaConfigDbContext>()
|
||||
.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("<PageErrorBoundary>");
|
||||
razor.ShouldContain("</PageErrorBoundary>");
|
||||
// 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<FleetDiagnosticsPage> RenderAt(string node)
|
||||
{
|
||||
var nav = Services.GetRequiredService<Microsoft.AspNetCore.Components.NavigationManager>();
|
||||
nav.NavigateTo(nav.GetUriWithQueryParameter("node", node));
|
||||
return Render<FleetDiagnosticsPage>();
|
||||
}
|
||||
|
||||
private SpyClient Configure(string[] upMembers, ClusterNode[] enabledRows)
|
||||
{
|
||||
AddAuthorization().SetAuthorized("fixture");
|
||||
var options = new DbContextOptionsBuilder<OtOpcUaConfigDbContext>()
|
||||
.UseInMemoryDatabase(Guid.NewGuid().ToString("N")).Options;
|
||||
using (var seed = new OtOpcUaConfigDbContext(options))
|
||||
{
|
||||
seed.ClusterNodes.AddRange(enabledRows);
|
||||
seed.SaveChanges();
|
||||
}
|
||||
|
||||
var spy = new SpyClient();
|
||||
Services.AddSingleton<IFleetDiagnosticsClient>(spy);
|
||||
Services.AddSingleton<IDbContextFactory<OtOpcUaConfigDbContext>>(new InMemoryFactory(options));
|
||||
var roles = DispatchProxy.Create<IClusterRoleInfo, RoleProxy>();
|
||||
((RoleProxy)(object)roles).Members = upMembers.Select(m => new NodeId(m)).ToList();
|
||||
Services.AddSingleton(roles);
|
||||
return spy;
|
||||
}
|
||||
|
||||
private sealed class SpyClient : IFleetDiagnosticsClient
|
||||
{
|
||||
public List<string> Dialled { get; } = new();
|
||||
|
||||
public Task<NodeDiagnosticsSnapshot> GetDiagnosticsAsync(NodeId nodeId, CancellationToken ct)
|
||||
{
|
||||
lock (Dialled) Dialled.Add(nodeId.Value);
|
||||
return Task.FromResult(new NodeDiagnosticsSnapshot(
|
||||
nodeId, null, Array.Empty<DriverInstanceDiagnostics>(), DateTime.UtcNow));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class InMemoryFactory(DbContextOptions<OtOpcUaConfigDbContext> options)
|
||||
: IDbContextFactory<OtOpcUaConfigDbContext>
|
||||
{
|
||||
public OtOpcUaConfigDbContext CreateDbContext() => new(options);
|
||||
}
|
||||
|
||||
public class RoleProxy : DispatchProxy
|
||||
{
|
||||
public IReadOnlyList<NodeId> Members { get; set; } = Array.Empty<NodeId>();
|
||||
|
||||
protected override object? Invoke(MethodInfo? method, object?[]? args) =>
|
||||
method!.Name == "MembersWithRole" ? Members : throw new NotSupportedException(method.Name);
|
||||
}
|
||||
|
||||
private sealed class CapturingLogger : ILogger<FleetDiagnosticsClient>
|
||||
{
|
||||
public List<string> Messages { get; } = new();
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception,
|
||||
Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
lock (Messages) Messages.Add(formatter(state, exception));
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user