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:
@@ -32,6 +32,15 @@ The server supports non-transparent warm/hot redundancy via the `Redundancy` sec
|
||||
|
||||
**Simultaneous cold-start splits — the bootstrap guard closes it (opt-in, `Cluster:BootstrapGuard:Enabled`, default OFF).** Self-first on BOTH nodes means when both cold-start at the same instant, each runs `FirstSeedNodeProcess`, times out, and forms its OWN 1-node cluster → two Primaries in one pair (the Phase 6 live gate reproduced this on docker; two separate clusters do NOT auto-merge). The guard prevents it without losing cold-start-alone: the lexicographically **lower** `host:port` node is the preferred founder (self-first, forms immediately); the **higher** node TCP-probes the partner's Akka port up to `PartnerProbeSeconds` (25s) — **reachable ⇒ peer-first (join the founder)**, **unreachable ⇒ self-first (partner dead, form alone)**. The order is chosen BEFORE the single `JoinSeedNodes`, from an explicit reachability signal — it never re-forms mid-handshake (the `SelfFormAfter` failure mode). When on, Akka gets NO config seeds (`BuildClusterOptions` empties `ClusterOptions.SeedNodes`) and `ClusterBootstrapCoordinator` drives the join. Residual trade (accepted, operator-visible via a warning + restart-recovers): the higher node hangs if the founder dies in the probe→join window. docker-dev: **site-a = guard demo** (guard on, serialization removed); **site-b = A/B control** (guard off, `depends_on: service_healthy` serialization). The guard is the production-faithful fix (compose `depends_on` doesn't exist on real VMs). Pinned by `ClusterBootstrapGuardTests` + `ClusterBootstrapCoordinatorTests` (real 2-node clusters, incl. the higher-node-cold-start-alone case). See `docs/Redundancy.md` §"Bootstrap guard".
|
||||
|
||||
**Akka remoting is hardened (lmxopcua#1003).** `Cluster:Remoting:UntrustedMode` is **on by default**: inbound
|
||||
`ActorSelection` reaches only `RemotingHardening.TrustedSelectionPaths` (cluster daemon + heartbeat receiver, remote-watcher,
|
||||
DPS mediator, `/user/{singleton}` + `/user/{singleton}/{singleton}` for each ControlPlane singleton, `/user/driver-host`).
|
||||
⚠️ **A new cluster singleton or a new cross-node `ActorSelection` must add its path** to `RemotingHardening` —
|
||||
`RemotingTrustedPathsCoverageTests` fails otherwise; a missed path is a Warning `untrusted-mode dropped …` + the
|
||||
`otopcua.cluster.remoting.untrusted_drops` counter, and the feature silently stops across nodes. Mutual TLS
|
||||
(`Cluster:Remoting:Tls`) is opt-in and all-or-nothing per link (scheme `akka.ssl.tcp`; seeds are rewritten) — flip both
|
||||
pair nodes together. See `docs/security.md` §"Akka remoting hardening".
|
||||
|
||||
Assert the **effective** cluster config off a running `ActorSystem` (as `SplitBrainResolverActivationTests` does), never the typed options or the akka.conf text — several HOCON fragments compete and the losing one still reads correctly in the file.
|
||||
|
||||
**RESOLVED by per-cluster mesh Phase 6 (2026-07-24) — no longer per-Akka-cluster.** The "one Primary across the whole Akka mesh" limitation described above is gone; see the Phase 6 paragraph immediately below.
|
||||
|
||||
@@ -173,6 +173,9 @@ Security__Ldap__GroupToRole__<AD group>=Viewer
|
||||
| `Port` | int | `4053` | Cluster transport port. **Duplicated as `ClusterNode.AkkaPort` in the Config DB** — see the note below. |
|
||||
| `PublicHostname` | string | `127.0.0.1` | Hostname advertised in cluster gossip; must be reachable by peers. **Duplicated as `ClusterNode.Host`** — see the note below. |
|
||||
| `SeedNodes` | string[] | `[]` | Seed nodes for bootstrapping. **Ordered:** a node that appears in its own list must be entry 0 (only `seed-nodes[0]` can form a new cluster), or the host refuses to start — see [Redundancy.md § Bootstrap: self-first seed ordering](Redundancy.md#bootstrap-self-first-seed-ordering). **Per-pair since Phase 6:** each application `Cluster`'s pair is its own Akka mesh, so a node's `SeedNodes` lists only itself (first) and its own pair partner (second) — never a node from another cluster's pair. |
|
||||
| `Remoting:UntrustedMode` | bool | `true` | Akka `untrusted-mode` with the trusted selection paths this code base uses (lmxopcua#1003). Receive-side only; a drop is a Warning naming the path. See [security.md § Akka remoting hardening](security.md#akka-remoting-hardening-clusterremoting-lmxopcua1003). |
|
||||
| `Remoting:AdditionalTrustedSelectionPaths` | string[] | `[]` | Extra `/user/…` / `/system/…` paths a peer may reach by selection. |
|
||||
| `Remoting:Tls:*` | object | `Enabled=false` | Opt-in mutual TLS on the remoting transport (`CertificatePath`+`CertificatePassword` or `CertificateThumbprint`+store, `RequireMutualAuthentication=true`, `AllowedThumbprints`, `ValidateCertificateHostname`). Both nodes of a pair change together. |
|
||||
| `Roles` | string[] | `[]` | Cluster roles for this node. When empty, falls back to `OTOPCUA_ROLES` (see the note below). Values are trimmed and (for a plain role) lower-cased; a cluster role's ClusterId suffix keeps the operator's spelling. An unknown role from either source **fails host start**. Allowed values: `admin`, `driver`, `dev`, plus a per-cluster `cluster-{ClusterId}` role (e.g. `cluster-MAIN`, `cluster-SITE-A`) — see [Per-cluster mesh split (Phase 6)](#per-cluster-mesh-split-phase-6-cluster-clusterid-roles--splittopologytransportvalidator) below. |
|
||||
|
||||
> **One role authority, one precedence, both consumers (archreview R3-04).** `EffectiveRoles.Resolve` (`ZB.MOM.WW.OtOpcUa.Cluster`) is the SINGLE place a node's roles are decided: `Cluster:Roles` wins outright when non-empty, else `OTOPCUA_ROLES`, else empty. Both `Program.cs`'s conditional host wiring (which subsystems mount) AND the Akka `AkkaClusterOptions.Roles` gossiped to the cluster are the SAME `EffectiveRoles` instance's `Gossiped` list — not two separate derivations that happen to usually agree. The boot banner (`OtOpcUa.Host starting with roles=[...] source=...`) names which source won. Setting both sources to *different* normalized role sets logs a Warning at boot (still resolves from `Cluster:Roles`) — almost certainly not what an operator intended.
|
||||
|
||||
+70
-1
@@ -1823,7 +1823,76 @@ The page used to feed `?node=` (or the typed host:port box) straight into an Akk
|
||||
|
||||
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.
|
||||
**Akka remoting itself** is hardened since lmxopcua#1003 — untrusted mode on by default, mutual TLS opt-in; see the
|
||||
next section.
|
||||
|
||||
### Akka remoting hardening (`Cluster:Remoting`, lmxopcua#1003)
|
||||
|
||||
Every node listens for Akka remoting on `Cluster:Port` (4053). Two independent controls, configured under
|
||||
`Cluster:Remoting`:
|
||||
|
||||
**1. Untrusted mode — ON by default.** `akka.remote.untrusted-mode = on` with an explicit
|
||||
`trusted-selection-paths` list (`RemotingHardening.TrustedSelectionPaths`). What it does in Akka.NET 1.5 (read off
|
||||
`Akka.Remote.DefaultMessageDispatcher`, the setting's only consumer): an inbound `ActorSelection` is delivered only to a
|
||||
listed path; messages for the remote daemon (**remote deployment**) are dropped; an `IPossiblyHarmful` message
|
||||
(`PoisonPill`, `Kill`, …) sent by a peer to any 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, `Ask` temp actors) and
|
||||
system messages (remote watch) are unaffected — so, contrary to the earlier note here, untrusted mode does **not** break
|
||||
cluster gossip, DPS or singletons, provided their selection paths are trusted. The trusted set is every path this code
|
||||
base reaches by selection across nodes, enumerated from the Akka 1.5.62 sources and this repo:
|
||||
|
||||
| Path | Used by |
|
||||
|---|---|
|
||||
| `/system/cluster/core/daemon` | Akka.Cluster gossip, InitJoin/Join/Welcome, the seed-node processes, leave/exiting |
|
||||
| `/system/cluster/heartbeatReceiver` | cluster failure-detector heartbeats |
|
||||
| `/system/remote-watcher` | remote-watch heartbeats |
|
||||
| `/system/distributedPubSubMediator` | DistributedPubSub registry gossip (redundancy-state, the DPS transports, secrets replication) |
|
||||
| `/user/{name}`, `/user/{name}/{name}` for each singleton (`config-publish`, `admin-operations`, `audit-writer`, `redundancy-state`, `cluster-node-address-reconciler`, `deployment-retention`) | manager-to-manager hand-over; the proxies' `Identify` |
|
||||
| `/user/driver-host` | `/fleet/diagnostics` (`FleetDiagnosticsClient`), also across meshes |
|
||||
|
||||
Coverage is proven, not asserted: `RemotingHardeningClusterTests` (real pairs through the shipped bootstrap — formation,
|
||||
a singleton reached through its proxy and handed over on leave, DPS across nodes, zero drops; a selection to any other
|
||||
path dropped; the same selection delivered with the mode off) and `UntrustedModeHarnessTests` (the full two-node Host
|
||||
stack — every ControlPlane singleton + proxy, the redundancy singleton, runtime actors, deploys from both nodes, the
|
||||
diagnostics selection, node B restarting — zero drops, with a positive control that the monitor records one).
|
||||
`RemotingTrustedPathsCoverageTests` fails when a new singleton constant or a new `ActorSelection` in `src/` appears
|
||||
without its path. A drop is logged as a **Warning** naming the path (once per path; Akka logs it at Debug) and counted on
|
||||
`otopcua.cluster.remoting.untrusted_drops`.
|
||||
|
||||
What it does **not** do: authenticate the peer. The cluster daemon must stay reachable for joining to work, so any host
|
||||
that can reach the port can still associate — and join. That is what TLS is for.
|
||||
|
||||
- **Upgrade:** nothing to configure; the filter is receive-side only, so a mixed old/new pair keeps working through a
|
||||
rolling upgrade (both send the same selections). If a drop Warning ever names a path OtOpcUa itself uses, add it to
|
||||
`Cluster:Remoting:AdditionalTrustedSelectionPaths` (and file it); `Cluster:Remoting:UntrustedMode = false` is the
|
||||
escape hatch.
|
||||
|
||||
**2. Mutual TLS — opt-in (`Cluster:Remoting:Tls:Enabled`, default `false`).** The DotNetty transport runs TLS, and with
|
||||
`RequireMutualAuthentication` (default `true`) the accepting side demands a client certificate too — so only a peer
|
||||
holding an accepted certificate can associate at all.
|
||||
|
||||
| Key | Default | Meaning |
|
||||
|---|---|---|
|
||||
| `Enabled` | `false` | TLS on the remoting transport. The address scheme becomes `akka.ssl.tcp`; `Cluster:SeedNodes` may keep `akka.tcp://` (rewritten at startup). |
|
||||
| `CertificatePath` / `CertificatePassword` | — | The node certificate as an absolute-path `.pfx` with its private key; supply the password as `${secret:…}` or an env var. |
|
||||
| `CertificateThumbprint` / `CertificateStoreName` / `CertificateStoreLocation` | — / `My` / `LocalMachine` | Alternatively, a certificate in a store (Windows). Exactly one source is required. |
|
||||
| `RequireMutualAuthentication` | `true` | Demand a client certificate on inbound associations. Turning it off leaves the link encrypted but open to any client. |
|
||||
| `AllowedThumbprints` | `[]` | SHA-1 thumbprints accepted from peers. Non-empty ⇒ pin only (self-signed works, no CA). Empty ⇒ the peer chain must validate against the machine trust store. |
|
||||
| `ValidateCertificateHostname` | `false` | Also require the peer certificate's CN/SAN to match the host it was dialled at. |
|
||||
|
||||
Startup refuses `Enabled` with no certificate source (or two), a relative or missing `CertificatePath`, a malformed
|
||||
thumbprint, or a certificate without a private key. Proven by
|
||||
`RemotingHardeningClusterTests.Mutual_tls_forms_a_mesh_between_pinned_peers_and_keeps_an_unpinned_node_out`.
|
||||
|
||||
- **Rollout (TLS is all-or-nothing per link).** A TLS node and a plain node cannot associate, so: issue one certificate
|
||||
per node (or one per pair), put every peer's thumbprint in `AllowedThumbprints` on **both** nodes of a pair, then
|
||||
**stop both nodes, set `Cluster:Remoting:Tls` on both, start both** — a one-at-a-time restart leaves the pair split
|
||||
across the change (each side forms its own cluster ⇒ two Primaries until the second node is converted). An admin
|
||||
node's `/fleet/diagnostics` dials every node's `driver-host` over remoting, so either convert the whole fleet or
|
||||
expect diagnostics of a node on the other transport to come back empty (it degrades, it does not fail). The
|
||||
certificates of the admin nodes must be pinned on the nodes they query.
|
||||
- Rolling back is the same in reverse (both nodes together).
|
||||
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -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>(
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
+63
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user