Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/FleetDiagnosticsSsrfTests.cs
T
Joseph Doherty 56fcc6e939 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.
2026-12-03 09:46:37 -05:00

263 lines
11 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")]
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));
}
}
}