Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/FleetDiagnosticsSsrfTests.cs
T
Joseph Doherty 743d9e739d fix(adminui): #973 review — fleet-diagnostics target check: ASCII digits, \z anchor, TryParse
FleetDiagnosticsTargets.IsWellFormed used \d (any Unicode decimal digit, so
'host:٤٠٥٣' matched and int.Parse threw FormatException, crashing the page) and
$ (matches before a trailing '\n', which int.Parse then ignored, so
'host:4053\n' was 'well-formed' and could reach the akka.tcp address). Now
[0-9]{1,5}\z and int.TryParse(NumberStyles.None). Regression rows for trailing
newline, Arabic-Indic / full-width / mixed digits, and Resolve refusing them
without throwing (positive control kept); all failed first.

Co-Authored-By: Claude <noreply@anthropic.com>
2026-12-03 12:27:03 -05:00

280 lines
12 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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")]
// Review 2026-12-02: '$' also matches before a trailing '\n' (and int.Parse then ignores it), so a newline
// rode into the akka.tcp address; '\d' matches non-ASCII digits, which int.Parse rejects with a FormatException
// that took the page down instead of answering "not well-formed".
[InlineData("host-a:4053\n")]
[InlineData("host-a:4053\r\n")]
[InlineData("host-a:\u0664\u0660\u0665\u0663")] // Arabic-Indic digits
[InlineData("host-a:4053")] // full-width digits
[InlineData("host-a:405\u0663")]
public void Anything_that_could_retarget_the_actor_path_is_not_well_formed(string value) =>
FleetDiagnosticsTargets.IsWellFormed(value).ShouldBeFalse();
/// <summary>A non-ASCII-digit request is refused by Resolve, not thrown (the page must render "not allowed").</summary>
[Fact]
public void Resolve_refuses_unicode_digits_and_a_trailing_newline_without_throwing()
{
FleetDiagnosticsTargets.Resolve("host-a:\u0664\u0660\u0665\u0663", ["host-a:4053"], []).ShouldBeNull();
FleetDiagnosticsTargets.Resolve("host-a:4053", ["host-a:4053\n"], []).ShouldBeNull();
FleetDiagnosticsTargets.Resolve("host-a:4053", ["host-a:4053"], []).ShouldBe("host-a:4053"); // positive control
}
[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));
}
}
}