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
@@ -103,6 +103,12 @@ public sealed class AkkaClusterOptions
/// <c>ClusterBootstrapCoordinator</c> for the runtime.
/// </summary>
public ClusterBootstrapGuardOptions BootstrapGuard { get; set; } = new();
/// <summary>
/// Akka remoting hardening (<c>Cluster:Remoting</c>, lmxopcua#1003): untrusted-mode with the trusted selection
/// paths (on by default) and transport TLS (opt-in). See <see cref="AkkaRemotingOptions"/>.
/// </summary>
public AkkaRemotingOptions Remoting { get; set; } = new();
}
/// <summary>
@@ -67,6 +67,7 @@ public sealed class AkkaClusterOptionsValidator : OptionsValidatorBase<AkkaClust
ArgumentNullException.ThrowIfNull(options);
ValidateBootstrapGuard(builder, options.BootstrapGuard);
foreach (var problem in RemotingHardening.Validate(options.Remoting)) builder.Add(problem);
ValidateAgainstEffectiveRoles(builder, options);
var seeds = options.SeedNodes ?? Array.Empty<string>();
@@ -0,0 +1,79 @@
namespace ZB.MOM.WW.OtOpcUa.Cluster;
/// <summary>
/// Hardening of the Akka remoting endpoint every node listens on (<c>Cluster:Remoting</c>, lmxopcua#1003, review
/// 2026-12-02 A-1 follow-up). Two independent controls:
/// <list type="bullet">
/// <item><see cref="UntrustedMode"/> — <b>on by default</b>: inbound <c>ActorSelection</c> is delivered only to the
/// paths this code base actually addresses across nodes (<see cref="RemotingHardening.TrustedSelectionPaths"/>),
/// remote deployment is refused, and <c>PoisonPill</c>/<c>Kill</c>-class messages from a peer are dropped. A
/// receive-side filter only — the wire format is unchanged, so a mixed old/new pair keeps working.</item>
/// <item><see cref="Tls"/> — <b>off by default</b> (opt-in): TLS with mutual authentication on the remoting
/// transport, so only a peer presenting an accepted certificate can associate (and therefore join the mesh).
/// All-or-nothing per mesh: a TLS node and a plain node cannot talk.</item>
/// </list>
/// </summary>
public sealed class AkkaRemotingOptions
{
/// <summary>
/// Gets or sets whether Akka's <c>untrusted-mode</c> is on. Default <see langword="true"/>. Set
/// <see langword="false"/> only as an escape hatch while reporting a missing path (the drop is logged as a Warning
/// naming it; <see cref="AdditionalTrustedSelectionPaths"/> is the targeted fix).
/// </summary>
public bool UntrustedMode { get; set; } = true;
/// <summary>
/// Gets or sets extra actor paths (<c>/user/…</c> or <c>/system/…</c>, no address) a peer may reach with an
/// <c>ActorSelection</c>, on top of <see cref="RemotingHardening.TrustedSelectionPaths"/>.
/// </summary>
public string[] AdditionalTrustedSelectionPaths { get; set; } = [];
/// <summary>Gets or sets the transport TLS settings (opt-in).</summary>
public AkkaRemotingTlsOptions Tls { get; set; } = new();
}
/// <summary>
/// TLS on the Akka remoting transport (<c>Cluster:Remoting:Tls</c>). Opt-in; see <c>docs/security.md</c> §"Akka
/// remoting" for the rollout (both nodes of a pair, and every node a central admin dials for diagnostics, together).
/// </summary>
public sealed class AkkaRemotingTlsOptions
{
/// <summary>Gets or sets whether the remoting transport runs TLS. Default <see langword="false"/>.</summary>
/// <remarks>
/// Changes the address scheme from <c>akka.tcp</c> to <c>akka.ssl.tcp</c>. <c>Cluster:SeedNodes</c> may keep
/// either spelling: the scheme is rewritten to match this switch at startup.
/// </remarks>
public bool Enabled { get; set; }
/// <summary>Gets or sets the node certificate as a PKCS#12 (<c>.pfx</c>) file, with its private key. Absolute path.</summary>
public string? CertificatePath { get; set; }
/// <summary>Gets or sets the PFX password — supply it as <c>${secret:…}</c> or an environment variable, never committed.</summary>
public string? CertificatePassword { get; set; }
/// <summary>Gets or sets the node certificate's SHA-1 thumbprint in a certificate store (alternative to <see cref="CertificatePath"/>).</summary>
public string? CertificateThumbprint { get; set; }
/// <summary>Gets or sets the store name for <see cref="CertificateThumbprint"/>. Default <c>My</c>.</summary>
public string CertificateStoreName { get; set; } = "My";
/// <summary>Gets or sets the store location for <see cref="CertificateThumbprint"/>. Default <c>LocalMachine</c>.</summary>
public string CertificateStoreLocation { get; set; } = "LocalMachine";
/// <summary>
/// Gets or sets whether an inbound peer must present a certificate too. Default <see langword="true"/> — without it
/// the transport is encrypted but any host can still associate (and join), which is the threat this exists for.
/// </summary>
public bool RequireMutualAuthentication { get; set; } = true;
/// <summary>Gets or sets whether the peer certificate's CN/SAN must match the host it was dialled at. Default off.</summary>
public bool ValidateCertificateHostname { get; set; }
/// <summary>
/// Gets or sets the SHA-1 thumbprints of the peer certificates this node accepts (its pair partner, its own, and —
/// on a node an admin node dials for diagnostics — the admin nodes'). When non-empty, a peer is accepted on its
/// pinned thumbprint alone (self-signed certificates work; no CA needed). When empty, the peer's chain must
/// validate against the machine's trust store.
/// </summary>
public string[] AllowedThumbprints { get; set; } = [];
}
@@ -78,7 +78,10 @@ public sealed class ClusterBootstrapCoordinator : IHostedService
{
try
{
var seeds = _options.SeedNodes ?? Array.Empty<string>();
// lmxopcua#1003: the transport's scheme (akka.ssl.tcp under TLS) wins over the configured spelling.
var seeds = (_options.SeedNodes ?? Array.Empty<string>())
.Select(s => RemotingHardening.NormalizeSeed(s, _options.Remoting?.Tls))
.ToArray();
var role = ClusterBootstrapGuard.Analyze(seeds, _options.PublicHostname, _options.Port);
string[] order;
@@ -44,7 +44,7 @@ namespace ZB.MOM.WW.OtOpcUa.Cluster;
public static class ClusterBootstrapGuard
{
private static readonly Regex SeedPattern =
new(@"^akka(?:\.[a-z0-9]+)?://[^@/]+@(?<host>[^:/]+):(?<port>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
new(@"^akka(?:\.[a-z0-9]+)*://[^@/]+@(?<host>[^:/]+):(?<port>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
/// <summary>The analyzed bootstrap role of this node within its seed list.</summary>
/// <param name="Applies">True only when the guard engages: exactly two seeds, one of them this node.</param>
@@ -0,0 +1,329 @@
using System.Collections.Concurrent;
using System.Diagnostics.Metrics;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using Akka.Actor;
using Akka.Event;
using Akka.Remote.Hosting;
using Akka.Remote.Transport.DotNetty;
namespace ZB.MOM.WW.OtOpcUa.Cluster;
/// <summary>
/// Builds the Akka remoting hardening for <see cref="AkkaRemotingOptions"/> (lmxopcua#1003): the <c>untrusted-mode</c>
/// HOCON with the trusted selection paths, the TLS transport settings, and the scheme normalisation of seed addresses.
/// </summary>
/// <remarks>
/// <para>
/// <b>What untrusted-mode does in Akka.NET 1.5</b> (read off <c>Akka.Remote.DefaultMessageDispatcher</c>, the only
/// consumer of the setting): an inbound <c>ActorSelection</c> is delivered only when its path is listed in
/// <c>trusted-selection-paths</c> (and its payload is not <c>IPossiblyHarmful</c>); a message for the remote
/// daemon (remote deployment) is dropped; an <c>IPossiblyHarmful</c> message (<c>PoisonPill</c>, <c>Kill</c>, …)
/// sent to an actor reference is dropped; a message a peer asks this node to forward to a third system is dropped.
/// Messages to actor references (DistributedPubSub delivery, replies, <c>Ask</c> temp actors) and system messages
/// (remote watch) are unaffected. It does NOT authenticate the peer: the cluster daemon has to stay reachable for
/// joining to work at all, so any host that can reach the port can still associate. That is what <see cref="AkkaRemotingTlsOptions"/>
/// (mutual TLS) is for.
/// </para>
/// <para>
/// <b>The trusted set is every path this code base addresses with a selection across nodes</b>, enumerated from
/// the Akka 1.5.62 sources and this repo (no other <c>ActorSelection</c> crosses a node boundary):
/// <list type="bullet">
/// <item><c>/system/cluster/core/daemon</c> — Akka.Cluster gossip, InitJoin/Join/Welcome, seed-node processes,
/// leave/exiting.</item>
/// <item><c>/system/cluster/heartbeatReceiver</c> — cluster failure-detector heartbeats.</item>
/// <item><c>/system/remote-watcher</c> — remote-watch heartbeats (<c>RemoteWatcher</c>/<c>ClusterRemoteWatcher</c>).</item>
/// <item><c>/system/distributedPubSubMediator</c> — DistributedPubSub registry gossip (redundancy-state, DPS
/// transports, secrets replication).</item>
/// <item><c>/user/{name}</c>, <c>/user/{name}/{name}</c> — each cluster singleton's manager (hand-over
/// protocol between managers) and the singleton itself (the proxies' <c>Identify</c>); see
/// <see cref="SingletonNames"/>.</item>
/// <item><c>/user/driver-host</c> — the AdminUI's <c>/fleet/diagnostics</c> query (<c>FleetDiagnosticsClient</c>).</item>
/// </list>
/// A drop is logged at <b>Warning</b> naming the path (once per path) and counted on
/// <c>otopcua.cluster.remoting.untrusted_drops</c>, so a missed path is loud, not a silent outage.
/// </para>
/// </remarks>
public static class RemotingHardening
{
/// <summary>
/// The cluster singleton names this code base registers (<c>ControlPlane.ServiceCollectionExtensions</c>). A test
/// fails if a singleton is added there without being added here.
/// </summary>
public static readonly IReadOnlyList<string> SingletonNames =
[
"config-publish",
"admin-operations",
"audit-writer",
"redundancy-state",
"cluster-node-address-reconciler",
"deployment-retention",
];
/// <summary>The Akka infrastructure paths a peer reaches by selection.</summary>
public static readonly IReadOnlyList<string> InfrastructurePaths =
[
"/system/cluster/core/daemon",
"/system/cluster/heartbeatReceiver",
"/system/remote-watcher",
"/system/distributedPubSubMediator",
];
/// <summary>The driver host actor (<c>Runtime.ServiceCollectionExtensions.DriverHostActorName</c>), queried for diagnostics.</summary>
public const string DriverHostPath = "/user/driver-host";
/// <summary>The metric counting inbound remote messages dropped by untrusted-mode.</summary>
public const string DropCounterName = "otopcua.cluster.remoting.untrusted_drops";
private static readonly Meter Meter = new("ZB.MOM.WW.OtOpcUa.Cluster.Remoting");
private static readonly Counter<long> DropCounter = Meter.CreateCounter<long>(DropCounterName);
private static readonly ConcurrentDictionary<ActorSystem, ConcurrentQueue<string>> Drops = new();
private static readonly Regex PathPattern = new(@"^/(user|system)(/[A-Za-z0-9\-_.*$+:@&=,!~';]+)+$", RegexOptions.Compiled);
private static readonly Regex ThumbprintPattern = new("^[0-9A-Fa-f]{40}$", RegexOptions.Compiled);
/// <summary>Every path a peer may reach by <c>ActorSelection</c> (before <see cref="AkkaRemotingOptions.AdditionalTrustedSelectionPaths"/>).</summary>
public static IReadOnlyList<string> TrustedSelectionPaths { get; } = BuildTrustedPaths();
private static IReadOnlyList<string> BuildTrustedPaths()
{
var paths = new List<string>(InfrastructurePaths);
foreach (var name in SingletonNames)
{
paths.Add($"/user/{name}");
paths.Add($"/user/{name}/{name}");
}
paths.Add(DriverHostPath);
return paths;
}
/// <summary>Builds the <c>akka.remote</c> untrusted-mode HOCON for <paramref name="options"/>.</summary>
/// <param name="options">The remoting options.</param>
/// <returns>The HOCON (sets <c>untrusted-mode = off</c> explicitly when disabled).</returns>
public static string BuildUntrustedModeHocon(AkkaRemotingOptions options)
{
ArgumentNullException.ThrowIfNull(options);
if (!options.UntrustedMode) return "akka.remote.untrusted-mode = off";
var paths = TrustedSelectionPaths
.Concat((options.AdditionalTrustedSelectionPaths ?? []).Select(static p => p.Trim()).Where(static p => p.Length > 0))
.Distinct(StringComparer.Ordinal);
var sb = new StringBuilder("akka.remote {\n untrusted-mode = on\n trusted-selection-paths = [\n");
foreach (var path in paths) sb.Append(" \"").Append(path).Append("\"\n");
sb.Append(" ]\n}\n");
return sb.ToString();
}
/// <summary>The address scheme the transport uses: <c>akka.ssl.tcp</c> with TLS, <c>akka.tcp</c> without.</summary>
/// <param name="tls">The TLS options.</param>
/// <returns>The protocol part of an address.</returns>
public static string Scheme(AkkaRemotingTlsOptions? tls) => tls is { Enabled: true } ? "akka.ssl.tcp" : "akka.tcp";
/// <summary>
/// Rewrites a seed's scheme to the one the transport uses, so <c>Cluster:SeedNodes</c> need not change when TLS is
/// switched (an <c>akka.tcp</c> seed would otherwise never be dialled by a TLS transport). Anything that is not an
/// <c>akka.tcp</c>/<c>akka.ssl.tcp</c> address is returned unchanged.
/// </summary>
/// <param name="seed">The configured seed.</param>
/// <param name="tls">The TLS options.</param>
/// <returns>The seed with the active scheme.</returns>
public static string NormalizeSeed(string seed, AkkaRemotingTlsOptions? tls)
{
if (string.IsNullOrWhiteSpace(seed)) return seed;
var trimmed = seed.Trim();
var scheme = Scheme(tls);
foreach (var known in new[] { "akka.ssl.tcp://", "akka.tcp://" })
{
if (trimmed.StartsWith(known, StringComparison.OrdinalIgnoreCase))
return scheme + "://" + trimmed[known.Length..];
}
return seed;
}
/// <summary>Validates the remoting options; returns one message per problem.</summary>
/// <param name="options">The options.</param>
/// <returns>The problems (empty when valid).</returns>
public static IEnumerable<string> Validate(AkkaRemotingOptions? options)
{
if (options is null) yield break;
foreach (var path in options.AdditionalTrustedSelectionPaths ?? [])
{
if (!PathPattern.IsMatch(path?.Trim() ?? string.Empty))
yield return $"Cluster:Remoting:AdditionalTrustedSelectionPaths entry '{path}' is not an actor path "
+ "(expected '/user/…' or '/system/…' with no address part).";
}
var tls = options.Tls;
if (tls is null || !tls.Enabled) yield break;
var hasPath = !string.IsNullOrWhiteSpace(tls.CertificatePath);
var hasThumb = !string.IsNullOrWhiteSpace(tls.CertificateThumbprint);
if (hasPath == hasThumb)
yield return "Cluster:Remoting:Tls:Enabled needs exactly one of CertificatePath (a .pfx) or CertificateThumbprint (a store certificate).";
if (hasPath && !Path.IsPathFullyQualified(tls.CertificatePath!))
yield return $"Cluster:Remoting:Tls:CertificatePath '{tls.CertificatePath}' must be an absolute path.";
else if (hasPath && !File.Exists(tls.CertificatePath))
yield return $"Cluster:Remoting:Tls:CertificatePath '{tls.CertificatePath}' does not exist.";
if (hasThumb && !ThumbprintPattern.IsMatch(NormalizeThumbprint(tls.CertificateThumbprint!)))
yield return "Cluster:Remoting:Tls:CertificateThumbprint must be a 40-hex-digit SHA-1 thumbprint.";
if (hasThumb && !Enum.TryParse<StoreName>(tls.CertificateStoreName, ignoreCase: true, out _))
yield return $"Cluster:Remoting:Tls:CertificateStoreName '{tls.CertificateStoreName}' is not a certificate store name.";
if (hasThumb && !Enum.TryParse<StoreLocation>(tls.CertificateStoreLocation, ignoreCase: true, out _))
yield return $"Cluster:Remoting:Tls:CertificateStoreLocation '{tls.CertificateStoreLocation}' is not CurrentUser or LocalMachine.";
foreach (var thumb in tls.AllowedThumbprints ?? [])
{
if (!ThumbprintPattern.IsMatch(NormalizeThumbprint(thumb ?? string.Empty)))
yield return $"Cluster:Remoting:Tls:AllowedThumbprints entry '{thumb}' is not a 40-hex-digit SHA-1 thumbprint.";
}
}
/// <summary>
/// Applies the TLS settings to <paramref name="remote"/>: loads the node certificate (PFX file or store) and sets
/// mutual authentication and the peer validator (thumbprint pinning, or chain validation when no pins are given;
/// hostname matching on request). No-op when TLS is off.
/// </summary>
/// <param name="remote">The remote options being built.</param>
/// <param name="tls">The TLS options (already validated).</param>
/// <exception cref="InvalidOperationException">The certificate cannot be loaded or has no private key.</exception>
public static void ApplyTls(RemoteOptions remote, AkkaRemotingTlsOptions? tls)
{
ArgumentNullException.ThrowIfNull(remote);
if (tls is not { Enabled: true }) return;
var certificate = LoadCertificate(tls);
if (!certificate.HasPrivateKey)
throw new InvalidOperationException(
$"Cluster:Remoting:Tls: the node certificate ({certificate.Subject}, {certificate.Thumbprint}) has no private key.");
CertificateValidationCallback? validator = null;
var pins = (tls.AllowedThumbprints ?? []).Select(NormalizeThumbprint).Where(static t => t.Length > 0).ToArray();
if (pins.Length > 0)
{
validator = CertificateValidation.PinnedCertificate(pins);
if (tls.ValidateCertificateHostname)
validator = CertificateValidation.Combine(validator, CertificateValidation.ValidateHostname());
}
remote.EnableSsl = true;
remote.Ssl = new SslOptions
{
X509Certificate = certificate,
SuppressValidation = false,
RequireMutualAuthentication = tls.RequireMutualAuthentication,
ValidateCertificateHostname = tls.ValidateCertificateHostname,
CustomValidator = validator,
};
}
private static X509Certificate2 LoadCertificate(AkkaRemotingTlsOptions tls)
{
if (!string.IsNullOrWhiteSpace(tls.CertificatePath))
{
try
{
// DefaultKeySet, as Kestrel loads a PFX: an ephemeral key cannot back an SslStream server on Windows
// (SChannel needs a key container) and is unsupported on macOS.
return X509CertificateLoader.LoadPkcs12FromFile(tls.CertificatePath, tls.CertificatePassword, X509KeyStorageFlags.DefaultKeySet);
}
catch (Exception ex) when (ex is System.Security.Cryptography.CryptographicException or IOException)
{
throw new InvalidOperationException(
$"Cluster:Remoting:Tls: cannot load the certificate '{tls.CertificatePath}': {ex.Message}", ex);
}
}
var thumbprint = NormalizeThumbprint(tls.CertificateThumbprint ?? string.Empty);
using var store = new X509Store(
Enum.Parse<StoreName>(tls.CertificateStoreName, ignoreCase: true),
Enum.Parse<StoreLocation>(tls.CertificateStoreLocation, ignoreCase: true));
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);
if (found.Count == 0)
throw new InvalidOperationException(
$"Cluster:Remoting:Tls: no certificate with thumbprint {thumbprint} in {tls.CertificateStoreLocation}\\{tls.CertificateStoreName}.");
return found[0];
}
private static string NormalizeThumbprint(string thumbprint)
=> new string(thumbprint.Where(static c => !char.IsWhiteSpace(c) && c != ':').ToArray()).ToUpperInvariant();
/// <summary>Paths of inbound selections (or daemon / harmful messages) <paramref name="system"/> dropped (tests, diagnostics).</summary>
/// <param name="system">The actor system.</param>
/// <returns>The drops recorded so far, oldest first (at most 1000).</returns>
public static IReadOnlyList<string> DroppedFor(ActorSystem system)
=> Drops.TryGetValue(system, out var q) ? q.ToArray() : [];
/// <summary>Spawns the monitor that turns Akka's Debug-level untrusted-mode drops into Warnings and a metric.</summary>
/// <param name="system">The actor system.</param>
public static void StartDropMonitor(ActorSystem system)
{
ArgumentNullException.ThrowIfNull(system);
var queue = Drops.GetOrAdd(system, static _ => new ConcurrentQueue<string>());
var monitor = system.ActorOf(Props.Create(() => new UntrustedDropMonitor(queue)), "untrusted-drop-monitor");
system.EventStream.Subscribe(monitor, typeof(Debug));
system.RegisterOnTermination(() => Drops.TryRemove(system, out _));
}
/// <summary>Classifies one Akka Debug message as an untrusted-mode drop.</summary>
/// <param name="message">The rendered message.</param>
/// <param name="what">What was dropped (the selection path, or the kind of message).</param>
/// <returns>True for a drop.</returns>
internal static bool TryParseDrop(string? message, out string what)
{
what = string.Empty;
if (string.IsNullOrEmpty(message)) return false;
const string selection = "operating in UntrustedMode, dropping inbound actor selection to [";
const string harmful = "operating in UntrustedMode, dropping inbound IPossiblyHarmful message of type ";
const string daemon = "dropping daemon message in untrusted mode";
if (message.StartsWith(selection, StringComparison.Ordinal))
{
var end = message.IndexOf(']', selection.Length);
what = end > selection.Length ? message[selection.Length..end] : message[selection.Length..];
return true;
}
if (message.StartsWith(harmful, StringComparison.Ordinal))
{
what = "IPossiblyHarmful " + message[harmful.Length..];
return true;
}
if (message.StartsWith(daemon, StringComparison.Ordinal))
{
what = "remote daemon (remote deployment)";
return true;
}
return false;
}
private static bool MightBeDrop(string? format)
=> format is not null
&& (format.StartsWith("operating in UntrustedMode", StringComparison.Ordinal)
|| format.StartsWith("dropping daemon message in untrusted mode", StringComparison.Ordinal));
private sealed class UntrustedDropMonitor : ReceiveActor
{
private const int MaxRecorded = 1000;
private const int MaxWarnedPaths = 256;
private readonly HashSet<string> _warned = new(StringComparer.Ordinal);
private readonly ILoggingAdapter _log = Context.GetLogger();
public UntrustedDropMonitor(ConcurrentQueue<string> drops)
{
Receive<Debug>(debug =>
{
// Cheap pre-filter on the format string: every Debug event of the system arrives here, and rendering
// each one would cost a format per event for nothing.
if (debug.Message is LogMessage lm && !MightBeDrop(lm.Format)) return;
if (!TryParseDrop(debug.Message?.ToString(), out var what)) return;
DropCounter.Add(1);
if (drops.Count < MaxRecorded) drops.Enqueue(what);
if (_warned.Count < MaxWarnedPaths && _warned.Add(what))
{
_log.Warning(
"Akka untrusted-mode dropped an inbound remote message: {0}. If this is a path OtOpcUa itself uses, add it to "
+ "Cluster:Remoting:AdditionalTrustedSelectionPaths and report it (lmxopcua#1003); otherwise a peer is "
+ "addressing an actor it should not. Further drops of it are counted on {1} only.",
what, DropCounterName);
}
});
}
}
}
@@ -144,12 +144,23 @@ public static class ServiceCollectionExtensions
setup.AddLogger<SerilogLogger>();
});
builder.WithRemoting(new RemoteOptions
var remote = new RemoteOptions
{
HostName = options.Hostname,
Port = options.Port,
PublicHostName = options.PublicHostname,
});
};
// lmxopcua#1003: opt-in mutual TLS on the transport (no-op unless Cluster:Remoting:Tls:Enabled).
RemotingHardening.ApplyTls(remote, options.Remoting?.Tls);
builder.WithRemoting(remote);
// lmxopcua#1003: untrusted-mode (default on) — inbound ActorSelection only to the paths this code base uses
// across nodes, no remote deployment, no PoisonPill/Kill from a peer. Prepend: highest precedence, so no other
// fragment (or a stray akka.remote block) silently turns it off. Drops become Warnings + a metric.
var remoting = options.Remoting ?? new AkkaRemotingOptions();
builder.AddHocon(RemotingHardening.BuildUntrustedModeHocon(remoting), HoconAddMode.Prepend);
if (remoting.UntrustedMode)
builder.WithActors((system, _) => RemotingHardening.StartDropMonitor(system));
builder.WithClustering(BuildClusterOptions(options));
@@ -283,7 +294,13 @@ public static class ServiceCollectionExtensions
// unjoined and ClusterBootstrapCoordinator picks the order (founder self-first / joiner
// peer-first, after a reachability probe) and issues the single Cluster.JoinSeedNodes.
// The config seed list is still read — by the coordinator, off AkkaClusterOptions.SeedNodes.
SeedNodes = options.BootstrapGuard.Enabled ? Array.Empty<string>() : options.SeedNodes,
//
// lmxopcua#1003: each seed's scheme follows the transport (akka.ssl.tcp under TLS), so an operator switching
// TLS on does not also have to respell every seed.
SeedNodes = options.BootstrapGuard.Enabled
? Array.Empty<string>()
: (options.SeedNodes ?? Array.Empty<string>())
.Select(s => RemotingHardening.NormalizeSeed(s, options.Remoting?.Tls)).ToArray(),
Roles = options.Roles,
SplitBrainResolver = IsKeepOldest(options) ? new KeepOldestOption { DownIfAlone = true } : null,
};
@@ -58,7 +58,9 @@ public sealed class FleetDiagnosticsClient : IFleetDiagnosticsClient
{
// Inside the try: a malformed node value makes ActorSelection throw, and that must degrade to
// "unavailable" like a dead node does, not surface through the page's error boundary.
var selection = _system.ActorSelection($"akka.tcp://{_systemName}@{nodeId.Value}/user/driver-host");
// lmxopcua#1003: the scheme follows this node's own transport (akka.ssl.tcp under Cluster:Remoting:Tls).
var scheme = _system is ExtendedActorSystem ext ? ext.Provider.DefaultAddress.Protocol : "akka.tcp";
var selection = _system.ActorSelection($"{scheme}://{_systemName}@{nodeId.Value}/user/driver-host");
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct);
linked.CancelAfter(AskTimeout);
return await selection.Ask<NodeDiagnosticsSnapshot>(