diff --git a/.claude/rules/cluster-topology.md b/.claude/rules/cluster-topology.md index 36a2d1c10..43c2a11c8 100644 --- a/.claude/rules/cluster-topology.md +++ b/.claude/rules/cluster-topology.md @@ -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. diff --git a/docs/Configuration.md b/docs/Configuration.md index 99c1c6210..574a84ff5 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -173,6 +173,9 @@ Security__Ldap__GroupToRole__=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. diff --git a/docs/security.md b/docs/security.md index 6e9199988..e26774251 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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). + --- diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptions.cs index 2aa534268..215963ef8 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptions.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptions.cs @@ -103,6 +103,12 @@ public sealed class AkkaClusterOptions /// ClusterBootstrapCoordinator for the runtime. /// public ClusterBootstrapGuardOptions BootstrapGuard { get; set; } = new(); + + /// + /// Akka remoting hardening (Cluster:Remoting, lmxopcua#1003): untrusted-mode with the trusted selection + /// paths (on by default) and transport TLS (opt-in). See . + /// + public AkkaRemotingOptions Remoting { get; set; } = new(); } /// diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptionsValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptionsValidator.cs index f622d9b1d..59d319a81 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptionsValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaClusterOptionsValidator.cs @@ -67,6 +67,7 @@ public sealed class AkkaClusterOptionsValidator : OptionsValidatorBase(); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaRemotingOptions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaRemotingOptions.cs new file mode 100644 index 000000000..cc8bc1632 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/AkkaRemotingOptions.cs @@ -0,0 +1,79 @@ +namespace ZB.MOM.WW.OtOpcUa.Cluster; + +/// +/// Hardening of the Akka remoting endpoint every node listens on (Cluster:Remoting, lmxopcua#1003, review +/// 2026-12-02 A-1 follow-up). Two independent controls: +/// +/// — on by default: inbound ActorSelection is delivered only to the +/// paths this code base actually addresses across nodes (), +/// remote deployment is refused, and PoisonPill/Kill-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. +/// — off by default (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. +/// +/// +public sealed class AkkaRemotingOptions +{ + /// + /// Gets or sets whether Akka's untrusted-mode is on. Default . Set + /// only as an escape hatch while reporting a missing path (the drop is logged as a Warning + /// naming it; is the targeted fix). + /// + public bool UntrustedMode { get; set; } = true; + + /// + /// Gets or sets extra actor paths (/user/… or /system/…, no address) a peer may reach with an + /// ActorSelection, on top of . + /// + public string[] AdditionalTrustedSelectionPaths { get; set; } = []; + + /// Gets or sets the transport TLS settings (opt-in). + public AkkaRemotingTlsOptions Tls { get; set; } = new(); +} + +/// +/// TLS on the Akka remoting transport (Cluster:Remoting:Tls). Opt-in; see docs/security.md §"Akka +/// remoting" for the rollout (both nodes of a pair, and every node a central admin dials for diagnostics, together). +/// +public sealed class AkkaRemotingTlsOptions +{ + /// Gets or sets whether the remoting transport runs TLS. Default . + /// + /// Changes the address scheme from akka.tcp to akka.ssl.tcp. Cluster:SeedNodes may keep + /// either spelling: the scheme is rewritten to match this switch at startup. + /// + public bool Enabled { get; set; } + + /// Gets or sets the node certificate as a PKCS#12 (.pfx) file, with its private key. Absolute path. + public string? CertificatePath { get; set; } + + /// Gets or sets the PFX password — supply it as ${secret:…} or an environment variable, never committed. + public string? CertificatePassword { get; set; } + + /// Gets or sets the node certificate's SHA-1 thumbprint in a certificate store (alternative to ). + public string? CertificateThumbprint { get; set; } + + /// Gets or sets the store name for . Default My. + public string CertificateStoreName { get; set; } = "My"; + + /// Gets or sets the store location for . Default LocalMachine. + public string CertificateStoreLocation { get; set; } = "LocalMachine"; + + /// + /// Gets or sets whether an inbound peer must present a certificate too. Default — without it + /// the transport is encrypted but any host can still associate (and join), which is the threat this exists for. + /// + public bool RequireMutualAuthentication { get; set; } = true; + + /// Gets or sets whether the peer certificate's CN/SAN must match the host it was dialled at. Default off. + public bool ValidateCertificateHostname { get; set; } + + /// + /// 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. + /// + public string[] AllowedThumbprints { get; set; } = []; +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapCoordinator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapCoordinator.cs index 9df34be7e..99fd3cd9e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapCoordinator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapCoordinator.cs @@ -78,7 +78,10 @@ public sealed class ClusterBootstrapCoordinator : IHostedService { try { - var seeds = _options.SeedNodes ?? Array.Empty(); + // lmxopcua#1003: the transport's scheme (akka.ssl.tcp under TLS) wins over the configured spelling. + var seeds = (_options.SeedNodes ?? Array.Empty()) + .Select(s => RemotingHardening.NormalizeSeed(s, _options.Remoting?.Tls)) + .ToArray(); var role = ClusterBootstrapGuard.Analyze(seeds, _options.PublicHostname, _options.Port); string[] order; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapGuard.cs index b84b2afa5..a80bff662 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapGuard.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ClusterBootstrapGuard.cs @@ -44,7 +44,7 @@ namespace ZB.MOM.WW.OtOpcUa.Cluster; public static class ClusterBootstrapGuard { private static readonly Regex SeedPattern = - new(@"^akka(?:\.[a-z0-9]+)?://[^@/]+@(?[^:/]+):(?\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); + new(@"^akka(?:\.[a-z0-9]+)*://[^@/]+@(?[^:/]+):(?\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// The analyzed bootstrap role of this node within its seed list. /// True only when the guard engages: exactly two seeds, one of them this node. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/RemotingHardening.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/RemotingHardening.cs new file mode 100644 index 000000000..9a61cb89f --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/RemotingHardening.cs @@ -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; + +/// +/// Builds the Akka remoting hardening for (lmxopcua#1003): the untrusted-mode +/// HOCON with the trusted selection paths, the TLS transport settings, and the scheme normalisation of seed addresses. +/// +/// +/// +/// What untrusted-mode does in Akka.NET 1.5 (read off Akka.Remote.DefaultMessageDispatcher, the only +/// consumer of the setting): an inbound ActorSelection is delivered only when its path is listed in +/// trusted-selection-paths (and its payload is not IPossiblyHarmful); a message for the remote +/// daemon (remote deployment) is dropped; an IPossiblyHarmful message (PoisonPill, Kill, …) +/// 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, Ask 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 +/// (mutual TLS) is for. +/// +/// +/// The trusted set is every path this code base addresses with a selection across nodes, enumerated from +/// the Akka 1.5.62 sources and this repo (no other ActorSelection crosses a node boundary): +/// +/// /system/cluster/core/daemon — Akka.Cluster gossip, InitJoin/Join/Welcome, seed-node processes, +/// leave/exiting. +/// /system/cluster/heartbeatReceiver — cluster failure-detector heartbeats. +/// /system/remote-watcher — remote-watch heartbeats (RemoteWatcher/ClusterRemoteWatcher). +/// /system/distributedPubSubMediator — DistributedPubSub registry gossip (redundancy-state, DPS +/// transports, secrets replication). +/// /user/{name}, /user/{name}/{name} — each cluster singleton's manager (hand-over +/// protocol between managers) and the singleton itself (the proxies' Identify); see +/// . +/// /user/driver-host — the AdminUI's /fleet/diagnostics query (FleetDiagnosticsClient). +/// +/// A drop is logged at Warning naming the path (once per path) and counted on +/// otopcua.cluster.remoting.untrusted_drops, so a missed path is loud, not a silent outage. +/// +/// +public static class RemotingHardening +{ + /// + /// The cluster singleton names this code base registers (ControlPlane.ServiceCollectionExtensions). A test + /// fails if a singleton is added there without being added here. + /// + public static readonly IReadOnlyList SingletonNames = + [ + "config-publish", + "admin-operations", + "audit-writer", + "redundancy-state", + "cluster-node-address-reconciler", + "deployment-retention", + ]; + + /// The Akka infrastructure paths a peer reaches by selection. + public static readonly IReadOnlyList InfrastructurePaths = + [ + "/system/cluster/core/daemon", + "/system/cluster/heartbeatReceiver", + "/system/remote-watcher", + "/system/distributedPubSubMediator", + ]; + + /// The driver host actor (Runtime.ServiceCollectionExtensions.DriverHostActorName), queried for diagnostics. + public const string DriverHostPath = "/user/driver-host"; + + /// The metric counting inbound remote messages dropped by untrusted-mode. + 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 DropCounter = Meter.CreateCounter(DropCounterName); + private static readonly ConcurrentDictionary> 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); + + /// Every path a peer may reach by ActorSelection (before ). + public static IReadOnlyList TrustedSelectionPaths { get; } = BuildTrustedPaths(); + + private static IReadOnlyList BuildTrustedPaths() + { + var paths = new List(InfrastructurePaths); + foreach (var name in SingletonNames) + { + paths.Add($"/user/{name}"); + paths.Add($"/user/{name}/{name}"); + } + paths.Add(DriverHostPath); + return paths; + } + + /// Builds the akka.remote untrusted-mode HOCON for . + /// The remoting options. + /// The HOCON (sets untrusted-mode = off explicitly when disabled). + 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(); + } + + /// The address scheme the transport uses: akka.ssl.tcp with TLS, akka.tcp without. + /// The TLS options. + /// The protocol part of an address. + public static string Scheme(AkkaRemotingTlsOptions? tls) => tls is { Enabled: true } ? "akka.ssl.tcp" : "akka.tcp"; + + /// + /// Rewrites a seed's scheme to the one the transport uses, so Cluster:SeedNodes need not change when TLS is + /// switched (an akka.tcp seed would otherwise never be dialled by a TLS transport). Anything that is not an + /// akka.tcp/akka.ssl.tcp address is returned unchanged. + /// + /// The configured seed. + /// The TLS options. + /// The seed with the active scheme. + 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; + } + + /// Validates the remoting options; returns one message per problem. + /// The options. + /// The problems (empty when valid). + public static IEnumerable 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(tls.CertificateStoreName, ignoreCase: true, out _)) + yield return $"Cluster:Remoting:Tls:CertificateStoreName '{tls.CertificateStoreName}' is not a certificate store name."; + if (hasThumb && !Enum.TryParse(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."; + } + } + + /// + /// Applies the TLS settings to : 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. + /// + /// The remote options being built. + /// The TLS options (already validated). + /// The certificate cannot be loaded or has no private key. + 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(tls.CertificateStoreName, ignoreCase: true), + Enum.Parse(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(); + + /// Paths of inbound selections (or daemon / harmful messages) dropped (tests, diagnostics). + /// The actor system. + /// The drops recorded so far, oldest first (at most 1000). + public static IReadOnlyList DroppedFor(ActorSystem system) + => Drops.TryGetValue(system, out var q) ? q.ToArray() : []; + + /// Spawns the monitor that turns Akka's Debug-level untrusted-mode drops into Warnings and a metric. + /// The actor system. + public static void StartDropMonitor(ActorSystem system) + { + ArgumentNullException.ThrowIfNull(system); + var queue = Drops.GetOrAdd(system, static _ => new ConcurrentQueue()); + var monitor = system.ActorOf(Props.Create(() => new UntrustedDropMonitor(queue)), "untrusted-drop-monitor"); + system.EventStream.Subscribe(monitor, typeof(Debug)); + system.RegisterOnTermination(() => Drops.TryRemove(system, out _)); + } + + /// Classifies one Akka Debug message as an untrusted-mode drop. + /// The rendered message. + /// What was dropped (the selection path, or the kind of message). + /// True for a drop. + 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 _warned = new(StringComparer.Ordinal); + private readonly ILoggingAdapter _log = Context.GetLogger(); + + public UntrustedDropMonitor(ConcurrentQueue drops) + { + Receive(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); + } + }); + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ServiceCollectionExtensions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ServiceCollectionExtensions.cs index fda0c131e..72c65ad22 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ServiceCollectionExtensions.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Cluster/ServiceCollectionExtensions.cs @@ -144,12 +144,23 @@ public static class ServiceCollectionExtensions setup.AddLogger(); }); - 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() : 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() + : (options.SeedNodes ?? Array.Empty()) + .Select(s => RemotingHardening.NormalizeSeed(s, options.Remoting?.Tls)).ToArray(), Roles = options.Roles, SplitBrainResolver = IsKeepOldest(options) ? new KeepOldestOption { DownIfAlone = true } : null, }; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs index 80f6f1a6c..e6dec0938 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Clients/FleetDiagnosticsClient.cs @@ -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( diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/RemotingHardeningClusterTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/RemotingHardeningClusterTests.cs new file mode 100644 index 000000000..dc8845908 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/RemotingHardeningClusterTests.cs @@ -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; + +/// +/// lmxopcua#1003 on real clusters built through the shipped : +/// 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. +/// +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; + + /// Answers any string with the address of the node it runs on. + private sealed class Echo : ReceiveActor + { + public Echo() + { + var self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.ToString(); + Receive(_ => Sender.Tell(self)); + } + } + + /// Forwards whatever it receives to a TaskCompletionSource. + private sealed class Sink : ReceiveActor + { + public Sink(TaskCompletionSource got) + { + Receive(_ => { }); + ReceiveAny(m => got.TrySetResult(m)); + } + } + + private static async Task 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>(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("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(); + + private static async Task 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 AskUntilAsync(IActorRef target, Func accept, TimeSpan timeout) + { + var deadline = DateTime.UtcNow + timeout; + string last = "(no answer)"; + while (DateTime.UtcNow < deadline) + { + try + { + last = await target.Ask("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(); + } + + /// + /// 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. + /// + [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().Get(); + (await AskUntilAsync(proxyB, s => s.EndsWith($":{pa}"), FormTimeout)).ShouldEndWith($":{pa}"); + + // DistributedPubSub across the pair. + var got = new TaskCompletionSource(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); + } + } + + /// + /// Negative control: a selection to a path that is NOT trusted is dropped, recorded and never answered — while the + /// diagnostics path (/user/driver-host, 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. + /// + [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(new Identify(1), TimeSpan.FromSeconds(10), Ct); + diag.Subject.ShouldNotBeNull("positive control: the trusted diagnostics path is delivered"); + + await Should.ThrowAsync(() => fromB + .ActorSelection($"akka.tcp://{name}@127.0.0.1:{pa}/user/not-trusted") + .Ask(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); + } + } + + /// Falsifiability control for the test above: with untrusted-mode OFF the same selection IS delivered. + [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(new Identify(3), TimeSpan.FromSeconds(10), Ct); + identity.Subject.ShouldNotBeNull(); + } + finally + { + await StopAsync(hostA); + await StopAsync(hostB); + } + } + + /// + /// Opt-in mutual TLS: two nodes whose certificates pin each other form a mesh on akka.ssl.tcp (from seeds + /// still spelled akka.tcp — 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. + /// + [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 */ } + } + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/RemotingHardeningTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/RemotingHardeningTests.cs new file mode 100644 index 000000000..6aeddccaf --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Cluster.Tests/RemotingHardeningTests.cs @@ -0,0 +1,166 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Cluster.Tests; + +/// +/// 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 . +/// +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(); + } + + /// Every path the code base reaches by selection across nodes is trusted (see the remarks on ). + [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 }; +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/UntrustedModeHarnessTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/UntrustedModeHarnessTests.cs new file mode 100644 index 000000000..7cce7345b --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.IntegrationTests/UntrustedModeHarnessTests.cs @@ -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; + +/// +/// 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. +/// +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(); + 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(); + 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(); + 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"); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Configuration/RemotingTrustedPathsCoverageTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Configuration/RemotingTrustedPathsCoverageTests.cs new file mode 100644 index 000000000..bb846dd81 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Host.Tests/Configuration/RemotingTrustedPathsCoverageTests.cs @@ -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; + +/// +/// lmxopcua#1003: Akka untrusted-mode is ON by default, so a cross-node ActorSelection to a path missing from +/// 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 src/. +/// +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); + + /// + /// The only ActorSelection in src/ is the diagnostics client (which targets /user/driver-host). + /// A new one must come with its path in the trusted set — then add its file here. + /// + [Fact] + public void No_new_cross_node_actor_selection_appears_without_a_trusted_path() + { + var allowed = new HashSet(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; + } +}