feat(cluster): #1003 Akka remoting hardening — untrusted-mode on by default, mutual TLS opt-in

Follow-up of #973 (review 2026-12-02 A-1). New Cluster:Remoting section (AkkaRemotingOptions):

- UntrustedMode (default ON): akka.remote.untrusted-mode with trusted-selection-paths =
  every path this code base reaches by ActorSelection across nodes, enumerated from the Akka
  1.5.62 sources + src/: cluster core daemon + heartbeat receiver, remote-watcher, the DPS
  mediator, /user/{s} + /user/{s}/{s} for each ControlPlane singleton, /user/driver-host.
  Remote deployment and peer PoisonPill/Kill are dropped. Receive-side only, so a mixed
  old/new pair keeps working through a rolling upgrade. Drops (Akka logs them at Debug)
  become a Warning per path + otopcua.cluster.remoting.untrusted_drops.
  AdditionalTrustedSelectionPaths / UntrustedMode=false are the escape hatches.
- Tls (default OFF): mutual TLS on the DotNetty transport (PFX or store cert, mutual auth
  on by default, thumbprint pinning or chain validation, optional hostname check). Seeds and
  the diagnostics selection follow the transport scheme (akka.ssl.tcp); the bootstrap guard
  parses it. Validated at boot.

Proven on real clusters: pair formation, singleton via proxy + hand-over on leave, DPS, zero
drops; untrusted selection dropped (and delivered with the mode off); pinned TLS peers form,
an unpinned node cannot join; full two-node Host harness (deploys from both nodes,
diagnostics, node restart) with zero drops + positive control. Guards fail when a new
singleton or ActorSelection appears without its trusted path.
This commit is contained in:
Joseph Doherty
2026-12-03 15:35:56 -05:00
parent bed9620e31
commit ef4e1668de
15 changed files with 1150 additions and 7 deletions
@@ -0,0 +1,325 @@
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using Akka.Actor;
using Akka.Cluster;
using Akka.Cluster.Hosting;
using Akka.Cluster.Tools.PublishSubscribe;
using Akka.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Cluster.Tests;
/// <summary>
/// lmxopcua#1003 on real clusters built through the shipped <see cref="ServiceCollectionExtensions.WithOtOpcUaClusterBootstrap"/>:
/// untrusted-mode (default on) leaves every cross-node mechanism this code base uses working — membership, a cluster
/// singleton reached through its proxy and handed over on leave, DistributedPubSub, the diagnostics selection — with
/// ZERO drops, while it does drop a selection to any other path (negative control, and its falsifiability control with
/// the mode off). Mutual TLS (opt-in) forms a mesh between pinned peers and keeps an unpinned node out.
/// </summary>
public sealed class RemotingHardeningClusterTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static readonly TimeSpan FormTimeout = TimeSpan.FromSeconds(45);
private static int FreePort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private sealed class EchoKey;
/// <summary>Answers any string with the address of the node it runs on.</summary>
private sealed class Echo : ReceiveActor
{
public Echo()
{
var self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.ToString();
Receive<string>(_ => Sender.Tell(self));
}
}
/// <summary>Forwards whatever it receives to a TaskCompletionSource.</summary>
private sealed class Sink : ReceiveActor
{
public Sink(TaskCompletionSource<object> got)
{
Receive<SubscribeAck>(_ => { });
ReceiveAny(m => got.TrySetResult(m));
}
}
private static async Task<IHost> StartAsync(string system, int port, string[] seeds, AkkaRemotingOptions? remoting = null,
bool singleton = false)
{
var options = new AkkaClusterOptions
{
SystemName = system,
Hostname = "127.0.0.1",
PublicHostname = "127.0.0.1",
Port = port,
Roles = ["admin", "driver"],
SeedNodes = seeds,
Remoting = remoting ?? new AkkaRemotingOptions(),
};
var builder = Host.CreateDefaultBuilder();
builder.ConfigureServices(services =>
{
services.AddSingleton<IOptions<AkkaClusterOptions>>(Options.Create(options));
services.AddAkka(system, (ab, sp) =>
{
ab.WithOtOpcUaClusterBootstrap(sp);
// The diagnostics target, as Runtime spawns it on every driver node.
ab.WithActors((sys, _) => sys.ActorOf(Props.Create(() => new Echo()), "driver-host"));
ab.WithActors((sys, _) => sys.ActorOf(Props.Create(() => new Echo()), "not-trusted"));
if (singleton)
ab.WithSingleton<EchoKey>("config-publish", Props.Create(() => new Echo()), new ClusterSingletonOptions());
});
});
var host = builder.Build();
await host.StartAsync();
return host;
}
private static ActorSystem Sys(IHost host) => host.Services.GetRequiredService<ActorSystem>();
private static async Task<bool> WaitUpAsync(IHost host, int expected, TimeSpan timeout)
{
var cluster = Akka.Cluster.Cluster.Get(Sys(host));
var deadline = DateTime.UtcNow + timeout;
while (DateTime.UtcNow < deadline)
{
if (cluster.State.Members.Count(m => m.Status == MemberStatus.Up) >= expected) return true;
await Task.Delay(200);
}
return false;
}
private static async Task<string> AskUntilAsync(IActorRef target, Func<string, bool> accept, TimeSpan timeout)
{
var deadline = DateTime.UtcNow + timeout;
string last = "(no answer)";
while (DateTime.UtcNow < deadline)
{
try
{
last = await target.Ask<string>("ping", TimeSpan.FromSeconds(3));
if (accept(last)) return last;
}
catch (AskTimeoutException)
{
}
await Task.Delay(250);
}
throw new TimeoutException($"no accepted answer within {timeout}; last: {last}");
}
private static async Task StopAsync(IHost host)
{
try { await host.StopAsync(); } catch (Exception) { /* teardown */ }
host.Dispose();
}
/// <summary>
/// The coverage proof: with untrusted-mode ON (the default) a pair forms, the singleton proxy on the younger node
/// reaches the singleton on the oldest (Identify by selection), DistributedPubSub delivers across nodes (mediator
/// gossip by selection), the oldest leaving hands the singleton over (manager-to-manager selections) — and neither
/// node records a single untrusted-mode drop.
/// </summary>
[Fact]
public async Task A_pair_with_untrusted_mode_on_forms_and_its_singleton_and_pubsub_work_with_no_drops()
{
const string name = "otopcua-untrusted-1";
int pa = FreePort(), pb = FreePort();
string a = $"akka.tcp://{name}@127.0.0.1:{pa}", b = $"akka.tcp://{name}@127.0.0.1:{pb}";
var hostA = await StartAsync(name, pa, [a, b], singleton: true);
IHost? hostB = null;
try
{
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue("A forms alone");
hostB = await StartAsync(name, pb, [b, a], singleton: true);
(await WaitUpAsync(hostB, 2, FormTimeout)).ShouldBeTrue("B joins A with untrusted-mode on");
(await WaitUpAsync(hostA, 2, FormTimeout)).ShouldBeTrue();
Sys(hostA).Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue("the effective config, off the running system");
// Singleton on the oldest (A), reached from B through its proxy.
var proxyB = hostB.Services.GetRequiredService<ActorRegistry>().Get<EchoKey>();
(await AskUntilAsync(proxyB, s => s.EndsWith($":{pa}"), FormTimeout)).ShouldEndWith($":{pa}");
// DistributedPubSub across the pair.
var got = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
var sink = Sys(hostA).ActorOf(Props.Create(() => new Sink(got)));
DistributedPubSub.Get(Sys(hostA)).Mediator.Tell(new Subscribe("remoting-hardening", sink));
var mediatorB = DistributedPubSub.Get(Sys(hostB)).Mediator;
var deadline = DateTime.UtcNow + FormTimeout;
while (!got.Task.IsCompleted && DateTime.UtcNow < deadline)
{
mediatorB.Tell(new Publish("remoting-hardening", "hello"));
await Task.WhenAny(got.Task, Task.Delay(500, Ct));
}
got.Task.IsCompleted.ShouldBeTrue("a publish on B reaches a subscriber on A");
var dropsA = RemotingHardening.DroppedFor(Sys(hostA));
dropsA.ShouldBeEmpty($"A dropped: {string.Join(", ", dropsA)}");
// Graceful leave of the oldest: the singleton is handed over to B.
await StopAsync(hostA);
(await AskUntilAsync(proxyB, s => s.EndsWith($":{pb}"), TimeSpan.FromSeconds(60))).ShouldEndWith($":{pb}");
var dropsB = RemotingHardening.DroppedFor(Sys(hostB));
dropsB.ShouldBeEmpty($"B dropped: {string.Join(", ", dropsB)}");
}
finally
{
await StopAsync(hostA);
if (hostB is not null) await StopAsync(hostB);
}
}
/// <summary>
/// Negative control: a selection to a path that is NOT trusted is dropped, recorded and never answered — while the
/// diagnostics path (<c>/user/driver-host</c>, which the AdminUI queries across meshes) is answered on the same node.
/// Two separate one-node clusters, as central and a site are since the mesh split.
/// </summary>
[Fact]
public async Task A_selection_to_an_untrusted_path_is_dropped_but_the_diagnostics_path_is_answered()
{
int pa = FreePort(), pb = FreePort();
const string name = "otopcua-untrusted-2";
var hostA = await StartAsync(name, pa, [$"akka.tcp://{name}@127.0.0.1:{pa}"]);
var hostB = await StartAsync(name, pb, [$"akka.tcp://{name}@127.0.0.1:{pb}"]);
try
{
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue();
(await WaitUpAsync(hostB, 1, FormTimeout)).ShouldBeTrue();
var fromB = Sys(hostB);
var diag = await fromB.ActorSelection($"akka.tcp://{name}@127.0.0.1:{pa}/user/driver-host")
.Ask<ActorIdentity>(new Identify(1), TimeSpan.FromSeconds(10), Ct);
diag.Subject.ShouldNotBeNull("positive control: the trusted diagnostics path is delivered");
await Should.ThrowAsync<AskTimeoutException>(() => fromB
.ActorSelection($"akka.tcp://{name}@127.0.0.1:{pa}/user/not-trusted")
.Ask<ActorIdentity>(new Identify(2), TimeSpan.FromSeconds(3)));
await Task.Delay(500, Ct);
RemotingHardening.DroppedFor(Sys(hostA)).ShouldContain("/user/not-trusted");
}
finally
{
await StopAsync(hostA);
await StopAsync(hostB);
}
}
/// <summary>Falsifiability control for the test above: with untrusted-mode OFF the same selection IS delivered.</summary>
[Fact]
public async Task With_untrusted_mode_off_the_same_selection_is_delivered()
{
int pa = FreePort(), pb = FreePort();
const string name = "otopcua-untrusted-3";
var off = new AkkaRemotingOptions { UntrustedMode = false };
var hostA = await StartAsync(name, pa, [$"akka.tcp://{name}@127.0.0.1:{pa}"], off);
var hostB = await StartAsync(name, pb, [$"akka.tcp://{name}@127.0.0.1:{pb}"], off);
try
{
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue();
Sys(hostA).Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeFalse();
var identity = await Sys(hostB).ActorSelection($"akka.tcp://{name}@127.0.0.1:{pa}/user/not-trusted")
.Ask<ActorIdentity>(new Identify(3), TimeSpan.FromSeconds(10), Ct);
identity.Subject.ShouldNotBeNull();
}
finally
{
await StopAsync(hostA);
await StopAsync(hostB);
}
}
/// <summary>
/// Opt-in mutual TLS: two nodes whose certificates pin each other form a mesh on <c>akka.ssl.tcp</c> (from seeds
/// still spelled <c>akka.tcp</c> — the scheme is normalised); a third node with a certificate neither pins cannot join,
/// although it would accept them. Positive control for the third node: the same config with its certificate pinned
/// joins.
/// </summary>
[Fact]
public async Task Mutual_tls_forms_a_mesh_between_pinned_peers_and_keeps_an_unpinned_node_out()
{
using var dir = new TempDir();
var (pathA, thumbA) = MakeCert(dir.Path, "node-a");
var (pathB, thumbB) = MakeCert(dir.Path, "node-b");
var (pathC, thumbC) = MakeCert(dir.Path, "node-c");
AkkaRemotingOptions Tls(string path, params string[] pins) => new()
{
Tls = new AkkaRemotingTlsOptions
{
Enabled = true, CertificatePath = path, CertificatePassword = "test-only", AllowedThumbprints = pins,
},
};
const string name = "otopcua-tls-1";
int pa = FreePort(), pb = FreePort(), pc = FreePort();
string a = $"akka.tcp://{name}@127.0.0.1:{pa}", b = $"akka.tcp://{name}@127.0.0.1:{pb}";
var hostA = await StartAsync(name, pa, [a, b], Tls(pathA, thumbA, thumbB));
IHost? hostB = null, hostC = null;
try
{
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue();
Akka.Cluster.Cluster.Get(Sys(hostA)).SelfAddress.Protocol.ShouldBe("akka.ssl.tcp");
hostB = await StartAsync(name, pb, [b, a], Tls(pathB, thumbA, thumbB));
(await WaitUpAsync(hostA, 2, FormTimeout)).ShouldBeTrue("pinned peers form a mesh over mutual TLS");
hostC = await StartAsync(name, pc, [a], Tls(pathC, thumbA, thumbB, thumbC));
(await WaitUpAsync(hostC, 1, TimeSpan.FromSeconds(15))).ShouldBeFalse("A refuses C's unpinned certificate");
Akka.Cluster.Cluster.Get(Sys(hostA)).State.Members.Count.ShouldBe(2);
await StopAsync(hostC);
hostC = await StartAsync(name, FreePort(), [a], Tls(pathA, thumbA, thumbB));
(await WaitUpAsync(hostC, 3, FormTimeout)).ShouldBeTrue("positive control: a pinned certificate joins");
}
finally
{
if (hostC is not null) await StopAsync(hostC);
if (hostB is not null) await StopAsync(hostB);
await StopAsync(hostA);
}
}
private static (string Path, string Thumbprint) MakeCert(string dir, string cn)
{
using var rsa = RSA.Create(2048);
var request = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
var san = new SubjectAlternativeNameBuilder();
san.AddDnsName("localhost");
san.AddIpAddress(IPAddress.Loopback);
request.CertificateExtensions.Add(san.Build());
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(
[new Oid("1.3.6.1.5.5.7.3.1"), new Oid("1.3.6.1.5.5.7.3.2")], critical: false));
request.CertificateExtensions.Add(new X509KeyUsageExtension(
X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, critical: false));
using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(7));
var path = System.IO.Path.Combine(dir, cn + ".pfx");
File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx, "test-only"));
return (path, cert.Thumbprint);
}
private sealed class TempDir : IDisposable
{
public string Path { get; } = Directory.CreateTempSubdirectory("otopcua-remoting-").FullName;
public void Dispose()
{
try { Directory.Delete(Path, recursive: true); } catch { /* best effort */ }
}
}
}
@@ -0,0 +1,166 @@
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Cluster.Tests;
/// <summary>
/// lmxopcua#1003 (review 2026-12-02 A-1 follow-up): the remoting hardening's pure parts — the untrusted-mode HOCON and
/// its trusted path set, seed scheme normalisation, option validation, and the drop classifier. The behaviour on real
/// clusters is <see cref="RemotingHardeningClusterTests"/>.
/// </summary>
public sealed class RemotingHardeningTests
{
[Fact]
public void Untrusted_mode_is_on_by_default()
=> new AkkaClusterOptions().Remoting.UntrustedMode.ShouldBeTrue();
[Fact]
public void Tls_is_off_by_default_and_mutual_when_on()
{
var tls = new AkkaClusterOptions().Remoting.Tls;
tls.Enabled.ShouldBeFalse("TLS is opt-in: an existing fleet's mesh must keep talking after an upgrade");
tls.RequireMutualAuthentication.ShouldBeTrue();
}
/// <summary>Every path the code base reaches by selection across nodes is trusted (see the remarks on <see cref="RemotingHardening"/>).</summary>
[Fact]
public void The_trusted_set_covers_cluster_remote_watch_pubsub_every_singleton_and_the_driver_host()
{
var paths = RemotingHardening.TrustedSelectionPaths;
paths.ShouldContain("/system/cluster/core/daemon");
paths.ShouldContain("/system/cluster/heartbeatReceiver");
paths.ShouldContain("/system/remote-watcher");
paths.ShouldContain("/system/distributedPubSubMediator");
paths.ShouldContain("/user/driver-host");
foreach (var name in RemotingHardening.SingletonNames)
{
paths.ShouldContain($"/user/{name}", "the manager: hand-over between managers");
paths.ShouldContain($"/user/{name}/{name}", "the singleton: the proxies' Identify");
}
}
[Fact]
public void The_hocon_turns_untrusted_mode_on_with_the_trusted_paths_and_any_additional_ones()
{
var hocon = RemotingHardening.BuildUntrustedModeHocon(new AkkaRemotingOptions
{
AdditionalTrustedSelectionPaths = ["/user/extra", " ", "/user/extra"],
});
var config = Akka.Configuration.ConfigurationFactory.ParseString(hocon);
config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue();
var trusted = config.GetStringList("akka.remote.trusted-selection-paths");
trusted.ShouldBe(RemotingHardening.TrustedSelectionPaths.Append("/user/extra"), ignoreOrder: true);
}
[Fact]
public void Disabled_untrusted_mode_is_written_off_explicitly()
{
var config = Akka.Configuration.ConfigurationFactory.ParseString(
RemotingHardening.BuildUntrustedModeHocon(new AkkaRemotingOptions { UntrustedMode = false }));
config.GetBoolean("akka.remote.untrusted-mode").ShouldBeFalse();
}
[Theory]
[InlineData("akka.tcp://otopcua@node-a:4053", false, "akka.tcp://otopcua@node-a:4053")]
[InlineData("akka.tcp://otopcua@node-a:4053", true, "akka.ssl.tcp://otopcua@node-a:4053")]
[InlineData("akka.ssl.tcp://otopcua@node-a:4053", false, "akka.tcp://otopcua@node-a:4053")]
[InlineData("AKKA.SSL.TCP://otopcua@node-a:4053", true, "akka.ssl.tcp://otopcua@node-a:4053")]
[InlineData("akka://otopcua", true, "akka://otopcua")]
public void A_seed_takes_the_transport_scheme(string seed, bool tls, string expected)
=> RemotingHardening.NormalizeSeed(seed, new AkkaRemotingTlsOptions { Enabled = tls }).ShouldBe(expected);
[Fact]
public void BuildClusterOptions_rewrites_seeds_to_the_tls_scheme()
{
var options = new AkkaClusterOptions
{
SeedNodes = ["akka.tcp://otopcua@a:4053", "akka.tcp://otopcua@b:4053"],
Remoting = new AkkaRemotingOptions { Tls = new AkkaRemotingTlsOptions { Enabled = true } },
};
ServiceCollectionExtensions.BuildClusterOptions(options).SeedNodes
.ShouldBe(["akka.ssl.tcp://otopcua@a:4053", "akka.ssl.tcp://otopcua@b:4053"]);
}
[Fact]
public void The_bootstrap_guard_parses_a_tls_seed()
{
ClusterBootstrapGuard.TryParse("akka.ssl.tcp://otopcua@node-b:4054", out var host, out var port).ShouldBeTrue();
host.ShouldBe("node-b");
port.ShouldBe(4054);
}
[Fact]
public void Default_options_validate()
=> RemotingHardening.Validate(new AkkaRemotingOptions()).ShouldBeEmpty();
[Theory]
[InlineData("user/no-leading-slash")]
[InlineData("akka.tcp://otopcua@x:1/user/a")]
[InlineData("/other/a")]
[InlineData("")]
public void A_malformed_additional_path_is_refused(string path)
=> RemotingHardening.Validate(new AkkaRemotingOptions { AdditionalTrustedSelectionPaths = [path] })
.ShouldHaveSingleItem().ShouldContain("AdditionalTrustedSelectionPaths");
[Fact]
public void Tls_needs_exactly_one_certificate_source()
{
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions { Enabled = true }))
.ShouldContain(m => m.Contains("exactly one of CertificatePath"));
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions
{
Enabled = true, CertificatePath = "/x.pfx", CertificateThumbprint = new string('A', 40),
}))
.ShouldContain(m => m.Contains("exactly one of CertificatePath"));
}
[Fact]
public void Tls_refuses_a_relative_or_missing_certificate_file_and_bad_thumbprints()
{
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions { Enabled = true, CertificatePath = "node.pfx" }))
.ShouldContain(m => m.Contains("absolute"));
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions
{
Enabled = true, CertificatePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".pfx"),
}))
.ShouldContain(m => m.Contains("does not exist"));
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions
{
Enabled = true, CertificateThumbprint = "nope", AllowedThumbprints = ["12:34"],
}))
.Count().ShouldBe(2);
}
[Fact]
public void Tls_options_are_not_validated_while_tls_is_off()
=> RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions { Enabled = false, CertificatePath = "relative" }))
.ShouldBeEmpty();
[Fact]
public void The_cluster_options_validator_reports_remoting_problems()
{
var validator = new AkkaClusterOptionsValidator();
var result = validator.Validate(null, new AkkaClusterOptions
{
Remoting = new AkkaRemotingOptions { Tls = new AkkaRemotingTlsOptions { Enabled = true } },
});
result.Failed.ShouldBeTrue();
result.FailureMessage.ShouldContain("Cluster:Remoting:Tls");
}
[Theory]
[InlineData("operating in UntrustedMode, dropping inbound actor selection to [/user/x/y], allow itby adding the path", "/user/x/y")]
[InlineData("operating in UntrustedMode, dropping inbound IPossiblyHarmful message of type Akka.Actor.PoisonPill", "IPossiblyHarmful Akka.Actor.PoisonPill")]
[InlineData("dropping daemon message in untrusted mode", "remote daemon (remote deployment)")]
public void A_drop_message_is_recognised(string message, string expected)
{
RemotingHardening.TryParseDrop(message, out var what).ShouldBeTrue();
what.ShouldBe(expected);
}
[Fact]
public void An_ordinary_debug_message_is_not_a_drop()
=> RemotingHardening.TryParseDrop("Cluster Node [x] - Received InitJoin message", out _).ShouldBeFalse();
private static AkkaRemotingOptions Tls(AkkaRemotingTlsOptions tls) => new() { Tls = tls };
}
@@ -0,0 +1,71 @@
using Microsoft.Extensions.DependencyInjection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Cluster;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
/// <summary>
/// lmxopcua#1003: Akka untrusted-mode is ON by default. On the full two-node harness — the shipped bootstrap with every
/// ControlPlane singleton and proxy, the cluster-scoped redundancy singleton, the runtime actors and DistributedPubSub —
/// a deployment through the AdminOperations proxy, the diagnostics selection to each node's driver host, and node B
/// leaving and rejoining (singleton proxies re-identifying) leave NO untrusted-mode drop on either node.
/// </summary>
public sealed class UntrustedModeHarnessTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Fact]
public async Task The_full_two_node_stack_runs_under_untrusted_mode_without_a_single_dropped_message()
{
await using var harness = await TwoNodeClusterHarness.StartAsync();
harness.NodeASystem.Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue("the default, effective");
harness.NodeBSystem.Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue();
await harness.SeedDefaultClusterAsync();
// Deploy from EACH node: one of them reaches the singletons through a cross-node proxy.
foreach (var node in new[] { harness.NodeA, harness.NodeB })
{
await using var scope = node.Services.CreateAsyncScope();
var adminOps = scope.ServiceProvider.GetRequiredService<IAdminOperationsClient>();
var deploy = await adminOps.StartDeploymentAsync(createdBy: "alice@test", Ct);
deploy.Outcome.ShouldBeOneOf(StartDeploymentOutcome.Accepted, StartDeploymentOutcome.NoChanges,
StartDeploymentOutcome.AnotherDeploymentInFlight); // any of these is the singleton answering
}
// The diagnostics selection (/user/driver-host) to both nodes, from node A.
await using (var scope = harness.NodeA.Services.CreateAsyncScope())
{
var diagnostics = scope.ServiceProvider.GetRequiredService<IFleetDiagnosticsClient>();
foreach (var member in Akka.Cluster.Cluster.Get(harness.NodeASystem).State.Members)
{
var nodeId = Commons.Types.NodeId.Parse($"{member.Address.Host}:{member.Address.Port}");
(await diagnostics.GetDiagnosticsAsync(nodeId, Ct)).NodeId.ShouldBe(nodeId, "answered, not the empty fallback");
}
}
// Node B leaves and rejoins: hand-over / re-identification on the remaining managers and proxies.
await harness.RestartNodeBAsync();
await using (var scope = harness.NodeB.Services.CreateAsyncScope())
{
var adminOps = scope.ServiceProvider.GetRequiredService<IAdminOperationsClient>();
var deploy = await adminOps.StartDeploymentAsync(createdBy: "alice@test", Ct);
deploy.Outcome.ShouldBeOneOf(StartDeploymentOutcome.Accepted, StartDeploymentOutcome.NoChanges,
StartDeploymentOutcome.AnotherDeploymentInFlight); // any of these is the singleton answering
}
var drops = RemotingHardening.DroppedFor(harness.NodeASystem).Concat(RemotingHardening.DroppedFor(harness.NodeBSystem)).ToArray();
drops.ShouldBeEmpty($"untrusted-mode dropped: {string.Join(", ", drops)}");
// Positive control — the empty list above is not vacuous: the drop monitor runs on this stack and records a
// selection to a path that is not trusted.
var addressA = Akka.Cluster.Cluster.Get(harness.NodeASystem).SelfAddress;
harness.NodeBSystem.ActorSelection($"{addressA}/user/not-a-trusted-path").Tell(new Akka.Actor.Identify(1));
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
while (!RemotingHardening.DroppedFor(harness.NodeASystem).Contains("/user/not-a-trusted-path") && DateTime.UtcNow < deadline)
await Task.Delay(100, Ct);
RemotingHardening.DroppedFor(harness.NodeASystem).ShouldContain("/user/not-a-trusted-path");
}
}
@@ -0,0 +1,63 @@
using System.Reflection;
using System.Text.RegularExpressions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Cluster;
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.Configuration;
/// <summary>
/// lmxopcua#1003: Akka untrusted-mode is ON by default, so a cross-node <c>ActorSelection</c> to a path missing from
/// <see cref="RemotingHardening.TrustedSelectionPaths"/> is dropped. These guards keep the trusted set in step with the
/// code: every cluster singleton the ControlPlane registers, the driver host actor's name, and the one application-level
/// selection in <c>src/</c>.
/// </summary>
public sealed class RemotingTrustedPathsCoverageTests
{
[Fact]
public void Every_registered_cluster_singleton_is_trusted()
{
var names = typeof(ZB.MOM.WW.OtOpcUa.ControlPlane.ServiceCollectionExtensions)
.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(f => f.IsLiteral && f.Name.EndsWith("SingletonName", StringComparison.Ordinal))
.Select(f => (string)f.GetRawConstantValue()!)
.ToArray();
names.ShouldNotBeEmpty("positive control: the constants are found");
foreach (var name in names)
{
RemotingHardening.SingletonNames.ShouldContain(name,
$"singleton '{name}' must be added to RemotingHardening.SingletonNames or its proxy/hand-over selections are dropped");
}
}
[Fact]
public void The_driver_host_path_is_the_runtime_actor_name()
=> RemotingHardening.DriverHostPath.ShouldBe("/user/" + ZB.MOM.WW.OtOpcUa.Runtime.ServiceCollectionExtensions.DriverHostActorName);
/// <summary>
/// The only <c>ActorSelection</c> in <c>src/</c> is the diagnostics client (which targets <c>/user/driver-host</c>).
/// A new one must come with its path in the trusted set — then add its file here.
/// </summary>
[Fact]
public void No_new_cross_node_actor_selection_appears_without_a_trusted_path()
{
var allowed = new HashSet<string>(StringComparer.Ordinal) { "FleetDiagnosticsClient.cs" };
var call = new Regex(@"\.ActorSelection\s*\(", RegexOptions.Compiled);
var offenders = Directory.EnumerateFiles(Path.Combine(SolutionRoot(), "src"), "*.cs", SearchOption.AllDirectories)
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
.Where(f => File.ReadLines(f).Any(l => !l.TrimStart().StartsWith("//", StringComparison.Ordinal) && call.IsMatch(l)))
.Select(Path.GetFileName)
.Where(n => !allowed.Contains(n!))
.ToArray();
offenders.ShouldBeEmpty();
}
private static string SolutionRoot()
{
var dir = new DirectoryInfo(AppContext.BaseDirectory);
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx")))
dir = dir.Parent;
dir.ShouldNotBeNull("Could not find solution root (ZB.MOM.WW.OtOpcUa.slnx).");
return dir!.FullName;
}
}