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/CLAUDE.md b/CLAUDE.md index cec0eccf5..92499ac48 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -410,7 +410,7 @@ lists `ScriptedAlarm` — never by default) in `ZB.MOM.WW.OtOpcUa.ScriptWorker` (`src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess`, protocol in `Core.Scripting.Protocol`), shipped in `script-worker/` beside the host (self-contained + started via its apphost on a `-r win-x64 --self-contained` publish, through the muxer otherwise); a runner-side failure publishes `BadResourceUnavailable` (ScadaBridge-visible, ScadaBridge#112) and the seam re-evaluates when the worker is back. `IScriptRunner.RunBatch` sends ready evaluations as one frame per worker (Calc pump, VT coalescer, -alarm dirty set); a run queued behind busy worker threads has its deadlines restarted when it starts, so it is never blamed for a sibling. The soft deadline is the **worker's** clock from the run's start (#827, negotiated via `Hello`/`Ready.worker_soft_clock`); wall clock from there, so a pause during the run still counts. The host keeps a T + G transport deadline (passing it is a runner fault: `script worker unresponsive` → `BadResourceUnavailable`, Shadow `shadow_unavailable`; a later soft notice still cancels and counts the timeout) and a progress ceiling (`killed_unresponsive`) so it never depends on the worker's notices. Optional `Scripting:Worker:PeCacheDir` = HMAC'd compiled-PE cache (restart without Roslyn); optional (Windows) `Scripting:Worker:Identity` = `NT SERVICE\OtOpcUaScriptWorker` runs workers under a restricted token, set up by `scripts/install/Install-ScriptWorkerIsolation.ps1` (ACLs + outbound firewall block; `docs/ServiceHosting.md`); the `script-runner` +alarm dirty set); a run queued behind busy worker threads has its deadlines restarted when it starts, so it is never blamed for a sibling. The soft deadline is the **worker's** clock from the run's start (#827, negotiated via `Hello`/`Ready.worker_soft_clock`); wall clock from there, so a pause during the run still counts. The host keeps a T + G transport deadline (passing it is a runner fault: `script worker unresponsive` → `BadResourceUnavailable`, Shadow `shadow_unavailable`; a later soft notice still cancels and counts the timeout) and a progress ceiling (`killed_unresponsive`) so it never depends on the worker's notices. Optional `Scripting:Worker:PeCacheDir` = HMAC'd compiled-PE cache (restart without Roslyn; host-owned since #1014 — the host verifies, compiles and signs, workers never hold the key); optional (Windows) `Scripting:Worker:Identity` = `NT SERVICE\OtOpcUaScriptWorker` runs workers under a restricted token, set up by `scripts/install/Install-ScriptWorkerIsolation.ps1` (ACLs + outbound firewall block; `docs/ServiceHosting.md`); the `script-runner` readiness check is at worst Degraded (never fails ready). The worker tests are `tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests` (`Category=ScriptWorker`, real processes; `Category=Perf` harness opt-in via `OTOPCUA_SCRIPT_PERF=1`). docker-dev overlay: `docker-dev/docker-compose.script-runner.yml`. See `docs/VirtualTags.md` diff --git a/docs/Configuration.md b/docs/Configuration.md index 2319daa46..47bf26ab6 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/ServiceHosting.md b/docs/ServiceHosting.md index 9c743f65a..9d26bbd6c 100644 --- a/docs/ServiceHosting.md +++ b/docs/ServiceHosting.md @@ -97,7 +97,8 @@ and a Shutdown frame then a kill on host stop. Their stderr lands in the host lo At startup the host kills workers a dead predecessor of the same install left behind, matched by launch marker (pid + start time + image, and only when the marker's host is gone). `Scripting:Worker:PeCacheDir`, when set, holds the compiled-PE cache, its HMAC key and the launch markers: put it outside the install folder (startup refuses a relative path -or one inside the content root) on a directory only the service account can read. The `script-runner` readiness component +or one inside the content root) on a directory only the service account can read. Since lmxopcua#1014 only the host reads +or writes it (workers receive verified images over the pipe, never the key). The `script-runner` readiness component is at worst Degraded. A self-contained host publish (`dotnet publish … -r win-x64 --self-contained`, the Windows installs, which have no .NET runtime) ships a **self-contained** worker in `script-worker/` (~97 MB: it carries its own runtime) and the host starts its `ZB.MOM.WW.OtOpcUa.ScriptWorker.exe` apphost directly; a framework-dependent host (docker-dev) runs the worker's dll through the @@ -113,7 +114,7 @@ dotnet muxer. See `docs/VirtualTags.md` §"Out-of-process runner". | Worker identity | A **disabled** anchor service `OtOpcUaScriptWorker` running as `NT SERVICE\OtOpcUaScriptWorker`, so the virtual account exists. It is never started. | | `Scripting:Worker:Identity` | With `NT SERVICE\OtOpcUaScriptWorker` set (by `-ConfigureHostService`, or in appsettings), the host starts every worker under a **restricted token** derived from its own: every privilege but `SeChangeNotifyPrivilege` removed, and restricting SIDs = the identity + `Everyone` + `BUILTIN\Users` + `RESTRICTED`. Every access the worker makes must pass for the host account **and** for that set. The token's default DACL is host + SYSTEM + identity; the worker is created suspended and put in its Job Object before it runs; `TEMP`/`TMP` point at its per-launch working directory (ACL: host + SYSTEM full, identity Modify); `DOTNET_EnableDiagnostics=0`. The host also adds the identity to its own window station and desktop DACL (enumerate/read, and create-window on the desktop), once per process. USER32 connects to them in its DllMain and the runtime imports USER32, so without the grant `coreclr.dll` fails to load (`ERROR_DLL_INIT_FAILED`, measured on windev). The grant lives on the session's kernel objects and ends with the session; nothing persistent changes. The logon SID, which those objects normally grant, is deliberately not a restricting SID: the host's process DACL gives it `PROCESS_VM_READ`. Windows cannot start an ad-hoc child process *as* a virtual account (only the SCM can, for a service), and a separate local user would need a stored password plus `SeAssignPrimaryTokenPrivilege` on the host account; a restricted copy of the host's own token needs neither. Startup refuses the key off Windows or when malformed. | | Pipe ACL | On Windows the worker pipe always carries an explicit, protected DACL: the host account and (with an identity) the worker identity, read/write, nobody else. No SYSTEM, no Administrators, no Everyone. The owner is the host token's owner, so the worker's `CurrentUserOnly` check of the server end still holds. | -| `PeCacheDir` | Created with a protected ACL: SYSTEM, Administrators and the host account full control, no Users. `pe\` grants the identity Modify (workers compile and write entries). The HMAC key and `workers\` markers are host-only. | +| `PeCacheDir` | Created with a protected ACL: SYSTEM, Administrators and the host account full control, no Users. `pe\` grants the identity Modify — **unused since lmxopcua#1014**: the host now verifies, compiles and writes every entry and sends verified images over the pipe, so a worker no longer touches the directory (anything it could still drop in `pe\` fails the host's HMAC check; removing the grant is a follow-up). The HMAC key and `workers\` markers are host-only. | | Install folder | The identity is **denied** read and write on `` (inherited: ReadData/List, WriteData/AddFile, AppendData/AddSubdirectory, write attributes/EA, Delete, DeleteChild, ChangePermissions, TakeOwnership; Traverse/Execute, ReadAttributes and ReadPermissions stay so the loader reaches `script-worker\`). The worker cannot read `appsettings*.json`, logs or host binaries even where `Users` can. `script-worker\` grants it read + execute. | | Sensitive folders (`-DenyPaths`, lmxopcua#890) | The same inherited deny on every listed folder. **Name every folder outside `` that holds keys, secrets, stores, logs or backups**: the worker's restricting SIDs include `Everyone` and `BUILTIN\Users`, so anything Users can read is otherwise readable to it (and a data drive usually lets Users create files in subfolders, e.g. a certificate in `pki\trusted\certs`). Name the deployment folder around `` (one ACE covers `pki\`, `data\`, `logs\`, `backup\`, old `app.bak.*`) **and** `pki\` and `data\` themselves, so the deny holds even on a folder whose DACL does not inherit. Drive and share roots, `script-worker\` and the PE cache are refused; each folder must exist. The list is recorded under `HKLM\…\Services\OtOpcUaScriptWorker\Parameters` (`DenyPaths`): a re-run removes the deny from folders dropped from the list, and `-Uninstall` removes every recorded one without repeating `-DenyPaths`. After an apply the installer WARNs about any item under a denied folder whose DACL is protected and has no deny of its own (the inherited deny does not reach it); without `-DenyPaths` it WARNs about `pki`/`data`/`logs`/`backup`/`config`/`secrets` siblings of ``. Wonder layout: `-InstallRoot E:\ApiInstall\OtOpcUa\app -DenyPaths E:\ApiInstall\OtOpcUa,E:\ApiInstall\OtOpcUa\pki,E:\ApiInstall\OtOpcUa\data,C:\ProgramData\ZB\kek` plus, box-wide (lmxopcua#891), every other app folder under `E:\ApiInstall` and the staging folders `E:\psrem-stage`, `E:\psrem`; keep deploy backups (`.reg` exports, appsettings copies) in a folder with a protected SYSTEM + Administrators ACL. | | Firewall | Outbound **block** rule `OtOpcUa-ScriptWorker-BlockOutbound` on `script-worker\ZB.MOM.WW.OtOpcUa.ScriptWorker.exe`, every profile. It covers the self-contained apphost the Windows installs run. A framework-dependent worker runs under `dotnet.exe` and is not covered, so there the analyzer's `System.Net` ban is the only network control. | diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 49f93d82b..ef0ef13ea 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -147,15 +147,33 @@ processes: `Unavailable`: one Error is logged, evaluations answer `script runner unavailable` at once instead of each waiting out `UnavailableGrace`, and the shards keep retrying at the backoff cap. - **Compiled-PE cache** (`Scripting:Worker:PeCacheDir`, optional; absolute and outside the content root, or startup - fails). Workers write each compiled image to `/pe/.pe`, authenticated with HMAC-SHA256 under a per-node - random key (`/pe-cache.key`, created by the host; 0600 / directory 0700 on Linux and macOS, the directory ACL on - Windows), and a restarted worker loads the image instead of re-entering Roslyn. The id is SHA-256 over the source, the - context kind and a compile fingerprint (Roslyn version, the `Core.Scripting` build — analyzer, wrapper, stack guard —, - the sandbox reference set, the runtime), so a compiler or analyzer change misses every old entry. An entry that fails - verification (edited, truncated, another key, copied under another id) is deleted and the source recompiled; the - worker never loads bytes that did not verify. The key reaches the worker in `Hello`, never on disk or in its - environment. Entries unused for 30 days, and the least recently used beyond 50 000, are pruned at startup; the - directory can be deleted at any time. Measured on macOS (40 scripts, restart to every first result): 820 ms with no + fails). Each compiled image lives in `/pe/.pe`, authenticated with HMAC-SHA256 under a per-node random key + (`/pe-cache.key`, created by the host; 0600 / directory 0700 on Linux and macOS, the directory ACL on Windows), and + a restarted worker loads the image instead of re-entering Roslyn. The id is SHA-256 over the source, the context kind + and a compile fingerprint (Roslyn version, the `Core.Scripting` build — analyzer, wrapper, stack guard —, the sandbox + reference set, the runtime), so a compiler or analyzer change misses every old entry. An entry that fails verification + (edited, truncated, another key, copied under another id) is deleted and the source recompiled. Entries unused for 30 + days, and the least recently used beyond 50 000, are pruned at startup; the directory can be deleted at any time. + - **The host owns the cache; the worker holds no key (lmxopcua#1014, review K-1 option 4).** Until #1014 the worker read, + verified and *wrote* entries with the key it was handed in `Hello`, and a verified image is loaded without re-running + the analyzer — so code that escaped inside a worker could sign an entry for any script's source and persist across + restarts and redeploys. Now the host reads and verifies the entry and ships the image inside the load + (`ScriptSource.pe_image`); on a miss the worker compiles as before and, only once that compile has **succeeded**, the + host queues **its own** compile of the same source (one background thread, below-normal priority, de-duplicated; the + same pipeline and analyzer as the in-process runner and the deploy gate, never loaded in the host) and writes the + signed entry. Filling after the worker's success keeps a source that crashes Roslyn inside the worker's isolation + machinery. `Hello` carries neither the key nor the directory, so the worker never opens the cache. + - **Compatibility.** The host compiles against its own runtime, so it ships images only to a worker whose + `Ready.pe_image_abi` (`ScriptSandbox.ImageAbi`: runtime version + the pinned assemblies' full names) equals its own; + any other worker compiles every script (one Warning per distinct value). An image that does not load in the worker is + reported `rejected`, the source compiled, and the host evicts and refills the entry. + - **Upgrade.** The entry format moved to version 2: every entry a pre-#1014 worker wrote (any of which may have been + forged) fails the magic check on first use, is deleted, and is refilled by the host — the first start after the + upgrade is a cold one. `Scripting:Worker:PeCacheDir` and the directory layout are unchanged; nothing to configure. The + installer's `pe\` Modify grant to the worker identity is now unused (a worker could only drop or add files the host + then rejects); removing it is a follow-up. + - **Cost.** A miss now compiles twice — once in the worker (to run), once in the host (to cache), off the evaluation + path. The host loads Roslyn the first time it fills. Measured on macOS (40 scripts, restart to every first result): 820 ms with no cache, 840 ms with an empty one, **85 ms warm**; on windev (Windows) 9.5 s / 9.4 s / **1.0 s**. An unusable directory is a Warning and a cache-less runner. - **Orphan sweep.** Every launched worker gets a marker (`/workers/.worker`, or a per-install directory under temp) naming its pid, start time and image, and the host's pid and start time. At startup the runner diff --git a/docs/security.md b/docs/security.md index 8ae3b33d7..fac7da911 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1826,7 +1826,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). + --- @@ -1966,9 +2035,11 @@ deploy is rejected if any in-use stored script uses an API now refused; see `doc Residual exposure, by design: a script can still burn CPU and memory up to its budget (`ScriptRunGuard`; pre-emptive limits need `OutOfProcess`), read any tag through `ctx.GetTag`, and write virtual tags. Extending the allow-list is a security change — add only types with no I/O, process-wide state, background work, blocking wait or reflection -surface. The out-of-process runner's compiled-PE cache is still HMAC-signed by the **worker** with a key it is handed -in `Hello`; a worker that had escaped could forge entries for other scripts (follow-up from #971: move signing to the -host). +surface. The out-of-process runner's compiled-PE cache is owned by the **host** since lmxopcua#1014: the host verifies +entries under a key only it holds, ships verified images inside the load, and fills misses with its own compile; the +worker is never handed the key or the directory, so a worker that had escaped cannot forge an entry for another script. +Entries written by pre-#1014 workers are rejected on upgrade (format version 2). See `docs/VirtualTags.md` +§"Out-of-process runner" → Compiled-PE cache. --- 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/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/HostPeCache.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/HostPeCache.cs new file mode 100644 index 000000000..1c1d7592d --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/HostPeCache.cs @@ -0,0 +1,217 @@ +using System.Collections.Concurrent; +using Serilog; +using ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol; +using ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol.V1; +using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess; + +/// +/// The host's side of the compiled-PE cache (lmxopcua#780 design §7), which since lmxopcua#1014 is the ONLY side: +/// the host verifies entries under a key only it holds and ships a verified image to the worker inside the load, and +/// it fills the cache with its OWN compile — a worker never writes an entry and never sees the key. +/// +/// +/// +/// Why (review 2026-12-02 K-1, option 4). The worker used to read, verify and write the cache itself with +/// the key it received in Hello, and a verified image is loaded without re-running the analyzer. Code +/// that escaped inside a worker could therefore sign an entry for ANY script's source and have it loaded by every +/// later worker, across restarts and redeploys. A worker is the component that runs Designer-authored code, so it +/// must hold nothing that lets it persist. +/// +/// +/// Fill. After a worker reports a successful compile of a source the cache did not have, the host queues +/// its own compile of the same source on one background thread (below-normal priority, de-duplicated) and writes +/// the signed entry. Filling only after the worker's compile succeeded keeps a source that crashes Roslyn inside +/// the worker, where the isolation machinery contains it — the host never compiles a source first. A host compile +/// is the same pipeline the in-process runner and the deploy gate use (analyzer included); its image is never +/// loaded in the host. +/// +/// +/// Compatibility. The host compiles against its own runtime, so it ships images only to a worker whose +/// Ready.pe_image_abi equals ; any other worker (including a pre-#1014 +/// one, which reports none) compiles every script, as with no cache. +/// +/// +internal sealed class HostPeCache : IDisposable +{ + /// A fill backlog above this is dropped (best effort: a dropped fill costs a recompile at the next start). + internal const int MaxQueuedFills = 10_000; + + private readonly ScriptPeCacheStore _store; + private readonly ILogger _log; + private readonly ConcurrentDictionary _queued = new(StringComparer.Ordinal); + private readonly ConcurrentDictionary _abiWarned = new(StringComparer.Ordinal); + private readonly BlockingCollection _fills = new(new ConcurrentQueue()); + private readonly object _idleGate = new(); + private TaskCompletionSource _idle = NewCompleted(); + private int _outstanding; + private Thread? _thread; + private int _failureLogged; + private volatile bool _disposed; + + /// Creates the host cache over . + /// The store, opened with the node's key. + /// Host diagnostics. + public HostPeCache(ScriptPeCacheStore store, ILogger log) + { + _store = store ?? throw new ArgumentNullException(nameof(store)); + _log = log ?? throw new ArgumentNullException(nameof(log)); + } + + /// The cache directory. + public string Directory => _store.Directory; + + /// Whether a worker reporting may be sent this host's images. + /// The worker's Ready.pe_image_abi. + /// True when it equals . + public bool IsCompatible(string? workerImageAbi) + => string.Equals(workerImageAbi, ScriptSandbox.ImageAbi, StringComparison.Ordinal); + + /// Logs, once per distinct value, that a worker is not served images because its ABI differs. + /// The worker's shard. + /// What it reported. + public void NoteIncompatible(string shard, string? workerImageAbi) + { + if (!_abiWarned.TryAdd(workerImageAbi ?? string.Empty, 0)) return; + _log.Warning( + "ScriptWorker {Shard} reports image ABI {WorkerAbi}, not the host's {HostAbi}: the PE cache is not used for it and it compiles every script", + shard, string.IsNullOrEmpty(workerImageAbi) ? "(none — a pre-#1014 worker)" : workerImageAbi, ScriptSandbox.ImageAbi); + } + + /// Reads and verifies the entry for one source. A rejected entry has been deleted. + /// The context kind. + /// The source. + /// The verified image on a hit. + /// Hit, miss or rejected. + public PeCacheLookup Lookup(ContextKind kind, string source, out byte[]? image) + { + image = null; + try + { + return _store.TryRead(EntryId(kind, source), out image); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Best effort: an unreadable entry is a miss (the fill will try to replace it). + return PeCacheLookup.Miss; + } + } + + /// Deletes the entry for one source (its image did not load in a worker). + /// The context kind. + /// The source. + public void Evict(ContextKind kind, string source) + { + try { File.Delete(_store.EntryPath(EntryId(kind, source))); } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { } + } + + /// + /// Queues the host's own compile of into the cache. Call only after a worker compiled + /// it successfully. Duplicates of a queued fill are ignored; past the fill is dropped. + /// + /// The context kind. + /// The source. + public void QueueFill(ContextKind kind, string source) + { + if (_disposed || kind is not (ContextKind.VirtualTag or ContextKind.Calculation or ContextKind.AlarmPredicate)) return; + var id = EntryId(kind, source); + if (_queued.Count >= MaxQueuedFills || !_queued.TryAdd(id, 0)) return; + lock (_idleGate) + { + if (_outstanding++ == 0) _idle = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + if (_thread is null) + { + _thread = new Thread(FillLoop) { IsBackground = true, Name = "ScriptPeCache.Fill", Priority = ThreadPriority.BelowNormal }; + _thread.Start(); + } + } + bool added; + try { added = _fills.TryAdd(new Fill(id, kind, source)); } + catch (InvalidOperationException) { added = false; } // disposed meanwhile + if (!added) Done(id); + } + + /// Completes when no fill is queued or running (tests; a fill is best effort and never awaited in production). + /// The idle task. + public Task WhenIdleAsync() + { + lock (_idleGate) return _idle.Task; + } + + /// + public void Dispose() + { + if (_disposed) return; + _disposed = true; + try { _fills.CompleteAdding(); } catch (ObjectDisposedException) { } + } + + private void FillLoop() + { + foreach (var fill in _fills.GetConsumingEnumerable()) + { + try + { + if (!_disposed) RunFill(fill); + } + finally + { + Done(fill.Id); + } + } + } + + private void RunFill(Fill fill) + { + // Another shard's load of the same source may have filled it already; a present entry that does not verify is + // deleted by the read and refilled here. + if (_store.TryRead(fill.Id, out _) == PeCacheLookup.Hit) return; + try + { + var image = fill.Kind == ContextKind.AlarmPredicate + ? ScriptEvaluator.CompileToImage(fill.Source) + : ScriptEvaluator.CompileToImage(fill.Source); + if (!_store.TryWrite(fill.Id, image) && Interlocked.Exchange(ref _failureLogged, 1) == 0) + _log.Warning("Script PE cache {Directory}: an entry could not be written; ScriptWorkers will recompile those scripts on each start", + _store.Directory); + } + catch (Exception ex) + { + // The worker compiled this source, so a host compile that fails is an environment difference (or a defect): + // never fatal — the worker keeps compiling it, as with no cache. + if (Interlocked.Exchange(ref _failureLogged, 1) == 0) + _log.Warning(ex, "Script PE cache {Directory}: the host could not compile a script a worker compiled; it will not be cached", + _store.Directory); + } + } + + private void Done(string id) + { + _queued.TryRemove(id, out _); + lock (_idleGate) + { + if (--_outstanding == 0) _idle.TrySetResult(); + } + } + + /// The entry id for one source: the HOST's compile fingerprint for the kind's context, the kind, the source. + internal static string EntryId(ContextKind kind, string source) + { + var fingerprint = kind == ContextKind.AlarmPredicate + ? ScriptEvaluator.CacheFingerprint + : ScriptEvaluator.CacheFingerprint; + return ScriptPeCacheStore.EntryId(fingerprint, (int)kind, source); + } + + private static TaskCompletionSource NewCompleted() + { + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + tcs.TrySetResult(); + return tcs; + } + + private sealed record Fill(string Id, ContextKind Kind, string Source); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs index cc465b4be..298c9c1cf 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/OutOfProcessScriptRunner.cs @@ -64,7 +64,9 @@ public sealed record ScriptRunnerStatus( /// the result is — never an in-process run — carrying a /// task the seam re-evaluates on. /// PE cache (design §7): with set, workers load -/// HMAC-verified compiled images instead of re-entering Roslyn after a restart. +/// compiled images instead of re-entering Roslyn after a restart. The host owns it end to end +/// (, lmxopcua#1014): it verifies entries under a key only it holds, ships the image +/// inside the load, and fills misses with its own compile; a worker never holds the key. /// /// public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisposable, IDisposable @@ -138,8 +140,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp private readonly ConcurrentDictionary _compileFailures = new(StringComparer.Ordinal); private readonly Timer _maintenance; private readonly string _markerDirectory; - private readonly string? _peCacheDirectory; - private readonly byte[]? _peCacheKey; + private readonly HostPeCache? _peCache; private readonly int _compileThreads; /// Test seam: the launched workers' initial silence limit (null = three heartbeat intervals). @@ -187,15 +188,16 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp { try { - _peCacheKey = ScriptPeCacheStore.LoadOrCreateKey(_worker.PeCacheDir); - _peCacheDirectory = _worker.PeCacheDir; - var pruned = new ScriptPeCacheStore(_peCacheDirectory, _peCacheKey).Prune(PeCacheMaxAge, PeCacheMaxEntries); - if (pruned > 0) _log.Information("Script PE cache {Directory}: pruned {Count} stale entr(ies)", _peCacheDirectory, pruned); + // lmxopcua#1014: the key stays in this process. Workers are sent verified images, never the key or the + // directory, and the host fills the cache with its own compile. + var store = new ScriptPeCacheStore(_worker.PeCacheDir, ScriptPeCacheStore.LoadOrCreateKey(_worker.PeCacheDir)); + var pruned = store.Prune(PeCacheMaxAge, PeCacheMaxEntries); + if (pruned > 0) _log.Information("Script PE cache {Directory}: pruned {Count} stale entr(ies)", store.Directory, pruned); + _peCache = new HostPeCache(store, _log); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { - _peCacheKey = null; - _peCacheDirectory = null; + _peCache = null; _log.Warning(ex, "Script PE cache {Directory} is unusable; ScriptWorkers will recompile every script on each start", _worker.PeCacheDir); } @@ -239,7 +241,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp AllShards.Select(s => s.Status()).ToArray(), SuspectKeys.Count, _keys.Count(kv => kv.Value.QuarantineReason is not null), - _peCacheDirectory is not null); + _peCache is not null); /// /// How long a compile in the worker may run before the worker is killed, counted from the moment a compile thread @@ -256,6 +258,12 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp /// The marker directory this runner writes launch markers to and sweeps at startup. internal string MarkerDirectory => _markerDirectory; + /// + /// Completes when the host has no PE-cache fill queued or running (tests: the fill is background work, lmxopcua#1014). + /// + /// The idle task (completed at once without a cache). + internal Task PeCacheIdleAsync() => _peCache?.WhenIdleAsync() ?? Task.CompletedTask; + /// PE cache outcomes reported by this runner's workers (tests / diagnostics). internal (long Hits, long Misses, long Rejected) PeCacheCounts => (Interlocked.Read(ref _peCacheHits), Interlocked.Read(ref _peCacheMisses), Interlocked.Read(ref _peCacheRejected)); @@ -702,6 +710,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp LiveRunners.TryRemove(this, out _); await _maintenance.DisposeAsync().ConfigureAwait(false); await Task.WhenAll(AllShards.Select(s => s.DisposeAsync().AsTask())).ConfigureAwait(false); + _peCache?.Dispose(); } /// Stops every worker (blocking). @@ -750,8 +759,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp HardGrace: _worker.HardGrace ?? TimeSpan.FromSeconds(Math.Max(1, _options.RunTimeout.TotalSeconds)), HeartbeatInterval: heartbeatInterval, HandshakeTimeout: TimeSpan.FromSeconds(15), - PeCacheDirectory: _peCacheDirectory, - PeCacheKey: _peCacheKey, + PeCache: _peCache, MarkerDirectory: _markerDirectory, LoadTimeout: LoadTimeout, CompileThreads: _compileThreads, diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs index 7bfc7eadc..fa0eec507 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/WorkerConnection.cs @@ -75,8 +75,11 @@ internal sealed record BatchSubmission(string Key, EvalRequest Request, TimeSpan /// The worker watchdog's grace past the soft deadline. /// How often the worker sends a heartbeat. /// How long a launch may take to reach Ready. -/// The compiled-PE cache directory handed to the worker; null = no cache. -/// The cache's HMAC key (with ). +/// +/// The host's compiled-PE cache (lmxopcua#1014): images it verified are shipped inside the loads of a worker whose +/// image ABI matches, and it is filled by the host's own compile. Null = no cache. The worker is never given the key +/// or the directory. +/// /// Where the launch marker for the orphan sweep is written; null = none. /// /// How long one compile may run, counted from the worker's LoadStarted for it (not from when the host sent @@ -107,8 +110,7 @@ internal sealed record WorkerLaunchSpec( TimeSpan HardGrace, TimeSpan HeartbeatInterval, TimeSpan HandshakeTimeout, - string? PeCacheDirectory = null, - byte[]? PeCacheKey = null, + HostPeCache? PeCache = null, string? MarkerDirectory = null, TimeSpan? LoadTimeout = null, int CompileThreads = 0, @@ -162,6 +164,9 @@ internal sealed class WorkerConnection : IAsyncDisposable private readonly CancellationTokenSource _stopping = new(); private readonly TimeSpan _heartbeatInterval; private TimeSpan _loadTimeout; + + /// The host's PE cache for THIS worker (null: none configured, or the worker's image ABI differs). + private readonly HostPeCache? _peCache; private readonly Action _onExiting; private readonly string? _markerPath; private TaskCompletionSource? _diag; @@ -182,9 +187,11 @@ internal sealed class WorkerConnection : IAsyncDisposable private WorkerConnection(string shard, Process process, Stream pipe, IDisposable? job, IDisposable? stdio, string workDir, ILogger log, Action onLogs, TimeSpan heartbeatInterval, TimeSpan loadTimeout, - Action onExiting, string? markerPath, bool workerSoftClock, TimeSpan? heartbeatSilenceLimit) + Action onExiting, string? markerPath, bool workerSoftClock, TimeSpan? heartbeatSilenceLimit, + HostPeCache? peCache = null) { WorkerSoftClock = workerSoftClock; + _peCache = peCache; _stdio = stdio; _loadTimeout = loadTimeout; _onExiting = onExiting; @@ -388,30 +395,22 @@ internal sealed class WorkerConnection : IAsyncDisposable $"the worker exited (code {SafeExitCode(process)}) before connecting to its pipe"); await accept.ConfigureAwait(false); - var hello = new Hello - { - Nonce = nonce, - MaxFrameBytes = ScriptWorkerFrameCodec.DefaultMaxFrameBytes, - EvalThreads = (uint)spec.EvalThreads, - QueueCapacity = 4096, - HardGraceMs = (uint)Math.Clamp(spec.HardGrace.TotalMilliseconds, 1, uint.MaxValue), - HeartbeatIntervalMs = (uint)spec.HeartbeatInterval.TotalMilliseconds, - MaxLogLines = 1000, - CompileThreads = (uint)Math.Max(0, spec.CompileThreads), - WorkerSoftClock = spec.WorkerSoftClock, - TestStallReaderOnDiag = spec.TestStallReaderOnDiag, - }; - if (spec.PeCacheDirectory is { } cacheDir && spec.PeCacheKey is { } cacheKey) - { - hello.PeCacheDir = cacheDir; - hello.PeCacheKey = Google.Protobuf.ByteString.CopyFrom(cacheKey); - } + var hello = BuildHello(spec, nonce); io = ScriptWorkerFrameCodec.BlockingStream(pipe); var ready = await HandshakeBlockingAsync(io, hello, nonce, process.Id, handshakeCts.Token).ConfigureAwait(false); + // lmxopcua#1014: images are compiled by the host against its runtime, so only a worker that binds them the same + // way is sent any. Anything else (a pre-#1014 worker reports nothing) compiles every script. + var peCache = spec.PeCache; + if (peCache is not null && !peCache.IsCompatible(ready.PeImageAbi)) + { + peCache.NoteIncompatible(spec.Shard, ready.PeImageAbi); + peCache = null; + } + var connection = new WorkerConnection(spec.Shard, process, io, job, stdio, workDir, log, onLogs, spec.HeartbeatInterval, spec.EffectiveLoadTimeout, onExiting, markerPath, workerSoftClock: spec.WorkerSoftClock && ready.WorkerSoftClock, - heartbeatSilenceLimit: spec.HeartbeatSilenceLimit); + heartbeatSilenceLimit: spec.HeartbeatSilenceLimit, peCache: peCache); connection.Begin(); return connection; } @@ -429,6 +428,28 @@ internal sealed class WorkerConnection : IAsyncDisposable } } + /// + /// The worker's first frame. It carries nothing about the compiled-PE cache (lmxopcua#1014): the worker used to be + /// handed the cache directory and its HMAC key here, which let code escaped inside a worker sign entries for any + /// script; the host now verifies, compiles and signs alone and ships verified images inside the loads. + /// + /// The launch spec. + /// The launch nonce the worker must echo. + /// The Hello. + internal static Hello BuildHello(WorkerLaunchSpec spec, string nonce) => new() + { + Nonce = nonce, + MaxFrameBytes = ScriptWorkerFrameCodec.DefaultMaxFrameBytes, + EvalThreads = (uint)spec.EvalThreads, + QueueCapacity = 4096, + HardGraceMs = (uint)Math.Clamp(spec.HardGrace.TotalMilliseconds, 1, uint.MaxValue), + HeartbeatIntervalMs = (uint)spec.HeartbeatInterval.TotalMilliseconds, + MaxLogLines = 1000, + CompileThreads = (uint)Math.Max(0, spec.CompileThreads), + WorkerSoftClock = spec.WorkerSoftClock, + TestStallReaderOnDiag = spec.TestStallReaderOnDiag, + }; + /// /// The host half of the handshake: send , require a Ready as the first frame, /// echoing (constant-time compare) from . @@ -613,13 +634,62 @@ internal sealed class WorkerConnection : IAsyncDisposable var load = new LoadScripts { LoadId = loadId }; var script = new ScriptSource { Key = key, Kind = kind, Source = source, SourceSha256 = Google.Protobuf.ByteString.CopyFrom(sourceHash) }; script.InputPaths.AddRange(inputPaths); + var cacheLookup = AttachCachedImage(script); load.Scripts.Add(script); - var inFlight = new LoadInFlight(loadId, key, entry, this); + var inFlight = new LoadInFlight(loadId, key, entry, this) + { + CacheLookup = cacheLookup, + ImageAttached = !script.PeImage.IsEmpty, + Kind = kind, + Source = cacheLookup is null ? null : source, // held only while the cache needs it to settle + }; _loads[loadId] = inFlight; if (!Send(new Envelope { Load = load }) && _loads.TryRemove(loadId, out _)) inFlight.Finish(null); return entry.Ready; } + /// + /// lmxopcua#1014: looks the source up in the host's PE cache and, on a verified hit, puts the image in the load so + /// the worker does not enter Roslyn. An image that would not fit one frame is left out (the worker compiles). + /// + /// The host-side lookup, or null when this worker gets no cache. + private PeCacheLookup? AttachCachedImage(ScriptSource script) + { + if (_peCache is not { } cache) return null; + var lookup = cache.Lookup(script.Kind, script.Source, out var image); + if (lookup != PeCacheLookup.Hit || image is null) return lookup; + script.PeImage = Google.Protobuf.ByteString.CopyFrom(image); + if (_writer.FitsOneFrame(script)) return lookup; + script.PeImage = Google.Protobuf.ByteString.Empty; + return null; // a cache that can never serve this script: neither a hit nor a miss to fill + } + + /// + /// Turns the worker's report of a successful load into the cache outcome the runner records, and keeps the cache + /// (lmxopcua#1014): an image that did not load is evicted and refilled; a host-side miss or verification failure + /// queues the host's own compile — only now, after the worker's compile succeeded, so a source that crashes Roslyn + /// never reaches the host's compiler first. + /// + private void SettleCache(LoadInFlight load, LoadOutcome outcome, ContextKind kind, string source) + { + if (_peCache is not { } cache || load.CacheLookup is not { } lookup) + { + outcome.Cache = PeCache.None; + return; + } + if (!outcome.Ok) return; + if (load.ImageAttached) + { + if (outcome.Cache == PeCache.Hit) return; + cache.Evict(kind, source); + cache.QueueFill(kind, source); + outcome.Cache = PeCache.Rejected; + return; + } + cache.QueueFill(kind, source); + outcome.Cache = lookup == PeCacheLookup.Rejected ? PeCache.Rejected : PeCache.Miss; + } + /// Forgets a key's compiled form here and in the worker. /// The scoped keys. public void Unload(IReadOnlyCollection keys) @@ -1107,6 +1177,18 @@ internal sealed class WorkerConnection : IAsyncDisposable public LoadEntry Entry { get; } = entry; + /// lmxopcua#1014: the host's PE-cache lookup for this load; null = no cache for it. + public PeCacheLookup? CacheLookup { get; init; } + + /// Whether the load carried a verified image from the cache. + public bool ImageAttached { get; init; } + + /// The script's kind. + public ContextKind Kind { get; init; } + + /// The source, while the cache needs it (null without a cache). + public string? Source { get; init; } + /// The worker has started compiling it: arm the compile timeout (once). public void Started(TimeSpan timeout) { @@ -1133,6 +1215,7 @@ internal sealed class WorkerConnection : IAsyncDisposable var outcome = result.Outcomes.FirstOrDefault(o => o.Key == Key) ?? new LoadOutcome { Key = Key, Ok = false, Error = new ScriptError { Kind = ScriptError.Types.Kind.Threw, Message = "no load outcome" } }; if (!outcome.Ok) Owner._loaded.TryRemove(new KeyValuePair(Key, Entry)); + Owner.SettleCache(this, outcome, Kind, Source ?? string.Empty); Entry.Complete(outcome); } } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto index 086de3ae7..c8463bb4d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/Protos/script_worker.proto @@ -38,8 +38,13 @@ message Hello { uint32 hard_grace_ms = 5; // worker watchdog: fail fast past soft + grace (+ margin) uint32 heartbeat_interval_ms = 6; uint32 max_log_lines = 7; // outbound log buffer cap - string pe_cache_dir = 8; // the node's compiled-PE cache (design §7); empty = no cache - bytes pe_cache_key = 9; // its HMAC key; the worker loads only entries that verify under it + // 8 and 9 were pe_cache_dir / pe_cache_key: the worker used to read, verify and WRITE the compiled-PE cache itself, + // holding the node's HMAC key — so code that escaped inside a worker could sign an entry for any script and persist + // across restarts (lmxopcua#1014, review K-1 option 4). The host now owns the cache end to end: it verifies an entry and + // ships the image in ScriptSource.pe_image, and it compiles and signs new entries itself. The worker holds no key and + // never touches the directory. Never reuse these numbers: a pre-#1014 worker would read a key out of them. + reserved 8, 9; + reserved "pe_cache_dir", "pe_cache_key"; uint32 compile_threads = 10; // dedicated compile threads; 0 = the worker's default (min(8, max(1, CPUs/2))) // lmxopcua#827: the host asks the worker to run each evaluation's SOFT clock itself, from when an evaluation thread // starts the run, and to report the crossing in EvalResults.soft_expired_eval_ids. The host then keeps only a @@ -55,6 +60,10 @@ message Ready { int32 pid = 2; string runtime_version = 3; bool worker_soft_clock = 4; // lmxopcua#827: this worker runs the soft clock (Hello.worker_soft_clock was set) + // lmxopcua#1014: the identity of what a compiled script image binds to in this worker (runtime version and the pinned + // assemblies' names; ScriptSandbox.ImageAbi). The host ships images from its PE cache only to a worker whose value + // equals its own, since the host compiled them against ITS runtime. Empty (a pre-#1014 worker) = never served images. + string pe_image_abi = 5; } enum ContextKind { @@ -70,6 +79,10 @@ message ScriptSource { ContextKind kind = 3; string source = 4; repeated string input_paths = 5; // slot order for EvalRequest.inputs + // lmxopcua#1014: a compiled image of `source`, from the host's PE cache — verified by the host under a key only the + // host holds, and emitted by the host's own compile pipeline (analyzer included). The worker loads it instead of + // entering Roslyn; if it does not load, the worker compiles `source` and reports PE_CACHE_REJECTED. Empty = compile. + bytes pe_image = 6; } message LoadScripts { @@ -84,11 +97,14 @@ message LoadOutcome { PeCache cache = 4; // how the PE cache served this load } +// Since lmxopcua#1014 the worker reports only what it did with ScriptSource.pe_image (NONE: there was none, compiled; +// HIT: loaded it; REJECTED: it did not load, compiled). The host owns the cache and turns that into the outcome it +// records (a host-side miss or verification failure, a fill it queued). enum PeCache { - PE_CACHE_NONE = 0; // no cache configured (or the load failed before it was consulted) - PE_CACHE_HIT = 1; // loaded from a verified entry; Roslyn not entered - PE_CACHE_MISS = 2; // compiled; the entry was written - PE_CACHE_REJECTED = 3; // an entry failed verification, was deleted, and the source was compiled + PE_CACHE_NONE = 0; // no image was supplied: compiled from source + PE_CACHE_HIT = 1; // loaded from the supplied (host-verified) image; Roslyn not entered + PE_CACHE_MISS = 2; // host side only: no entry; compiled, and the host queued its own compile to fill it + PE_CACHE_REJECTED = 3; // an entry failed verification (host) or its image failed to load (worker); recompiled } // A compile thread has taken the load off the worker's queue and is about to compile (or PE-load) it. The host's load diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptPeCacheStore.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptPeCacheStore.cs index edb0de1c4..35acde382 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptPeCacheStore.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol/ScriptPeCacheStore.cs @@ -22,7 +22,9 @@ public enum PeCacheLookup /// /// The node-local compiled-PE cache (lmxopcua#780 design §7, owner decision §14 #8): content-addressed files under /// Scripting:Worker:PeCacheDir, each authenticated with HMAC-SHA256 under a per-node random key, so a worker -/// restart loads its scripts' PE images instead of re-entering Roslyn — and never loads bytes it did not write. +/// restart loads its scripts' PE images instead of re-entering Roslyn — and never loads bytes the host did not write. +/// Host-only since lmxopcua#1014: the host reads, verifies, compiles and writes entries (HostPeCache) and +/// ships a verified image to the worker inside the load; the worker holds no key and never opens the directory. /// /// /// @@ -37,7 +39,7 @@ public enum PeCacheLookup /// outside the analyzer; a rejected entry is deleted and the source recompiled. /// Key. Readable only by the host account: on Linux/macOS the directory is 0700 and the key file /// 0600. On Windows the file inherits the directory's ACL, which must be the installer's (lmxopcua#780 installer -/// work). The worker receives the key in Hello, never on disk or in its environment. +/// work). The worker never receives it (lmxopcua#1014 — it used to arrive in Hello). /// Writes go to a unique temp file and are renamed into place, so a concurrent reader (another /// shard) sees the old entry, the new one, or none — never a torn file. /// @@ -57,7 +59,9 @@ public sealed class ScriptPeCacheStore public const int MaxEntryBytes = 32 * 1024 * 1024; private const string EntryExtension = ".pe"; - private static readonly byte[] Magic = "OTPEC\u0001\0\0"u8.ToArray(); + // Version 2 since lmxopcua#1014: version-1 entries were written by workers holding the key, so any of them may have + // been forged by code that escaped inside a worker. A version-1 file fails the magic check and is evicted. + private static readonly byte[] Magic = "OTPEC\u0002\0\0"u8.ToArray(); private const int TagLength = 32; private readonly byte[] _key; diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs index 3b2900d80..c623d879d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptSandbox.cs @@ -97,7 +97,32 @@ public static class ScriptSandbox /// /// The concrete script context type. /// One line per reference, in a stable order. - public static IEnumerable ReferenceIdentities(Type contextType) + public static IEnumerable ReferenceIdentities(Type contextType) => ReferenceIdentitiesCore(contextType); + + /// + /// What a compiled script image binds to when it is LOADED (lmxopcua#1014): the runtime version and the full names + /// (name, version, culture, key) of the assemblies the wrapper and the ctx API live in. The host compiles the + /// out-of-process runner's PE-cache entries against its own runtime and ships them to a worker only when the + /// worker reports the same value — unlike it + /// carries no file paths or module ids, which legitimately differ between the host and a self-contained worker + /// published beside it. + /// + public static string ImageAbi { get; } = BuildImageAbi(); + + private static string BuildImageAbi() + { + var names = new[] + { + typeof(DataValueSnapshot).Assembly, typeof(ScriptContext).Assembly, typeof(ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext).Assembly, + typeof(ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms.AlarmPredicateContext).Assembly, typeof(ScriptSandbox).Assembly, typeof(Serilog.ILogger).Assembly, + } + .Distinct() + .Select(static a => a.FullName ?? a.GetName().Name ?? "?") + .Order(StringComparer.Ordinal); + return "otopcua-script-image-abi/1|" + Environment.Version + "|" + string.Join("|", names); + } + + private static IEnumerable ReferenceIdentitiesCore(Type contextType) { ArgumentNullException.ThrowIfNull(contextType); var pinned = new[] { typeof(DataValueSnapshot).Assembly, typeof(ScriptContext).Assembly, typeof(Serilog.ILogger).Assembly, contextType.Assembly } 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/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs index d5a429483..26ef5492b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker/WorkerHost.cs @@ -78,7 +78,6 @@ internal sealed class WorkerHost private int _queueCapacity = 4096; private TimeSpan _hardGrace = TimeSpan.FromSeconds(1); private TimeSpan _heartbeatInterval = TimeSpan.FromSeconds(1); - private ScriptPeCacheStore? _peCache; /// /// lmxopcua#827: this worker runs each evaluation's soft clock from the run's start and reports the crossing @@ -129,6 +128,8 @@ internal sealed class WorkerHost Pid = Environment.ProcessId, RuntimeVersion = Environment.Version.ToString(), WorkerSoftClock = _workerSoftClock, + // lmxopcua#1014: lets the host decide whether its compiled images bind here. + PeImageAbi = ScriptSandbox.ImageAbi, }, }); ScriptWorkerFrameCodec.Write(_pipe, ready, _maxFrameBytes); @@ -161,11 +162,9 @@ internal sealed class WorkerHost if (hello.CompileThreads > 0) _compileThreads = (int)Math.Min(hello.CompileThreads, 64); _workerSoftClock = hello.WorkerSoftClock; _testStallReaderOnDiag = hello.TestStallReaderOnDiag; - if (!string.IsNullOrEmpty(hello.PeCacheDir) && hello.PeCacheKey.Length == ScriptPeCacheStore.KeyLength) - { - // Design §7: the host owns the key; it reaches us only here, never through the environment or a file. - _peCache = new ScriptPeCacheStore(hello.PeCacheDir, hello.PeCacheKey.ToByteArray()); - } + // lmxopcua#1014: no PE-cache key or directory any more — the host verifies, compiles and signs, and sends a + // verified image inside the load (ScriptSource.pe_image). This process runs Designer code; it holds nothing that + // would let that code persist. } private void StartBackground(int evalThreads) @@ -306,7 +305,7 @@ internal sealed class WorkerHost var outcome = new LoadOutcome { Key = script.Key, Ok = true }; try { - var loaded = LoadedScript.Load(script, _peCache, out var cache); + var loaded = LoadedScript.Load(script, out var cache); outcome.Cache = cache; if (_scripts.TryRemove(script.Key, out var previous)) previous.Dispose(); _scripts[script.Key] = loaded; @@ -723,49 +722,44 @@ internal sealed class WorkerHost public string[] InputPaths { get; } /// - /// Loads a script: from a verified PE cache entry when there is one (Roslyn is not entered), otherwise by - /// compiling it and writing the entry (design §7). A compile error is never cached — the host's negative - /// cache covers that — and an entry that fails verification is deleted by the store and recompiled. + /// Loads a script: from the image the host sent with it when there is one (Roslyn is not entered), otherwise by + /// compiling the source. The image comes from the host's PE cache (lmxopcua#1014): the host verified it under a + /// key this process never holds and emitted it with its own compile pipeline, analyzer included, so it is + /// loaded as the host's own compile would be. One that does not load is reported () + /// and the source compiled; the host evicts the entry. /// - public static LoadedScript Load(ScriptSource source, ScriptPeCacheStore? cache, out PeCache how) => source.Kind switch + public static LoadedScript Load(ScriptSource source, out PeCache how) => source.Kind switch { ContextKind.VirtualTag or ContextKind.Calculation => new LoadedScript( - [.. source.InputPaths], Load(source, cache, out how), null), + [.. source.InputPaths], Load(source, out how), null), ContextKind.AlarmPredicate => new LoadedScript( - [.. source.InputPaths], null, Load(source, cache, out how)), + [.. source.InputPaths], null, Load(source, out how)), _ => throw new ScriptWorkerProtocolException($"unknown script kind {source.Kind}"), }; - private static ScriptEvaluator Load(ScriptSource source, ScriptPeCacheStore? cache, - out PeCache how) where TContext : ScriptContext + private static ScriptEvaluator Load(ScriptSource source, out PeCache how) + where TContext : ScriptContext { - if (cache is null) - { - how = PeCache.None; - return ScriptEvaluator.Compile(source.Source); - } - - var id = ScriptPeCacheStore.EntryId(ScriptEvaluator.CacheFingerprint, (int)source.Kind, source.Source); - var lookup = cache.TryRead(id, out var image); - if (lookup == PeCacheLookup.Hit) + if (!source.PeImage.IsEmpty) { try { + var evaluator = ScriptEvaluator.FromImage(source.PeImage.ToByteArray()); how = PeCache.Hit; - return ScriptEvaluator.FromImage(image!); + return evaluator; } - catch (Exception ex) when (ex is BadImageFormatException or InvalidOperationException or TypeLoadException or MissingMethodException) + catch (Exception ex) when (ex is BadImageFormatException or InvalidOperationException or TypeLoadException + or MissingMethodException or FileLoadException or FileNotFoundException + or InvalidCastException or ArgumentException) { - // Authenticated but unloadable: only possible across a runtime change the fingerprint missed. - try { File.Delete(cache.EntryPath(id)); } catch (IOException) { } - lookup = PeCacheLookup.Rejected; + // Verified by the host but unloadable here: a runtime difference the image ABI did not capture. + how = PeCache.Rejected; + return ScriptEvaluator.Compile(source.Source); } } - var compiled = ScriptEvaluator.CompileToImage(source.Source); - cache.TryWrite(id, compiled); - how = lookup == PeCacheLookup.Rejected ? PeCache.Rejected : PeCache.Miss; - return ScriptEvaluator.FromImage(compiled); + how = PeCache.None; + return ScriptEvaluator.Compile(source.Source); } public object? Run(IReadOnlyDictionary inputs, ILogger logger, Func clock, 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; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/PeCacheTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/PeCacheTests.cs index 637ceef3f..4b1bb68f6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/PeCacheTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests/PeCacheTests.cs @@ -1,8 +1,10 @@ using System.Diagnostics; +using Google.Protobuf; using System.Security.Cryptography; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Core.Scripting; +using ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess; using ZB.MOM.WW.OtOpcUa.Core.Scripting.Protocol; using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; @@ -11,7 +13,8 @@ namespace ZB.MOM.WW.OtOpcUa.ScriptWorker.Tests; /// /// lmxopcua#780 design §7 (owner decision §14 #8): the node-local HMAC'd compiled-PE cache. The store is tested /// directly (authentication, eviction, keying); the worker-backed cases prove a restart loads from it instead of -/// recompiling, and that the worker never runs bytes that did not verify. +/// recompiling, and that the worker never runs bytes that did not verify. Since lmxopcua#1014 the HOST owns the cache +/// end to end (verifies, compiles, signs); the worker holds no key. /// public sealed class PeCacheStoreTests { @@ -77,6 +80,32 @@ public sealed class PeCacheStoreTests File.Exists(path).ShouldBeFalse("a rejected entry is evicted"); } + /// + /// lmxopcua#1014: an entry in the pre-host-signing format (magic v1), even one tagged under the node's REAL key, is + /// rejected and evicted. Those entries were written by workers holding the key, so any of them may have been forged + /// by code that escaped inside a worker; an upgrade must not keep serving them. Positive control: the same bytes + /// under the current magic verify (the round trip above). + /// + [Fact] + public void An_entry_written_in_the_worker_signed_format_is_rejected_even_under_the_real_key() + { + using var dir = new Scripts.TempDir(); + var key = ScriptPeCacheStore.LoadOrCreateKey(dir.Path); + var store = new ScriptPeCacheStore(dir.Path, key); + var id = ScriptPeCacheStore.EntryId(Fingerprint, 1, "return 1;"); + byte[] pe = [10, 20, 30, 40, 50]; + byte[] v1Magic = [(byte)'O', (byte)'T', (byte)'P', (byte)'E', (byte)'C', 1, 0, 0]; + using var hmac = IncrementalHash.CreateHMAC(HashAlgorithmName.SHA256, key); + hmac.AppendData(v1Magic); + hmac.AppendData(System.Text.Encoding.ASCII.GetBytes(id)); + hmac.AppendData(pe); + File.WriteAllBytes(store.EntryPath(id), [.. v1Magic, .. hmac.GetHashAndReset(), .. pe]); + + store.TryRead(id, out var image).ShouldBe(PeCacheLookup.Rejected); + image.ShouldBeNull(); + File.Exists(store.EntryPath(id)).ShouldBeFalse("a worker-signed entry is evicted"); + } + [Fact] public void The_entry_id_changes_with_the_compiler_fingerprint_the_kind_and_the_source() { @@ -159,7 +188,10 @@ public sealed class PeCacheWorkerTests outcome.Status.ShouldBe(ScriptRunStatus.Ok, outcome.Reason); outcome.Value.ShouldBe(Expected(i)); } - return (sw.Elapsed, runner.PeCacheCounts); + var elapsed = sw.Elapsed; + // lmxopcua#1014: the host fills the cache with its OWN compile after the worker's succeeded, in the background. + await runner.PeCacheIdleAsync().WaitAsync(TimeSpan.FromSeconds(60), Ct); + return (elapsed, runner.PeCacheCounts); } /// @@ -184,7 +216,7 @@ public sealed class PeCacheWorkerTests $"empty cache {cold.Elapsed.TotalMilliseconds:F0} ms; warm cache {warm.Elapsed.TotalMilliseconds:F0} ms"); uncached.Counts.ShouldBe((0L, 0L, 0L), "no cache configured"); - cold.Counts.ShouldBe((0L, (long)count, 0L), "the first start compiles and writes every entry"); + cold.Counts.ShouldBe((0L, (long)count, 0L), "the first start compiles and the host writes every entry"); warm.Counts.ShouldBe(((long)count, 0L, 0L), "the restart loads every script from the cache"); warm.Elapsed.ShouldBeLessThan(cold.Elapsed, "loading a PE is cheaper than entering Roslyn"); Directory.EnumerateFiles(Path.Combine(cacheDir, ScriptPeCacheStore.EntriesDirectoryName), "*.pe").Count().ShouldBe(count); @@ -201,7 +233,10 @@ public sealed class PeCacheWorkerTests using var dir = new Scripts.TempDir(); var cacheDir = Path.Combine(dir.Path, "pe-cache"); await using (var first = Scripts.Runner(Scripts.Options(peCacheDir: cacheDir))) + { (await first.RunAsync(Scripts.Vt("vt", "return 1;"), Ct)).Value.ShouldBe(1); + await first.PeCacheIdleAsync().WaitAsync(TimeSpan.FromSeconds(60), Ct); + } var entry = Directory.EnumerateFiles(Path.Combine(cacheDir, ScriptPeCacheStore.EntriesDirectoryName), "*.pe").ShouldHaveSingleItem(); var evil = ScriptEvaluator.CompileToImage("return 666;"); @@ -221,11 +256,79 @@ public sealed class PeCacheWorkerTests var outcome = await second.RunAsync(Scripts.Vt("vt", "return 1;"), Ct); outcome.Value.ShouldBe(1, "the forged bytes never ran"); second.PeCacheCounts.Rejected.ShouldBe(1); + await second.PeCacheIdleAsync().WaitAsync(TimeSpan.FromSeconds(60), Ct); var key = File.ReadAllBytes(Path.Combine(cacheDir, ScriptPeCacheStore.KeyFileName)); new ScriptPeCacheStore(cacheDir, key).TryRead(Path.GetFileNameWithoutExtension(entry), out _) .ShouldBe(PeCacheLookup.Hit, "the entry was rewritten from the real compile"); } + /// + /// lmxopcua#1014 (review K-1 option 4): the worker is never handed the cache's HMAC key. Before, Hello carried + /// it, so code that escaped inside a worker could sign an entry for any script's source and persist across restarts + /// and redeploys. Mutation check: putting the key back into the Hello fails this. + /// + [Fact] + public void The_hello_a_worker_receives_carries_neither_the_cache_key_nor_the_cache_directory() + { + using var dir = new Scripts.TempDir(); + var cacheDir = Path.Combine(dir.Path, "pe-cache"); + var key = ScriptPeCacheStore.LoadOrCreateKey(cacheDir); + using var cache = new HostPeCache(new ScriptPeCacheStore(cacheDir, key), new Serilog.LoggerConfiguration().CreateLogger()); + var spec = new WorkerLaunchSpec("0", "worker.dll", 1L << 28, 2, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), + TimeSpan.FromSeconds(15), PeCache: cache); + + var bytes = WorkerConnection.BuildHello(spec, "nonce").ToByteArray(); + + bytes.AsSpan().IndexOf(key).ShouldBe(-1, "the HMAC key never crosses the pipe"); + bytes.AsSpan().IndexOf(System.Text.Encoding.UTF8.GetBytes(cacheDir)).ShouldBe(-1, "the worker is not told where the cache is"); + } + + /// + /// A validly signed entry whose image does not load in the worker (here: not a PE at all) is not fatal: the worker + /// compiles the source and says so, the host evicts the entry and refills it with its own compile. Positive + /// control: the next start is a hit. + /// + [Fact] + public async Task A_signed_image_that_does_not_load_is_recompiled_evicted_and_refilled_by_the_host() + { + using var dir = new Scripts.TempDir(); + var cacheDir = Path.Combine(dir.Path, "pe-cache"); + var key = ScriptPeCacheStore.LoadOrCreateKey(cacheDir); + var store = new ScriptPeCacheStore(cacheDir, key); + var id = ScriptPeCacheStore.EntryId(ScriptEvaluator.CacheFingerprint, + (int)Core.Scripting.Protocol.V1.ContextKind.VirtualTag, "return 7;"); + store.TryWrite(id, [1, 2, 3, 4]).ShouldBeTrue(); + + await using (var runner = Scripts.Runner(Scripts.Options(peCacheDir: cacheDir))) + { + (await runner.RunAsync(Scripts.Vt("vt", "return 7;"), Ct)).Value.ShouldBe(7); + runner.PeCacheCounts.ShouldBe((0L, 0L, 1L)); + await runner.PeCacheIdleAsync().WaitAsync(TimeSpan.FromSeconds(60), Ct); + } + store.TryRead(id, out var image).ShouldBe(PeCacheLookup.Hit, "refilled by the host"); + image!.Length.ShouldBeGreaterThan(4); + + await using var again = Scripts.Runner(Scripts.Options(peCacheDir: cacheDir)); + (await again.RunAsync(Scripts.Vt("vt", "return 7;"), Ct)).Value.ShouldBe(7); + again.PeCacheCounts.ShouldBe((1L, 0L, 0L), "positive control: the refilled entry is served"); + } + + /// + /// The host compiled its entries against ITS runtime, so a worker reporting a different image ABI (a pre-#1014 + /// worker reports none) is never served images — it compiles, as with no cache. Positive control: the host's own + /// ABI is compatible. + /// + [Fact] + public void Images_are_served_only_to_a_worker_with_the_hosts_image_abi() + { + using var dir = new Scripts.TempDir(); + var key = ScriptPeCacheStore.LoadOrCreateKey(dir.Path); + using var cache = new HostPeCache(new ScriptPeCacheStore(dir.Path, key), new Serilog.LoggerConfiguration().CreateLogger()); + cache.IsCompatible(ScriptSandbox.ImageAbi).ShouldBeTrue("positive control"); + cache.IsCompatible("").ShouldBeFalse("a pre-#1014 worker reports nothing"); + cache.IsCompatible(ScriptSandbox.ImageAbi + "x").ShouldBeFalse(); + } + /// A compile error is never cached (the host's negative cache covers it) and does not poison the directory. [Fact] public async Task A_compile_error_writes_no_entry() @@ -234,6 +337,7 @@ public sealed class PeCacheWorkerTests var cacheDir = Path.Combine(dir.Path, "pe-cache"); await using var runner = Scripts.Runner(Scripts.Options(peCacheDir: cacheDir)); (await runner.RunAsync(Scripts.Vt("bad", "return nope;"), Ct)).Reason!.ShouldStartWith("compile error:"); + await runner.PeCacheIdleAsync().WaitAsync(TimeSpan.FromSeconds(60), Ct); Directory.EnumerateFiles(Path.Combine(cacheDir, ScriptPeCacheStore.EntriesDirectoryName), "*.pe").ShouldBeEmpty(); }