Merge security follow-ups: host-side PE-cache signing, worker no longer holds the HMAC key (#1014); Akka remoting untrusted-mode + trusted-selection-paths by default, opt-in mutual TLS (#1003)
This commit is contained in:
@@ -32,6 +32,15 @@ The server supports non-transparent warm/hot redundancy via the `Redundancy` sec
|
||||
|
||||
**Simultaneous cold-start splits — the bootstrap guard closes it (opt-in, `Cluster:BootstrapGuard:Enabled`, default OFF).** Self-first on BOTH nodes means when both cold-start at the same instant, each runs `FirstSeedNodeProcess`, times out, and forms its OWN 1-node cluster → two Primaries in one pair (the Phase 6 live gate reproduced this on docker; two separate clusters do NOT auto-merge). The guard prevents it without losing cold-start-alone: the lexicographically **lower** `host:port` node is the preferred founder (self-first, forms immediately); the **higher** node TCP-probes the partner's Akka port up to `PartnerProbeSeconds` (25s) — **reachable ⇒ peer-first (join the founder)**, **unreachable ⇒ self-first (partner dead, form alone)**. The order is chosen BEFORE the single `JoinSeedNodes`, from an explicit reachability signal — it never re-forms mid-handshake (the `SelfFormAfter` failure mode). When on, Akka gets NO config seeds (`BuildClusterOptions` empties `ClusterOptions.SeedNodes`) and `ClusterBootstrapCoordinator` drives the join. Residual trade (accepted, operator-visible via a warning + restart-recovers): the higher node hangs if the founder dies in the probe→join window. docker-dev: **site-a = guard demo** (guard on, serialization removed); **site-b = A/B control** (guard off, `depends_on: service_healthy` serialization). The guard is the production-faithful fix (compose `depends_on` doesn't exist on real VMs). Pinned by `ClusterBootstrapGuardTests` + `ClusterBootstrapCoordinatorTests` (real 2-node clusters, incl. the higher-node-cold-start-alone case). See `docs/Redundancy.md` §"Bootstrap guard".
|
||||
|
||||
**Akka remoting is hardened (lmxopcua#1003).** `Cluster:Remoting:UntrustedMode` is **on by default**: inbound
|
||||
`ActorSelection` reaches only `RemotingHardening.TrustedSelectionPaths` (cluster daemon + heartbeat receiver, remote-watcher,
|
||||
DPS mediator, `/user/{singleton}` + `/user/{singleton}/{singleton}` for each ControlPlane singleton, `/user/driver-host`).
|
||||
⚠️ **A new cluster singleton or a new cross-node `ActorSelection` must add its path** to `RemotingHardening` —
|
||||
`RemotingTrustedPathsCoverageTests` fails otherwise; a missed path is a Warning `untrusted-mode dropped …` + the
|
||||
`otopcua.cluster.remoting.untrusted_drops` counter, and the feature silently stops across nodes. Mutual TLS
|
||||
(`Cluster:Remoting:Tls`) is opt-in and all-or-nothing per link (scheme `akka.ssl.tcp`; seeds are rewritten) — flip both
|
||||
pair nodes together. See `docs/security.md` §"Akka remoting hardening".
|
||||
|
||||
Assert the **effective** cluster config off a running `ActorSystem` (as `SplitBrainResolverActivationTests` does), never the typed options or the akka.conf text — several HOCON fragments compete and the losing one still reads correctly in the file.
|
||||
|
||||
**RESOLVED by per-cluster mesh Phase 6 (2026-07-24) — no longer per-Akka-cluster.** The "one Primary across the whole Akka mesh" limitation described above is gone; see the Phase 6 paragraph immediately below.
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -173,6 +173,9 @@ Security__Ldap__GroupToRole__<AD group>=Viewer
|
||||
| `Port` | int | `4053` | Cluster transport port. **Duplicated as `ClusterNode.AkkaPort` in the Config DB** — see the note below. |
|
||||
| `PublicHostname` | string | `127.0.0.1` | Hostname advertised in cluster gossip; must be reachable by peers. **Duplicated as `ClusterNode.Host`** — see the note below. |
|
||||
| `SeedNodes` | string[] | `[]` | Seed nodes for bootstrapping. **Ordered:** a node that appears in its own list must be entry 0 (only `seed-nodes[0]` can form a new cluster), or the host refuses to start — see [Redundancy.md § Bootstrap: self-first seed ordering](Redundancy.md#bootstrap-self-first-seed-ordering). **Per-pair since Phase 6:** each application `Cluster`'s pair is its own Akka mesh, so a node's `SeedNodes` lists only itself (first) and its own pair partner (second) — never a node from another cluster's pair. |
|
||||
| `Remoting:UntrustedMode` | bool | `true` | Akka `untrusted-mode` with the trusted selection paths this code base uses (lmxopcua#1003). Receive-side only; a drop is a Warning naming the path. See [security.md § Akka remoting hardening](security.md#akka-remoting-hardening-clusterremoting-lmxopcua1003). |
|
||||
| `Remoting:AdditionalTrustedSelectionPaths` | string[] | `[]` | Extra `/user/…` / `/system/…` paths a peer may reach by selection. |
|
||||
| `Remoting:Tls:*` | object | `Enabled=false` | Opt-in mutual TLS on the remoting transport (`CertificatePath`+`CertificatePassword` or `CertificateThumbprint`+store, `RequireMutualAuthentication=true`, `AllowedThumbprints`, `ValidateCertificateHostname`). Both nodes of a pair change together. |
|
||||
| `Roles` | string[] | `[]` | Cluster roles for this node. When empty, falls back to `OTOPCUA_ROLES` (see the note below). Values are trimmed and (for a plain role) lower-cased; a cluster role's ClusterId suffix keeps the operator's spelling. An unknown role from either source **fails host start**. Allowed values: `admin`, `driver`, `dev`, plus a per-cluster `cluster-{ClusterId}` role (e.g. `cluster-MAIN`, `cluster-SITE-A`) — see [Per-cluster mesh split (Phase 6)](#per-cluster-mesh-split-phase-6-cluster-clusterid-roles--splittopologytransportvalidator) below. |
|
||||
|
||||
> **One role authority, one precedence, both consumers (archreview R3-04).** `EffectiveRoles.Resolve` (`ZB.MOM.WW.OtOpcUa.Cluster`) is the SINGLE place a node's roles are decided: `Cluster:Roles` wins outright when non-empty, else `OTOPCUA_ROLES`, else empty. Both `Program.cs`'s conditional host wiring (which subsystems mount) AND the Akka `AkkaClusterOptions.Roles` gossiped to the cluster are the SAME `EffectiveRoles` instance's `Gossiped` list — not two separate derivations that happen to usually agree. The boot banner (`OtOpcUa.Host starting with roles=[...] source=...`) names which source won. Setting both sources to *different* normalized role sets logs a Warning at boot (still resolves from `Cluster:Roles`) — almost certainly not what an operator intended.
|
||||
|
||||
@@ -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 `<InstallRoot>` (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 `<InstallRoot>` 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 `<InstallRoot>` (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 `<InstallRoot>`. 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. |
|
||||
|
||||
+27
-9
@@ -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 `<dir>/pe/<id>.pe`, authenticated with HMAC-SHA256 under a per-node
|
||||
random key (`<dir>/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 `<dir>/pe/<id>.pe`, authenticated with HMAC-SHA256 under a per-node random key
|
||||
(`<dir>/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 (`<PeCacheDir>/workers/<pid>.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
|
||||
|
||||
+75
-4
@@ -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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -103,6 +103,12 @@ public sealed class AkkaClusterOptions
|
||||
/// <c>ClusterBootstrapCoordinator</c> for the runtime.
|
||||
/// </summary>
|
||||
public ClusterBootstrapGuardOptions BootstrapGuard { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// Akka remoting hardening (<c>Cluster:Remoting</c>, lmxopcua#1003): untrusted-mode with the trusted selection
|
||||
/// paths (on by default) and transport TLS (opt-in). See <see cref="AkkaRemotingOptions"/>.
|
||||
/// </summary>
|
||||
public AkkaRemotingOptions Remoting { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -67,6 +67,7 @@ public sealed class AkkaClusterOptionsValidator : OptionsValidatorBase<AkkaClust
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
|
||||
ValidateBootstrapGuard(builder, options.BootstrapGuard);
|
||||
foreach (var problem in RemotingHardening.Validate(options.Remoting)) builder.Add(problem);
|
||||
ValidateAgainstEffectiveRoles(builder, options);
|
||||
|
||||
var seeds = options.SeedNodes ?? Array.Empty<string>();
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Cluster;
|
||||
|
||||
/// <summary>
|
||||
/// Hardening of the Akka remoting endpoint every node listens on (<c>Cluster:Remoting</c>, lmxopcua#1003, review
|
||||
/// 2026-12-02 A-1 follow-up). Two independent controls:
|
||||
/// <list type="bullet">
|
||||
/// <item><see cref="UntrustedMode"/> — <b>on by default</b>: inbound <c>ActorSelection</c> is delivered only to the
|
||||
/// paths this code base actually addresses across nodes (<see cref="RemotingHardening.TrustedSelectionPaths"/>),
|
||||
/// remote deployment is refused, and <c>PoisonPill</c>/<c>Kill</c>-class messages from a peer are dropped. A
|
||||
/// receive-side filter only — the wire format is unchanged, so a mixed old/new pair keeps working.</item>
|
||||
/// <item><see cref="Tls"/> — <b>off by default</b> (opt-in): TLS with mutual authentication on the remoting
|
||||
/// transport, so only a peer presenting an accepted certificate can associate (and therefore join the mesh).
|
||||
/// All-or-nothing per mesh: a TLS node and a plain node cannot talk.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
public sealed class AkkaRemotingOptions
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets or sets whether Akka's <c>untrusted-mode</c> is on. Default <see langword="true"/>. Set
|
||||
/// <see langword="false"/> only as an escape hatch while reporting a missing path (the drop is logged as a Warning
|
||||
/// naming it; <see cref="AdditionalTrustedSelectionPaths"/> is the targeted fix).
|
||||
/// </summary>
|
||||
public bool UntrustedMode { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets extra actor paths (<c>/user/…</c> or <c>/system/…</c>, no address) a peer may reach with an
|
||||
/// <c>ActorSelection</c>, on top of <see cref="RemotingHardening.TrustedSelectionPaths"/>.
|
||||
/// </summary>
|
||||
public string[] AdditionalTrustedSelectionPaths { get; set; } = [];
|
||||
|
||||
/// <summary>Gets or sets the transport TLS settings (opt-in).</summary>
|
||||
public AkkaRemotingTlsOptions Tls { get; set; } = new();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// TLS on the Akka remoting transport (<c>Cluster:Remoting:Tls</c>). Opt-in; see <c>docs/security.md</c> §"Akka
|
||||
/// remoting" for the rollout (both nodes of a pair, and every node a central admin dials for diagnostics, together).
|
||||
/// </summary>
|
||||
public sealed class AkkaRemotingTlsOptions
|
||||
{
|
||||
/// <summary>Gets or sets whether the remoting transport runs TLS. Default <see langword="false"/>.</summary>
|
||||
/// <remarks>
|
||||
/// Changes the address scheme from <c>akka.tcp</c> to <c>akka.ssl.tcp</c>. <c>Cluster:SeedNodes</c> may keep
|
||||
/// either spelling: the scheme is rewritten to match this switch at startup.
|
||||
/// </remarks>
|
||||
public bool Enabled { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the node certificate as a PKCS#12 (<c>.pfx</c>) file, with its private key. Absolute path.</summary>
|
||||
public string? CertificatePath { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the PFX password — supply it as <c>${secret:…}</c> or an environment variable, never committed.</summary>
|
||||
public string? CertificatePassword { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the node certificate's SHA-1 thumbprint in a certificate store (alternative to <see cref="CertificatePath"/>).</summary>
|
||||
public string? CertificateThumbprint { get; set; }
|
||||
|
||||
/// <summary>Gets or sets the store name for <see cref="CertificateThumbprint"/>. Default <c>My</c>.</summary>
|
||||
public string CertificateStoreName { get; set; } = "My";
|
||||
|
||||
/// <summary>Gets or sets the store location for <see cref="CertificateThumbprint"/>. Default <c>LocalMachine</c>.</summary>
|
||||
public string CertificateStoreLocation { get; set; } = "LocalMachine";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets whether an inbound peer must present a certificate too. Default <see langword="true"/> — without it
|
||||
/// the transport is encrypted but any host can still associate (and join), which is the threat this exists for.
|
||||
/// </summary>
|
||||
public bool RequireMutualAuthentication { get; set; } = true;
|
||||
|
||||
/// <summary>Gets or sets whether the peer certificate's CN/SAN must match the host it was dialled at. Default off.</summary>
|
||||
public bool ValidateCertificateHostname { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the SHA-1 thumbprints of the peer certificates this node accepts (its pair partner, its own, and —
|
||||
/// on a node an admin node dials for diagnostics — the admin nodes'). When non-empty, a peer is accepted on its
|
||||
/// pinned thumbprint alone (self-signed certificates work; no CA needed). When empty, the peer's chain must
|
||||
/// validate against the machine's trust store.
|
||||
/// </summary>
|
||||
public string[] AllowedThumbprints { get; set; } = [];
|
||||
}
|
||||
@@ -78,7 +78,10 @@ public sealed class ClusterBootstrapCoordinator : IHostedService
|
||||
{
|
||||
try
|
||||
{
|
||||
var seeds = _options.SeedNodes ?? Array.Empty<string>();
|
||||
// lmxopcua#1003: the transport's scheme (akka.ssl.tcp under TLS) wins over the configured spelling.
|
||||
var seeds = (_options.SeedNodes ?? Array.Empty<string>())
|
||||
.Select(s => RemotingHardening.NormalizeSeed(s, _options.Remoting?.Tls))
|
||||
.ToArray();
|
||||
var role = ClusterBootstrapGuard.Analyze(seeds, _options.PublicHostname, _options.Port);
|
||||
|
||||
string[] order;
|
||||
|
||||
@@ -44,7 +44,7 @@ namespace ZB.MOM.WW.OtOpcUa.Cluster;
|
||||
public static class ClusterBootstrapGuard
|
||||
{
|
||||
private static readonly Regex SeedPattern =
|
||||
new(@"^akka(?:\.[a-z0-9]+)?://[^@/]+@(?<host>[^:/]+):(?<port>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
new(@"^akka(?:\.[a-z0-9]+)*://[^@/]+@(?<host>[^:/]+):(?<port>\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
|
||||
|
||||
/// <summary>The analyzed bootstrap role of this node within its seed list.</summary>
|
||||
/// <param name="Applies">True only when the guard engages: exactly two seeds, one of them this node.</param>
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.Metrics;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using Akka.Actor;
|
||||
using Akka.Event;
|
||||
using Akka.Remote.Hosting;
|
||||
using Akka.Remote.Transport.DotNetty;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Cluster;
|
||||
|
||||
/// <summary>
|
||||
/// Builds the Akka remoting hardening for <see cref="AkkaRemotingOptions"/> (lmxopcua#1003): the <c>untrusted-mode</c>
|
||||
/// HOCON with the trusted selection paths, the TLS transport settings, and the scheme normalisation of seed addresses.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>What untrusted-mode does in Akka.NET 1.5</b> (read off <c>Akka.Remote.DefaultMessageDispatcher</c>, the only
|
||||
/// consumer of the setting): an inbound <c>ActorSelection</c> is delivered only when its path is listed in
|
||||
/// <c>trusted-selection-paths</c> (and its payload is not <c>IPossiblyHarmful</c>); a message for the remote
|
||||
/// daemon (remote deployment) is dropped; an <c>IPossiblyHarmful</c> message (<c>PoisonPill</c>, <c>Kill</c>, …)
|
||||
/// sent to an actor reference is dropped; a message a peer asks this node to forward to a third system is dropped.
|
||||
/// Messages to actor references (DistributedPubSub delivery, replies, <c>Ask</c> temp actors) and system messages
|
||||
/// (remote watch) are unaffected. It does NOT authenticate the peer: the cluster daemon has to stay reachable for
|
||||
/// joining to work at all, so any host that can reach the port can still associate. That is what <see cref="AkkaRemotingTlsOptions"/>
|
||||
/// (mutual TLS) is for.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>The trusted set is every path this code base addresses with a selection across nodes</b>, enumerated from
|
||||
/// the Akka 1.5.62 sources and this repo (no other <c>ActorSelection</c> crosses a node boundary):
|
||||
/// <list type="bullet">
|
||||
/// <item><c>/system/cluster/core/daemon</c> — Akka.Cluster gossip, InitJoin/Join/Welcome, seed-node processes,
|
||||
/// leave/exiting.</item>
|
||||
/// <item><c>/system/cluster/heartbeatReceiver</c> — cluster failure-detector heartbeats.</item>
|
||||
/// <item><c>/system/remote-watcher</c> — remote-watch heartbeats (<c>RemoteWatcher</c>/<c>ClusterRemoteWatcher</c>).</item>
|
||||
/// <item><c>/system/distributedPubSubMediator</c> — DistributedPubSub registry gossip (redundancy-state, DPS
|
||||
/// transports, secrets replication).</item>
|
||||
/// <item><c>/user/{name}</c>, <c>/user/{name}/{name}</c> — each cluster singleton's manager (hand-over
|
||||
/// protocol between managers) and the singleton itself (the proxies' <c>Identify</c>); see
|
||||
/// <see cref="SingletonNames"/>.</item>
|
||||
/// <item><c>/user/driver-host</c> — the AdminUI's <c>/fleet/diagnostics</c> query (<c>FleetDiagnosticsClient</c>).</item>
|
||||
/// </list>
|
||||
/// A drop is logged at <b>Warning</b> naming the path (once per path) and counted on
|
||||
/// <c>otopcua.cluster.remoting.untrusted_drops</c>, so a missed path is loud, not a silent outage.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class RemotingHardening
|
||||
{
|
||||
/// <summary>
|
||||
/// The cluster singleton names this code base registers (<c>ControlPlane.ServiceCollectionExtensions</c>). A test
|
||||
/// fails if a singleton is added there without being added here.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> SingletonNames =
|
||||
[
|
||||
"config-publish",
|
||||
"admin-operations",
|
||||
"audit-writer",
|
||||
"redundancy-state",
|
||||
"cluster-node-address-reconciler",
|
||||
"deployment-retention",
|
||||
];
|
||||
|
||||
/// <summary>The Akka infrastructure paths a peer reaches by selection.</summary>
|
||||
public static readonly IReadOnlyList<string> InfrastructurePaths =
|
||||
[
|
||||
"/system/cluster/core/daemon",
|
||||
"/system/cluster/heartbeatReceiver",
|
||||
"/system/remote-watcher",
|
||||
"/system/distributedPubSubMediator",
|
||||
];
|
||||
|
||||
/// <summary>The driver host actor (<c>Runtime.ServiceCollectionExtensions.DriverHostActorName</c>), queried for diagnostics.</summary>
|
||||
public const string DriverHostPath = "/user/driver-host";
|
||||
|
||||
/// <summary>The metric counting inbound remote messages dropped by untrusted-mode.</summary>
|
||||
public const string DropCounterName = "otopcua.cluster.remoting.untrusted_drops";
|
||||
|
||||
private static readonly Meter Meter = new("ZB.MOM.WW.OtOpcUa.Cluster.Remoting");
|
||||
private static readonly Counter<long> DropCounter = Meter.CreateCounter<long>(DropCounterName);
|
||||
private static readonly ConcurrentDictionary<ActorSystem, ConcurrentQueue<string>> Drops = new();
|
||||
|
||||
private static readonly Regex PathPattern = new(@"^/(user|system)(/[A-Za-z0-9\-_.*$+:@&=,!~';]+)+$", RegexOptions.Compiled);
|
||||
private static readonly Regex ThumbprintPattern = new("^[0-9A-Fa-f]{40}$", RegexOptions.Compiled);
|
||||
|
||||
/// <summary>Every path a peer may reach by <c>ActorSelection</c> (before <see cref="AkkaRemotingOptions.AdditionalTrustedSelectionPaths"/>).</summary>
|
||||
public static IReadOnlyList<string> TrustedSelectionPaths { get; } = BuildTrustedPaths();
|
||||
|
||||
private static IReadOnlyList<string> BuildTrustedPaths()
|
||||
{
|
||||
var paths = new List<string>(InfrastructurePaths);
|
||||
foreach (var name in SingletonNames)
|
||||
{
|
||||
paths.Add($"/user/{name}");
|
||||
paths.Add($"/user/{name}/{name}");
|
||||
}
|
||||
paths.Add(DriverHostPath);
|
||||
return paths;
|
||||
}
|
||||
|
||||
/// <summary>Builds the <c>akka.remote</c> untrusted-mode HOCON for <paramref name="options"/>.</summary>
|
||||
/// <param name="options">The remoting options.</param>
|
||||
/// <returns>The HOCON (sets <c>untrusted-mode = off</c> explicitly when disabled).</returns>
|
||||
public static string BuildUntrustedModeHocon(AkkaRemotingOptions options)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
if (!options.UntrustedMode) return "akka.remote.untrusted-mode = off";
|
||||
var paths = TrustedSelectionPaths
|
||||
.Concat((options.AdditionalTrustedSelectionPaths ?? []).Select(static p => p.Trim()).Where(static p => p.Length > 0))
|
||||
.Distinct(StringComparer.Ordinal);
|
||||
var sb = new StringBuilder("akka.remote {\n untrusted-mode = on\n trusted-selection-paths = [\n");
|
||||
foreach (var path in paths) sb.Append(" \"").Append(path).Append("\"\n");
|
||||
sb.Append(" ]\n}\n");
|
||||
return sb.ToString();
|
||||
}
|
||||
|
||||
/// <summary>The address scheme the transport uses: <c>akka.ssl.tcp</c> with TLS, <c>akka.tcp</c> without.</summary>
|
||||
/// <param name="tls">The TLS options.</param>
|
||||
/// <returns>The protocol part of an address.</returns>
|
||||
public static string Scheme(AkkaRemotingTlsOptions? tls) => tls is { Enabled: true } ? "akka.ssl.tcp" : "akka.tcp";
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites a seed's scheme to the one the transport uses, so <c>Cluster:SeedNodes</c> need not change when TLS is
|
||||
/// switched (an <c>akka.tcp</c> seed would otherwise never be dialled by a TLS transport). Anything that is not an
|
||||
/// <c>akka.tcp</c>/<c>akka.ssl.tcp</c> address is returned unchanged.
|
||||
/// </summary>
|
||||
/// <param name="seed">The configured seed.</param>
|
||||
/// <param name="tls">The TLS options.</param>
|
||||
/// <returns>The seed with the active scheme.</returns>
|
||||
public static string NormalizeSeed(string seed, AkkaRemotingTlsOptions? tls)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(seed)) return seed;
|
||||
var trimmed = seed.Trim();
|
||||
var scheme = Scheme(tls);
|
||||
foreach (var known in new[] { "akka.ssl.tcp://", "akka.tcp://" })
|
||||
{
|
||||
if (trimmed.StartsWith(known, StringComparison.OrdinalIgnoreCase))
|
||||
return scheme + "://" + trimmed[known.Length..];
|
||||
}
|
||||
return seed;
|
||||
}
|
||||
|
||||
/// <summary>Validates the remoting options; returns one message per problem.</summary>
|
||||
/// <param name="options">The options.</param>
|
||||
/// <returns>The problems (empty when valid).</returns>
|
||||
public static IEnumerable<string> Validate(AkkaRemotingOptions? options)
|
||||
{
|
||||
if (options is null) yield break;
|
||||
foreach (var path in options.AdditionalTrustedSelectionPaths ?? [])
|
||||
{
|
||||
if (!PathPattern.IsMatch(path?.Trim() ?? string.Empty))
|
||||
yield return $"Cluster:Remoting:AdditionalTrustedSelectionPaths entry '{path}' is not an actor path "
|
||||
+ "(expected '/user/…' or '/system/…' with no address part).";
|
||||
}
|
||||
|
||||
var tls = options.Tls;
|
||||
if (tls is null || !tls.Enabled) yield break;
|
||||
var hasPath = !string.IsNullOrWhiteSpace(tls.CertificatePath);
|
||||
var hasThumb = !string.IsNullOrWhiteSpace(tls.CertificateThumbprint);
|
||||
if (hasPath == hasThumb)
|
||||
yield return "Cluster:Remoting:Tls:Enabled needs exactly one of CertificatePath (a .pfx) or CertificateThumbprint (a store certificate).";
|
||||
if (hasPath && !Path.IsPathFullyQualified(tls.CertificatePath!))
|
||||
yield return $"Cluster:Remoting:Tls:CertificatePath '{tls.CertificatePath}' must be an absolute path.";
|
||||
else if (hasPath && !File.Exists(tls.CertificatePath))
|
||||
yield return $"Cluster:Remoting:Tls:CertificatePath '{tls.CertificatePath}' does not exist.";
|
||||
if (hasThumb && !ThumbprintPattern.IsMatch(NormalizeThumbprint(tls.CertificateThumbprint!)))
|
||||
yield return "Cluster:Remoting:Tls:CertificateThumbprint must be a 40-hex-digit SHA-1 thumbprint.";
|
||||
if (hasThumb && !Enum.TryParse<StoreName>(tls.CertificateStoreName, ignoreCase: true, out _))
|
||||
yield return $"Cluster:Remoting:Tls:CertificateStoreName '{tls.CertificateStoreName}' is not a certificate store name.";
|
||||
if (hasThumb && !Enum.TryParse<StoreLocation>(tls.CertificateStoreLocation, ignoreCase: true, out _))
|
||||
yield return $"Cluster:Remoting:Tls:CertificateStoreLocation '{tls.CertificateStoreLocation}' is not CurrentUser or LocalMachine.";
|
||||
foreach (var thumb in tls.AllowedThumbprints ?? [])
|
||||
{
|
||||
if (!ThumbprintPattern.IsMatch(NormalizeThumbprint(thumb ?? string.Empty)))
|
||||
yield return $"Cluster:Remoting:Tls:AllowedThumbprints entry '{thumb}' is not a 40-hex-digit SHA-1 thumbprint.";
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Applies the TLS settings to <paramref name="remote"/>: loads the node certificate (PFX file or store) and sets
|
||||
/// mutual authentication and the peer validator (thumbprint pinning, or chain validation when no pins are given;
|
||||
/// hostname matching on request). No-op when TLS is off.
|
||||
/// </summary>
|
||||
/// <param name="remote">The remote options being built.</param>
|
||||
/// <param name="tls">The TLS options (already validated).</param>
|
||||
/// <exception cref="InvalidOperationException">The certificate cannot be loaded or has no private key.</exception>
|
||||
public static void ApplyTls(RemoteOptions remote, AkkaRemotingTlsOptions? tls)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(remote);
|
||||
if (tls is not { Enabled: true }) return;
|
||||
|
||||
var certificate = LoadCertificate(tls);
|
||||
if (!certificate.HasPrivateKey)
|
||||
throw new InvalidOperationException(
|
||||
$"Cluster:Remoting:Tls: the node certificate ({certificate.Subject}, {certificate.Thumbprint}) has no private key.");
|
||||
|
||||
CertificateValidationCallback? validator = null;
|
||||
var pins = (tls.AllowedThumbprints ?? []).Select(NormalizeThumbprint).Where(static t => t.Length > 0).ToArray();
|
||||
if (pins.Length > 0)
|
||||
{
|
||||
validator = CertificateValidation.PinnedCertificate(pins);
|
||||
if (tls.ValidateCertificateHostname)
|
||||
validator = CertificateValidation.Combine(validator, CertificateValidation.ValidateHostname());
|
||||
}
|
||||
|
||||
remote.EnableSsl = true;
|
||||
remote.Ssl = new SslOptions
|
||||
{
|
||||
X509Certificate = certificate,
|
||||
SuppressValidation = false,
|
||||
RequireMutualAuthentication = tls.RequireMutualAuthentication,
|
||||
ValidateCertificateHostname = tls.ValidateCertificateHostname,
|
||||
CustomValidator = validator,
|
||||
};
|
||||
}
|
||||
|
||||
private static X509Certificate2 LoadCertificate(AkkaRemotingTlsOptions tls)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(tls.CertificatePath))
|
||||
{
|
||||
try
|
||||
{
|
||||
// DefaultKeySet, as Kestrel loads a PFX: an ephemeral key cannot back an SslStream server on Windows
|
||||
// (SChannel needs a key container) and is unsupported on macOS.
|
||||
return X509CertificateLoader.LoadPkcs12FromFile(tls.CertificatePath, tls.CertificatePassword, X509KeyStorageFlags.DefaultKeySet);
|
||||
}
|
||||
catch (Exception ex) when (ex is System.Security.Cryptography.CryptographicException or IOException)
|
||||
{
|
||||
throw new InvalidOperationException(
|
||||
$"Cluster:Remoting:Tls: cannot load the certificate '{tls.CertificatePath}': {ex.Message}", ex);
|
||||
}
|
||||
}
|
||||
|
||||
var thumbprint = NormalizeThumbprint(tls.CertificateThumbprint ?? string.Empty);
|
||||
using var store = new X509Store(
|
||||
Enum.Parse<StoreName>(tls.CertificateStoreName, ignoreCase: true),
|
||||
Enum.Parse<StoreLocation>(tls.CertificateStoreLocation, ignoreCase: true));
|
||||
store.Open(OpenFlags.ReadOnly | OpenFlags.OpenExistingOnly);
|
||||
var found = store.Certificates.Find(X509FindType.FindByThumbprint, thumbprint, validOnly: false);
|
||||
if (found.Count == 0)
|
||||
throw new InvalidOperationException(
|
||||
$"Cluster:Remoting:Tls: no certificate with thumbprint {thumbprint} in {tls.CertificateStoreLocation}\\{tls.CertificateStoreName}.");
|
||||
return found[0];
|
||||
}
|
||||
|
||||
private static string NormalizeThumbprint(string thumbprint)
|
||||
=> new string(thumbprint.Where(static c => !char.IsWhiteSpace(c) && c != ':').ToArray()).ToUpperInvariant();
|
||||
|
||||
/// <summary>Paths of inbound selections (or daemon / harmful messages) <paramref name="system"/> dropped (tests, diagnostics).</summary>
|
||||
/// <param name="system">The actor system.</param>
|
||||
/// <returns>The drops recorded so far, oldest first (at most 1000).</returns>
|
||||
public static IReadOnlyList<string> DroppedFor(ActorSystem system)
|
||||
=> Drops.TryGetValue(system, out var q) ? q.ToArray() : [];
|
||||
|
||||
/// <summary>Spawns the monitor that turns Akka's Debug-level untrusted-mode drops into Warnings and a metric.</summary>
|
||||
/// <param name="system">The actor system.</param>
|
||||
public static void StartDropMonitor(ActorSystem system)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(system);
|
||||
var queue = Drops.GetOrAdd(system, static _ => new ConcurrentQueue<string>());
|
||||
var monitor = system.ActorOf(Props.Create(() => new UntrustedDropMonitor(queue)), "untrusted-drop-monitor");
|
||||
system.EventStream.Subscribe(monitor, typeof(Debug));
|
||||
system.RegisterOnTermination(() => Drops.TryRemove(system, out _));
|
||||
}
|
||||
|
||||
/// <summary>Classifies one Akka Debug message as an untrusted-mode drop.</summary>
|
||||
/// <param name="message">The rendered message.</param>
|
||||
/// <param name="what">What was dropped (the selection path, or the kind of message).</param>
|
||||
/// <returns>True for a drop.</returns>
|
||||
internal static bool TryParseDrop(string? message, out string what)
|
||||
{
|
||||
what = string.Empty;
|
||||
if (string.IsNullOrEmpty(message)) return false;
|
||||
const string selection = "operating in UntrustedMode, dropping inbound actor selection to [";
|
||||
const string harmful = "operating in UntrustedMode, dropping inbound IPossiblyHarmful message of type ";
|
||||
const string daemon = "dropping daemon message in untrusted mode";
|
||||
if (message.StartsWith(selection, StringComparison.Ordinal))
|
||||
{
|
||||
var end = message.IndexOf(']', selection.Length);
|
||||
what = end > selection.Length ? message[selection.Length..end] : message[selection.Length..];
|
||||
return true;
|
||||
}
|
||||
if (message.StartsWith(harmful, StringComparison.Ordinal))
|
||||
{
|
||||
what = "IPossiblyHarmful " + message[harmful.Length..];
|
||||
return true;
|
||||
}
|
||||
if (message.StartsWith(daemon, StringComparison.Ordinal))
|
||||
{
|
||||
what = "remote daemon (remote deployment)";
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool MightBeDrop(string? format)
|
||||
=> format is not null
|
||||
&& (format.StartsWith("operating in UntrustedMode", StringComparison.Ordinal)
|
||||
|| format.StartsWith("dropping daemon message in untrusted mode", StringComparison.Ordinal));
|
||||
|
||||
private sealed class UntrustedDropMonitor : ReceiveActor
|
||||
{
|
||||
private const int MaxRecorded = 1000;
|
||||
private const int MaxWarnedPaths = 256;
|
||||
private readonly HashSet<string> _warned = new(StringComparer.Ordinal);
|
||||
private readonly ILoggingAdapter _log = Context.GetLogger();
|
||||
|
||||
public UntrustedDropMonitor(ConcurrentQueue<string> drops)
|
||||
{
|
||||
Receive<Debug>(debug =>
|
||||
{
|
||||
// Cheap pre-filter on the format string: every Debug event of the system arrives here, and rendering
|
||||
// each one would cost a format per event for nothing.
|
||||
if (debug.Message is LogMessage lm && !MightBeDrop(lm.Format)) return;
|
||||
if (!TryParseDrop(debug.Message?.ToString(), out var what)) return;
|
||||
DropCounter.Add(1);
|
||||
if (drops.Count < MaxRecorded) drops.Enqueue(what);
|
||||
if (_warned.Count < MaxWarnedPaths && _warned.Add(what))
|
||||
{
|
||||
_log.Warning(
|
||||
"Akka untrusted-mode dropped an inbound remote message: {0}. If this is a path OtOpcUa itself uses, add it to "
|
||||
+ "Cluster:Remoting:AdditionalTrustedSelectionPaths and report it (lmxopcua#1003); otherwise a peer is "
|
||||
+ "addressing an actor it should not. Further drops of it are counted on {1} only.",
|
||||
what, DropCounterName);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -144,12 +144,23 @@ public static class ServiceCollectionExtensions
|
||||
setup.AddLogger<SerilogLogger>();
|
||||
});
|
||||
|
||||
builder.WithRemoting(new RemoteOptions
|
||||
var remote = new RemoteOptions
|
||||
{
|
||||
HostName = options.Hostname,
|
||||
Port = options.Port,
|
||||
PublicHostName = options.PublicHostname,
|
||||
});
|
||||
};
|
||||
// lmxopcua#1003: opt-in mutual TLS on the transport (no-op unless Cluster:Remoting:Tls:Enabled).
|
||||
RemotingHardening.ApplyTls(remote, options.Remoting?.Tls);
|
||||
builder.WithRemoting(remote);
|
||||
|
||||
// lmxopcua#1003: untrusted-mode (default on) — inbound ActorSelection only to the paths this code base uses
|
||||
// across nodes, no remote deployment, no PoisonPill/Kill from a peer. Prepend: highest precedence, so no other
|
||||
// fragment (or a stray akka.remote block) silently turns it off. Drops become Warnings + a metric.
|
||||
var remoting = options.Remoting ?? new AkkaRemotingOptions();
|
||||
builder.AddHocon(RemotingHardening.BuildUntrustedModeHocon(remoting), HoconAddMode.Prepend);
|
||||
if (remoting.UntrustedMode)
|
||||
builder.WithActors((system, _) => RemotingHardening.StartDropMonitor(system));
|
||||
|
||||
builder.WithClustering(BuildClusterOptions(options));
|
||||
|
||||
@@ -283,7 +294,13 @@ public static class ServiceCollectionExtensions
|
||||
// unjoined and ClusterBootstrapCoordinator picks the order (founder self-first / joiner
|
||||
// peer-first, after a reachability probe) and issues the single Cluster.JoinSeedNodes.
|
||||
// The config seed list is still read — by the coordinator, off AkkaClusterOptions.SeedNodes.
|
||||
SeedNodes = options.BootstrapGuard.Enabled ? Array.Empty<string>() : options.SeedNodes,
|
||||
//
|
||||
// lmxopcua#1003: each seed's scheme follows the transport (akka.ssl.tcp under TLS), so an operator switching
|
||||
// TLS on does not also have to respell every seed.
|
||||
SeedNodes = options.BootstrapGuard.Enabled
|
||||
? Array.Empty<string>()
|
||||
: (options.SeedNodes ?? Array.Empty<string>())
|
||||
.Select(s => RemotingHardening.NormalizeSeed(s, options.Remoting?.Tls)).ToArray(),
|
||||
Roles = options.Roles,
|
||||
SplitBrainResolver = IsKeepOldest(options) ? new KeepOldestOption { DownIfAlone = true } : null,
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Why (review 2026-12-02 K-1, option 4).</b> The worker used to read, verify and write the cache itself with
|
||||
/// the key it received in <c>Hello</c>, 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Fill.</b> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Compatibility.</b> The host compiles against its own runtime, so it ships images only to a worker whose
|
||||
/// <c>Ready.pe_image_abi</c> equals <see cref="ScriptSandbox.ImageAbi"/>; any other worker (including a pre-#1014
|
||||
/// one, which reports none) compiles every script, as with no cache.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal sealed class HostPeCache : IDisposable
|
||||
{
|
||||
/// <summary>A fill backlog above this is dropped (best effort: a dropped fill costs a recompile at the next start).</summary>
|
||||
internal const int MaxQueuedFills = 10_000;
|
||||
|
||||
private readonly ScriptPeCacheStore _store;
|
||||
private readonly ILogger _log;
|
||||
private readonly ConcurrentDictionary<string, byte> _queued = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, byte> _abiWarned = new(StringComparer.Ordinal);
|
||||
private readonly BlockingCollection<Fill> _fills = new(new ConcurrentQueue<Fill>());
|
||||
private readonly object _idleGate = new();
|
||||
private TaskCompletionSource _idle = NewCompleted();
|
||||
private int _outstanding;
|
||||
private Thread? _thread;
|
||||
private int _failureLogged;
|
||||
private volatile bool _disposed;
|
||||
|
||||
/// <summary>Creates the host cache over <paramref name="store"/>.</summary>
|
||||
/// <param name="store">The store, opened with the node's key.</param>
|
||||
/// <param name="log">Host diagnostics.</param>
|
||||
public HostPeCache(ScriptPeCacheStore store, ILogger log)
|
||||
{
|
||||
_store = store ?? throw new ArgumentNullException(nameof(store));
|
||||
_log = log ?? throw new ArgumentNullException(nameof(log));
|
||||
}
|
||||
|
||||
/// <summary>The cache directory.</summary>
|
||||
public string Directory => _store.Directory;
|
||||
|
||||
/// <summary>Whether a worker reporting <paramref name="workerImageAbi"/> may be sent this host's images.</summary>
|
||||
/// <param name="workerImageAbi">The worker's <c>Ready.pe_image_abi</c>.</param>
|
||||
/// <returns>True when it equals <see cref="ScriptSandbox.ImageAbi"/>.</returns>
|
||||
public bool IsCompatible(string? workerImageAbi)
|
||||
=> string.Equals(workerImageAbi, ScriptSandbox.ImageAbi, StringComparison.Ordinal);
|
||||
|
||||
/// <summary>Logs, once per distinct value, that a worker is not served images because its ABI differs.</summary>
|
||||
/// <param name="shard">The worker's shard.</param>
|
||||
/// <param name="workerImageAbi">What it reported.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Reads and verifies the entry for one source. A rejected entry has been deleted.</summary>
|
||||
/// <param name="kind">The context kind.</param>
|
||||
/// <param name="source">The source.</param>
|
||||
/// <param name="image">The verified image on a hit.</param>
|
||||
/// <returns>Hit, miss or rejected.</returns>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deletes the entry for one source (its image did not load in a worker).</summary>
|
||||
/// <param name="kind">The context kind.</param>
|
||||
/// <param name="source">The source.</param>
|
||||
public void Evict(ContextKind kind, string source)
|
||||
{
|
||||
try { File.Delete(_store.EntryPath(EntryId(kind, source))); }
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Queues the host's own compile of <paramref name="source"/> into the cache. Call only after a worker compiled
|
||||
/// it successfully. Duplicates of a queued fill are ignored; past <see cref="MaxQueuedFills"/> the fill is dropped.
|
||||
/// </summary>
|
||||
/// <param name="kind">The context kind.</param>
|
||||
/// <param name="source">The source.</param>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>Completes when no fill is queued or running (tests; a fill is best effort and never awaited in production).</summary>
|
||||
/// <returns>The idle task.</returns>
|
||||
public Task WhenIdleAsync()
|
||||
{
|
||||
lock (_idleGate) return _idle.Task;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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<AlarmPredicateContext, bool>.CompileToImage(fill.Source)
|
||||
: ScriptEvaluator<VirtualTagContext, object?>.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();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The entry id for one source: the HOST's compile fingerprint for the kind's context, the kind, the source.</summary>
|
||||
internal static string EntryId(ContextKind kind, string source)
|
||||
{
|
||||
var fingerprint = kind == ContextKind.AlarmPredicate
|
||||
? ScriptEvaluator<AlarmPredicateContext, bool>.CacheFingerprint
|
||||
: ScriptEvaluator<VirtualTagContext, object?>.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);
|
||||
}
|
||||
+20
-12
@@ -64,7 +64,9 @@ public sealed record ScriptRunnerStatus(
|
||||
/// the result is <see cref="ScriptRunStatus.Unavailable"/> — never an in-process run — carrying a
|
||||
/// <see cref="ScriptRunOutcome.Recovery"/> task the seam re-evaluates on.</item>
|
||||
/// <item><b>PE cache</b> (design §7): with <see cref="ScriptWorkerOptions.PeCacheDir"/> set, workers load
|
||||
/// HMAC-verified compiled images instead of re-entering Roslyn after a restart.</item>
|
||||
/// compiled images instead of re-entering Roslyn after a restart. The host owns it end to end
|
||||
/// (<see cref="HostPeCache"/>, 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.</item>
|
||||
/// </list>
|
||||
/// </remarks>
|
||||
public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisposable, IDisposable
|
||||
@@ -138,8 +140,7 @@ public sealed class OutOfProcessScriptRunner : IPhysicalScriptRunner, IAsyncDisp
|
||||
private readonly ConcurrentDictionary<string, string> _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;
|
||||
|
||||
/// <summary>Test seam: the launched workers' initial silence limit (null = three heartbeat intervals).</summary>
|
||||
@@ -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);
|
||||
|
||||
/// <summary>
|
||||
/// 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
|
||||
/// <summary>The marker directory this runner writes launch markers to and sweeps at startup.</summary>
|
||||
internal string MarkerDirectory => _markerDirectory;
|
||||
|
||||
/// <summary>
|
||||
/// Completes when the host has no PE-cache fill queued or running (tests: the fill is background work, lmxopcua#1014).
|
||||
/// </summary>
|
||||
/// <returns>The idle task (completed at once without a cache).</returns>
|
||||
internal Task PeCacheIdleAsync() => _peCache?.WhenIdleAsync() ?? Task.CompletedTask;
|
||||
|
||||
/// <summary>PE cache outcomes reported by this runner's workers (tests / diagnostics).</summary>
|
||||
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();
|
||||
}
|
||||
|
||||
/// <summary>Stops every worker (blocking).</summary>
|
||||
@@ -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,
|
||||
|
||||
@@ -75,8 +75,11 @@ internal sealed record BatchSubmission(string Key, EvalRequest Request, TimeSpan
|
||||
/// <param name="HardGrace">The worker watchdog's grace past the soft deadline.</param>
|
||||
/// <param name="HeartbeatInterval">How often the worker sends a heartbeat.</param>
|
||||
/// <param name="HandshakeTimeout">How long a launch may take to reach Ready.</param>
|
||||
/// <param name="PeCacheDirectory">The compiled-PE cache directory handed to the worker; null = no cache.</param>
|
||||
/// <param name="PeCacheKey">The cache's HMAC key (with <paramref name="PeCacheDirectory"/>).</param>
|
||||
/// <param name="PeCache">
|
||||
/// 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.
|
||||
/// </param>
|
||||
/// <param name="MarkerDirectory">Where the launch marker for the orphan sweep is written; null = none.</param>
|
||||
/// <param name="LoadTimeout">
|
||||
/// How long one compile may run, counted from the worker's <c>LoadStarted</c> 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;
|
||||
|
||||
/// <summary>The host's PE cache for THIS worker (null: none configured, or the worker's image ABI differs).</summary>
|
||||
private readonly HostPeCache? _peCache;
|
||||
private readonly Action<WorkerExit> _onExiting;
|
||||
private readonly string? _markerPath;
|
||||
private TaskCompletionSource<DiagnosticsReply>? _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<LogBatch> onLogs, TimeSpan heartbeatInterval, TimeSpan loadTimeout,
|
||||
Action<WorkerExit> onExiting, string? markerPath, bool workerSoftClock, TimeSpan? heartbeatSilenceLimit)
|
||||
Action<WorkerExit> 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
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="spec">The launch spec.</param>
|
||||
/// <param name="nonce">The launch nonce the worker must echo.</param>
|
||||
/// <returns>The Hello.</returns>
|
||||
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,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The host half of the handshake: send <paramref name="hello"/>, require a <c>Ready</c> as the first frame,
|
||||
/// echoing <paramref name="expectedNonce"/> (constant-time compare) from <paramref name="expectedPid"/>.
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
/// <returns>The host-side lookup, or null when this worker gets no cache.</returns>
|
||||
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
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>Forgets a key's compiled form here and in the worker.</summary>
|
||||
/// <param name="keys">The scoped keys.</param>
|
||||
public void Unload(IReadOnlyCollection<string> keys)
|
||||
@@ -1107,6 +1177,18 @@ internal sealed class WorkerConnection : IAsyncDisposable
|
||||
|
||||
public LoadEntry Entry { get; } = entry;
|
||||
|
||||
/// <summary>lmxopcua#1014: the host's PE-cache lookup for this load; null = no cache for it.</summary>
|
||||
public PeCacheLookup? CacheLookup { get; init; }
|
||||
|
||||
/// <summary>Whether the load carried a verified image from the cache.</summary>
|
||||
public bool ImageAttached { get; init; }
|
||||
|
||||
/// <summary>The script's kind.</summary>
|
||||
public ContextKind Kind { get; init; }
|
||||
|
||||
/// <summary>The source, while the cache needs it (null without a cache).</summary>
|
||||
public string? Source { get; init; }
|
||||
|
||||
/// <summary>The worker has started compiling it: arm the compile timeout (once).</summary>
|
||||
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<string, LoadEntry>(Key, Entry));
|
||||
Owner.SettleCache(this, outcome, Kind, Source ?? string.Empty);
|
||||
Entry.Complete(outcome);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -22,7 +22,9 @@ public enum PeCacheLookup
|
||||
/// <summary>
|
||||
/// The node-local compiled-PE cache (lmxopcua#780 design §7, owner decision §14 #8): content-addressed files under
|
||||
/// <c>Scripting:Worker:PeCacheDir</c>, 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.
|
||||
/// <b>Host-only since lmxopcua#1014</b>: the host reads, verifies, compiles and writes entries (<c>HostPeCache</c>) and
|
||||
/// ships a verified image to the worker inside the load; the worker holds no key and never opens the directory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <list type="bullet">
|
||||
@@ -37,7 +39,7 @@ public enum PeCacheLookup
|
||||
/// outside the analyzer; a rejected entry is deleted and the source recompiled.</item>
|
||||
/// <item><b>Key.</b> 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 <c>Hello</c>, never on disk or in its environment.</item>
|
||||
/// work). The worker never receives it (lmxopcua#1014 — it used to arrive in <c>Hello</c>).</item>
|
||||
/// <item><b>Writes</b> 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.</item>
|
||||
/// </list>
|
||||
@@ -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;
|
||||
|
||||
@@ -97,7 +97,32 @@ public static class ScriptSandbox
|
||||
/// </summary>
|
||||
/// <param name="contextType">The concrete script context type.</param>
|
||||
/// <returns>One line per reference, in a stable order.</returns>
|
||||
public static IEnumerable<string> ReferenceIdentities(Type contextType)
|
||||
public static IEnumerable<string> ReferenceIdentities(Type contextType) => ReferenceIdentitiesCore(contextType);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>ctx</c> 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 <see cref="ScriptEvaluator{TContext, TResult}.CacheFingerprint"/> it
|
||||
/// carries no file paths or module ids, which legitimately differ between the host and a self-contained worker
|
||||
/// published beside it.
|
||||
/// </summary>
|
||||
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<string> ReferenceIdentitiesCore(Type contextType)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(contextType);
|
||||
var pinned = new[] { typeof(DataValueSnapshot).Assembly, typeof(ScriptContext).Assembly, typeof(Serilog.ILogger).Assembly, contextType.Assembly }
|
||||
|
||||
@@ -58,7 +58,9 @@ public sealed class FleetDiagnosticsClient : IFleetDiagnosticsClient
|
||||
{
|
||||
// Inside the try: a malformed node value makes ActorSelection throw, and that must degrade to
|
||||
// "unavailable" like a dead node does, not surface through the page's error boundary.
|
||||
var selection = _system.ActorSelection($"akka.tcp://{_systemName}@{nodeId.Value}/user/driver-host");
|
||||
// lmxopcua#1003: the scheme follows this node's own transport (akka.ssl.tcp under Cluster:Remoting:Tls).
|
||||
var scheme = _system is ExtendedActorSystem ext ? ext.Provider.DefaultAddress.Protocol : "akka.tcp";
|
||||
var selection = _system.ActorSelection($"{scheme}://{_systemName}@{nodeId.Value}/user/driver-host");
|
||||
using var linked = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
||||
linked.CancelAfter(AskTimeout);
|
||||
return await selection.Ask<NodeDiagnosticsSnapshot>(
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// 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; }
|
||||
|
||||
/// <summary>
|
||||
/// 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 (<see cref="PeCache.Rejected"/>)
|
||||
/// and the source compiled; the host evicts the entry.
|
||||
/// </summary>
|
||||
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<VirtualTagContext, object?>(source, cache, out how), null),
|
||||
[.. source.InputPaths], Load<VirtualTagContext, object?>(source, out how), null),
|
||||
ContextKind.AlarmPredicate => new LoadedScript(
|
||||
[.. source.InputPaths], null, Load<AlarmPredicateContext, bool>(source, cache, out how)),
|
||||
[.. source.InputPaths], null, Load<AlarmPredicateContext, bool>(source, out how)),
|
||||
_ => throw new ScriptWorkerProtocolException($"unknown script kind {source.Kind}"),
|
||||
};
|
||||
|
||||
private static ScriptEvaluator<TContext, TResult> Load<TContext, TResult>(ScriptSource source, ScriptPeCacheStore? cache,
|
||||
out PeCache how) where TContext : ScriptContext
|
||||
private static ScriptEvaluator<TContext, TResult> Load<TContext, TResult>(ScriptSource source, out PeCache how)
|
||||
where TContext : ScriptContext
|
||||
{
|
||||
if (cache is null)
|
||||
{
|
||||
how = PeCache.None;
|
||||
return ScriptEvaluator<TContext, TResult>.Compile(source.Source);
|
||||
}
|
||||
|
||||
var id = ScriptPeCacheStore.EntryId(ScriptEvaluator<TContext, TResult>.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<TContext, TResult>.FromImage(source.PeImage.ToByteArray());
|
||||
how = PeCache.Hit;
|
||||
return ScriptEvaluator<TContext, TResult>.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<TContext, TResult>.Compile(source.Source);
|
||||
}
|
||||
}
|
||||
|
||||
var compiled = ScriptEvaluator<TContext, TResult>.CompileToImage(source.Source);
|
||||
cache.TryWrite(id, compiled);
|
||||
how = lookup == PeCacheLookup.Rejected ? PeCache.Rejected : PeCache.Miss;
|
||||
return ScriptEvaluator<TContext, TResult>.FromImage(compiled);
|
||||
how = PeCache.None;
|
||||
return ScriptEvaluator<TContext, TResult>.Compile(source.Source);
|
||||
}
|
||||
|
||||
public object? Run(IReadOnlyDictionary<string, DataValueSnapshot> inputs, ILogger logger, Func<DateTime> clock,
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
using System.Security.Cryptography;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using Akka.Actor;
|
||||
using Akka.Cluster;
|
||||
using Akka.Cluster.Hosting;
|
||||
using Akka.Cluster.Tools.PublishSubscribe;
|
||||
using Akka.Hosting;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Cluster.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1003 on real clusters built through the shipped <see cref="ServiceCollectionExtensions.WithOtOpcUaClusterBootstrap"/>:
|
||||
/// untrusted-mode (default on) leaves every cross-node mechanism this code base uses working — membership, a cluster
|
||||
/// singleton reached through its proxy and handed over on leave, DistributedPubSub, the diagnostics selection — with
|
||||
/// ZERO drops, while it does drop a selection to any other path (negative control, and its falsifiability control with
|
||||
/// the mode off). Mutual TLS (opt-in) forms a mesh between pinned peers and keeps an unpinned node out.
|
||||
/// </summary>
|
||||
public sealed class RemotingHardeningClusterTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
private static readonly TimeSpan FormTimeout = TimeSpan.FromSeconds(45);
|
||||
|
||||
private static int FreePort()
|
||||
{
|
||||
var listener = new TcpListener(IPAddress.Loopback, 0);
|
||||
listener.Start();
|
||||
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
|
||||
listener.Stop();
|
||||
return port;
|
||||
}
|
||||
|
||||
private sealed class EchoKey;
|
||||
|
||||
/// <summary>Answers any string with the address of the node it runs on.</summary>
|
||||
private sealed class Echo : ReceiveActor
|
||||
{
|
||||
public Echo()
|
||||
{
|
||||
var self = Akka.Cluster.Cluster.Get(Context.System).SelfAddress.ToString();
|
||||
Receive<string>(_ => Sender.Tell(self));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forwards whatever it receives to a TaskCompletionSource.</summary>
|
||||
private sealed class Sink : ReceiveActor
|
||||
{
|
||||
public Sink(TaskCompletionSource<object> got)
|
||||
{
|
||||
Receive<SubscribeAck>(_ => { });
|
||||
ReceiveAny(m => got.TrySetResult(m));
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task<IHost> StartAsync(string system, int port, string[] seeds, AkkaRemotingOptions? remoting = null,
|
||||
bool singleton = false)
|
||||
{
|
||||
var options = new AkkaClusterOptions
|
||||
{
|
||||
SystemName = system,
|
||||
Hostname = "127.0.0.1",
|
||||
PublicHostname = "127.0.0.1",
|
||||
Port = port,
|
||||
Roles = ["admin", "driver"],
|
||||
SeedNodes = seeds,
|
||||
Remoting = remoting ?? new AkkaRemotingOptions(),
|
||||
};
|
||||
var builder = Host.CreateDefaultBuilder();
|
||||
builder.ConfigureServices(services =>
|
||||
{
|
||||
services.AddSingleton<IOptions<AkkaClusterOptions>>(Options.Create(options));
|
||||
services.AddAkka(system, (ab, sp) =>
|
||||
{
|
||||
ab.WithOtOpcUaClusterBootstrap(sp);
|
||||
// The diagnostics target, as Runtime spawns it on every driver node.
|
||||
ab.WithActors((sys, _) => sys.ActorOf(Props.Create(() => new Echo()), "driver-host"));
|
||||
ab.WithActors((sys, _) => sys.ActorOf(Props.Create(() => new Echo()), "not-trusted"));
|
||||
if (singleton)
|
||||
ab.WithSingleton<EchoKey>("config-publish", Props.Create(() => new Echo()), new ClusterSingletonOptions());
|
||||
});
|
||||
});
|
||||
var host = builder.Build();
|
||||
await host.StartAsync();
|
||||
return host;
|
||||
}
|
||||
|
||||
private static ActorSystem Sys(IHost host) => host.Services.GetRequiredService<ActorSystem>();
|
||||
|
||||
private static async Task<bool> WaitUpAsync(IHost host, int expected, TimeSpan timeout)
|
||||
{
|
||||
var cluster = Akka.Cluster.Cluster.Get(Sys(host));
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
if (cluster.State.Members.Count(m => m.Status == MemberStatus.Up) >= expected) return true;
|
||||
await Task.Delay(200);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static async Task<string> AskUntilAsync(IActorRef target, Func<string, bool> accept, TimeSpan timeout)
|
||||
{
|
||||
var deadline = DateTime.UtcNow + timeout;
|
||||
string last = "(no answer)";
|
||||
while (DateTime.UtcNow < deadline)
|
||||
{
|
||||
try
|
||||
{
|
||||
last = await target.Ask<string>("ping", TimeSpan.FromSeconds(3));
|
||||
if (accept(last)) return last;
|
||||
}
|
||||
catch (AskTimeoutException)
|
||||
{
|
||||
}
|
||||
await Task.Delay(250);
|
||||
}
|
||||
throw new TimeoutException($"no accepted answer within {timeout}; last: {last}");
|
||||
}
|
||||
|
||||
private static async Task StopAsync(IHost host)
|
||||
{
|
||||
try { await host.StopAsync(); } catch (Exception) { /* teardown */ }
|
||||
host.Dispose();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The coverage proof: with untrusted-mode ON (the default) a pair forms, the singleton proxy on the younger node
|
||||
/// reaches the singleton on the oldest (Identify by selection), DistributedPubSub delivers across nodes (mediator
|
||||
/// gossip by selection), the oldest leaving hands the singleton over (manager-to-manager selections) — and neither
|
||||
/// node records a single untrusted-mode drop.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_pair_with_untrusted_mode_on_forms_and_its_singleton_and_pubsub_work_with_no_drops()
|
||||
{
|
||||
const string name = "otopcua-untrusted-1";
|
||||
int pa = FreePort(), pb = FreePort();
|
||||
string a = $"akka.tcp://{name}@127.0.0.1:{pa}", b = $"akka.tcp://{name}@127.0.0.1:{pb}";
|
||||
var hostA = await StartAsync(name, pa, [a, b], singleton: true);
|
||||
IHost? hostB = null;
|
||||
try
|
||||
{
|
||||
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue("A forms alone");
|
||||
hostB = await StartAsync(name, pb, [b, a], singleton: true);
|
||||
(await WaitUpAsync(hostB, 2, FormTimeout)).ShouldBeTrue("B joins A with untrusted-mode on");
|
||||
(await WaitUpAsync(hostA, 2, FormTimeout)).ShouldBeTrue();
|
||||
|
||||
Sys(hostA).Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue("the effective config, off the running system");
|
||||
|
||||
// Singleton on the oldest (A), reached from B through its proxy.
|
||||
var proxyB = hostB.Services.GetRequiredService<ActorRegistry>().Get<EchoKey>();
|
||||
(await AskUntilAsync(proxyB, s => s.EndsWith($":{pa}"), FormTimeout)).ShouldEndWith($":{pa}");
|
||||
|
||||
// DistributedPubSub across the pair.
|
||||
var got = new TaskCompletionSource<object>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var sink = Sys(hostA).ActorOf(Props.Create(() => new Sink(got)));
|
||||
DistributedPubSub.Get(Sys(hostA)).Mediator.Tell(new Subscribe("remoting-hardening", sink));
|
||||
var mediatorB = DistributedPubSub.Get(Sys(hostB)).Mediator;
|
||||
var deadline = DateTime.UtcNow + FormTimeout;
|
||||
while (!got.Task.IsCompleted && DateTime.UtcNow < deadline)
|
||||
{
|
||||
mediatorB.Tell(new Publish("remoting-hardening", "hello"));
|
||||
await Task.WhenAny(got.Task, Task.Delay(500, Ct));
|
||||
}
|
||||
got.Task.IsCompleted.ShouldBeTrue("a publish on B reaches a subscriber on A");
|
||||
|
||||
var dropsA = RemotingHardening.DroppedFor(Sys(hostA));
|
||||
dropsA.ShouldBeEmpty($"A dropped: {string.Join(", ", dropsA)}");
|
||||
|
||||
// Graceful leave of the oldest: the singleton is handed over to B.
|
||||
await StopAsync(hostA);
|
||||
(await AskUntilAsync(proxyB, s => s.EndsWith($":{pb}"), TimeSpan.FromSeconds(60))).ShouldEndWith($":{pb}");
|
||||
|
||||
var dropsB = RemotingHardening.DroppedFor(Sys(hostB));
|
||||
dropsB.ShouldBeEmpty($"B dropped: {string.Join(", ", dropsB)}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await StopAsync(hostA);
|
||||
if (hostB is not null) await StopAsync(hostB);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Negative control: a selection to a path that is NOT trusted is dropped, recorded and never answered — while the
|
||||
/// diagnostics path (<c>/user/driver-host</c>, which the AdminUI queries across meshes) is answered on the same node.
|
||||
/// Two separate one-node clusters, as central and a site are since the mesh split.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_selection_to_an_untrusted_path_is_dropped_but_the_diagnostics_path_is_answered()
|
||||
{
|
||||
int pa = FreePort(), pb = FreePort();
|
||||
const string name = "otopcua-untrusted-2";
|
||||
var hostA = await StartAsync(name, pa, [$"akka.tcp://{name}@127.0.0.1:{pa}"]);
|
||||
var hostB = await StartAsync(name, pb, [$"akka.tcp://{name}@127.0.0.1:{pb}"]);
|
||||
try
|
||||
{
|
||||
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue();
|
||||
(await WaitUpAsync(hostB, 1, FormTimeout)).ShouldBeTrue();
|
||||
var fromB = Sys(hostB);
|
||||
|
||||
var diag = await fromB.ActorSelection($"akka.tcp://{name}@127.0.0.1:{pa}/user/driver-host")
|
||||
.Ask<ActorIdentity>(new Identify(1), TimeSpan.FromSeconds(10), Ct);
|
||||
diag.Subject.ShouldNotBeNull("positive control: the trusted diagnostics path is delivered");
|
||||
|
||||
await Should.ThrowAsync<AskTimeoutException>(() => fromB
|
||||
.ActorSelection($"akka.tcp://{name}@127.0.0.1:{pa}/user/not-trusted")
|
||||
.Ask<ActorIdentity>(new Identify(2), TimeSpan.FromSeconds(3)));
|
||||
await Task.Delay(500, Ct);
|
||||
RemotingHardening.DroppedFor(Sys(hostA)).ShouldContain("/user/not-trusted");
|
||||
}
|
||||
finally
|
||||
{
|
||||
await StopAsync(hostA);
|
||||
await StopAsync(hostB);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Falsifiability control for the test above: with untrusted-mode OFF the same selection IS delivered.</summary>
|
||||
[Fact]
|
||||
public async Task With_untrusted_mode_off_the_same_selection_is_delivered()
|
||||
{
|
||||
int pa = FreePort(), pb = FreePort();
|
||||
const string name = "otopcua-untrusted-3";
|
||||
var off = new AkkaRemotingOptions { UntrustedMode = false };
|
||||
var hostA = await StartAsync(name, pa, [$"akka.tcp://{name}@127.0.0.1:{pa}"], off);
|
||||
var hostB = await StartAsync(name, pb, [$"akka.tcp://{name}@127.0.0.1:{pb}"], off);
|
||||
try
|
||||
{
|
||||
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue();
|
||||
Sys(hostA).Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeFalse();
|
||||
var identity = await Sys(hostB).ActorSelection($"akka.tcp://{name}@127.0.0.1:{pa}/user/not-trusted")
|
||||
.Ask<ActorIdentity>(new Identify(3), TimeSpan.FromSeconds(10), Ct);
|
||||
identity.Subject.ShouldNotBeNull();
|
||||
}
|
||||
finally
|
||||
{
|
||||
await StopAsync(hostA);
|
||||
await StopAsync(hostB);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Opt-in mutual TLS: two nodes whose certificates pin each other form a mesh on <c>akka.ssl.tcp</c> (from seeds
|
||||
/// still spelled <c>akka.tcp</c> — the scheme is normalised); a third node with a certificate neither pins cannot join,
|
||||
/// although it would accept them. Positive control for the third node: the same config with its certificate pinned
|
||||
/// joins.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Mutual_tls_forms_a_mesh_between_pinned_peers_and_keeps_an_unpinned_node_out()
|
||||
{
|
||||
using var dir = new TempDir();
|
||||
var (pathA, thumbA) = MakeCert(dir.Path, "node-a");
|
||||
var (pathB, thumbB) = MakeCert(dir.Path, "node-b");
|
||||
var (pathC, thumbC) = MakeCert(dir.Path, "node-c");
|
||||
AkkaRemotingOptions Tls(string path, params string[] pins) => new()
|
||||
{
|
||||
Tls = new AkkaRemotingTlsOptions
|
||||
{
|
||||
Enabled = true, CertificatePath = path, CertificatePassword = "test-only", AllowedThumbprints = pins,
|
||||
},
|
||||
};
|
||||
|
||||
const string name = "otopcua-tls-1";
|
||||
int pa = FreePort(), pb = FreePort(), pc = FreePort();
|
||||
string a = $"akka.tcp://{name}@127.0.0.1:{pa}", b = $"akka.tcp://{name}@127.0.0.1:{pb}";
|
||||
var hostA = await StartAsync(name, pa, [a, b], Tls(pathA, thumbA, thumbB));
|
||||
IHost? hostB = null, hostC = null;
|
||||
try
|
||||
{
|
||||
(await WaitUpAsync(hostA, 1, FormTimeout)).ShouldBeTrue();
|
||||
Akka.Cluster.Cluster.Get(Sys(hostA)).SelfAddress.Protocol.ShouldBe("akka.ssl.tcp");
|
||||
hostB = await StartAsync(name, pb, [b, a], Tls(pathB, thumbA, thumbB));
|
||||
(await WaitUpAsync(hostA, 2, FormTimeout)).ShouldBeTrue("pinned peers form a mesh over mutual TLS");
|
||||
|
||||
hostC = await StartAsync(name, pc, [a], Tls(pathC, thumbA, thumbB, thumbC));
|
||||
(await WaitUpAsync(hostC, 1, TimeSpan.FromSeconds(15))).ShouldBeFalse("A refuses C's unpinned certificate");
|
||||
Akka.Cluster.Cluster.Get(Sys(hostA)).State.Members.Count.ShouldBe(2);
|
||||
await StopAsync(hostC);
|
||||
|
||||
hostC = await StartAsync(name, FreePort(), [a], Tls(pathA, thumbA, thumbB));
|
||||
(await WaitUpAsync(hostC, 3, FormTimeout)).ShouldBeTrue("positive control: a pinned certificate joins");
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (hostC is not null) await StopAsync(hostC);
|
||||
if (hostB is not null) await StopAsync(hostB);
|
||||
await StopAsync(hostA);
|
||||
}
|
||||
}
|
||||
|
||||
private static (string Path, string Thumbprint) MakeCert(string dir, string cn)
|
||||
{
|
||||
using var rsa = RSA.Create(2048);
|
||||
var request = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
|
||||
var san = new SubjectAlternativeNameBuilder();
|
||||
san.AddDnsName("localhost");
|
||||
san.AddIpAddress(IPAddress.Loopback);
|
||||
request.CertificateExtensions.Add(san.Build());
|
||||
request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(
|
||||
[new Oid("1.3.6.1.5.5.7.3.1"), new Oid("1.3.6.1.5.5.7.3.2")], critical: false));
|
||||
request.CertificateExtensions.Add(new X509KeyUsageExtension(
|
||||
X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, critical: false));
|
||||
using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(7));
|
||||
var path = System.IO.Path.Combine(dir, cn + ".pfx");
|
||||
File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx, "test-only"));
|
||||
return (path, cert.Thumbprint);
|
||||
}
|
||||
|
||||
private sealed class TempDir : IDisposable
|
||||
{
|
||||
public string Path { get; } = Directory.CreateTempSubdirectory("otopcua-remoting-").FullName;
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
try { Directory.Delete(Path, recursive: true); } catch { /* best effort */ }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Cluster.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1003 (review 2026-12-02 A-1 follow-up): the remoting hardening's pure parts — the untrusted-mode HOCON and
|
||||
/// its trusted path set, seed scheme normalisation, option validation, and the drop classifier. The behaviour on real
|
||||
/// clusters is <see cref="RemotingHardeningClusterTests"/>.
|
||||
/// </summary>
|
||||
public sealed class RemotingHardeningTests
|
||||
{
|
||||
[Fact]
|
||||
public void Untrusted_mode_is_on_by_default()
|
||||
=> new AkkaClusterOptions().Remoting.UntrustedMode.ShouldBeTrue();
|
||||
|
||||
[Fact]
|
||||
public void Tls_is_off_by_default_and_mutual_when_on()
|
||||
{
|
||||
var tls = new AkkaClusterOptions().Remoting.Tls;
|
||||
tls.Enabled.ShouldBeFalse("TLS is opt-in: an existing fleet's mesh must keep talking after an upgrade");
|
||||
tls.RequireMutualAuthentication.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>Every path the code base reaches by selection across nodes is trusted (see the remarks on <see cref="RemotingHardening"/>).</summary>
|
||||
[Fact]
|
||||
public void The_trusted_set_covers_cluster_remote_watch_pubsub_every_singleton_and_the_driver_host()
|
||||
{
|
||||
var paths = RemotingHardening.TrustedSelectionPaths;
|
||||
paths.ShouldContain("/system/cluster/core/daemon");
|
||||
paths.ShouldContain("/system/cluster/heartbeatReceiver");
|
||||
paths.ShouldContain("/system/remote-watcher");
|
||||
paths.ShouldContain("/system/distributedPubSubMediator");
|
||||
paths.ShouldContain("/user/driver-host");
|
||||
foreach (var name in RemotingHardening.SingletonNames)
|
||||
{
|
||||
paths.ShouldContain($"/user/{name}", "the manager: hand-over between managers");
|
||||
paths.ShouldContain($"/user/{name}/{name}", "the singleton: the proxies' Identify");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_hocon_turns_untrusted_mode_on_with_the_trusted_paths_and_any_additional_ones()
|
||||
{
|
||||
var hocon = RemotingHardening.BuildUntrustedModeHocon(new AkkaRemotingOptions
|
||||
{
|
||||
AdditionalTrustedSelectionPaths = ["/user/extra", " ", "/user/extra"],
|
||||
});
|
||||
var config = Akka.Configuration.ConfigurationFactory.ParseString(hocon);
|
||||
config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue();
|
||||
var trusted = config.GetStringList("akka.remote.trusted-selection-paths");
|
||||
trusted.ShouldBe(RemotingHardening.TrustedSelectionPaths.Append("/user/extra"), ignoreOrder: true);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Disabled_untrusted_mode_is_written_off_explicitly()
|
||||
{
|
||||
var config = Akka.Configuration.ConfigurationFactory.ParseString(
|
||||
RemotingHardening.BuildUntrustedModeHocon(new AkkaRemotingOptions { UntrustedMode = false }));
|
||||
config.GetBoolean("akka.remote.untrusted-mode").ShouldBeFalse();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("akka.tcp://otopcua@node-a:4053", false, "akka.tcp://otopcua@node-a:4053")]
|
||||
[InlineData("akka.tcp://otopcua@node-a:4053", true, "akka.ssl.tcp://otopcua@node-a:4053")]
|
||||
[InlineData("akka.ssl.tcp://otopcua@node-a:4053", false, "akka.tcp://otopcua@node-a:4053")]
|
||||
[InlineData("AKKA.SSL.TCP://otopcua@node-a:4053", true, "akka.ssl.tcp://otopcua@node-a:4053")]
|
||||
[InlineData("akka://otopcua", true, "akka://otopcua")]
|
||||
public void A_seed_takes_the_transport_scheme(string seed, bool tls, string expected)
|
||||
=> RemotingHardening.NormalizeSeed(seed, new AkkaRemotingTlsOptions { Enabled = tls }).ShouldBe(expected);
|
||||
|
||||
[Fact]
|
||||
public void BuildClusterOptions_rewrites_seeds_to_the_tls_scheme()
|
||||
{
|
||||
var options = new AkkaClusterOptions
|
||||
{
|
||||
SeedNodes = ["akka.tcp://otopcua@a:4053", "akka.tcp://otopcua@b:4053"],
|
||||
Remoting = new AkkaRemotingOptions { Tls = new AkkaRemotingTlsOptions { Enabled = true } },
|
||||
};
|
||||
ServiceCollectionExtensions.BuildClusterOptions(options).SeedNodes
|
||||
.ShouldBe(["akka.ssl.tcp://otopcua@a:4053", "akka.ssl.tcp://otopcua@b:4053"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_bootstrap_guard_parses_a_tls_seed()
|
||||
{
|
||||
ClusterBootstrapGuard.TryParse("akka.ssl.tcp://otopcua@node-b:4054", out var host, out var port).ShouldBeTrue();
|
||||
host.ShouldBe("node-b");
|
||||
port.ShouldBe(4054);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Default_options_validate()
|
||||
=> RemotingHardening.Validate(new AkkaRemotingOptions()).ShouldBeEmpty();
|
||||
|
||||
[Theory]
|
||||
[InlineData("user/no-leading-slash")]
|
||||
[InlineData("akka.tcp://otopcua@x:1/user/a")]
|
||||
[InlineData("/other/a")]
|
||||
[InlineData("")]
|
||||
public void A_malformed_additional_path_is_refused(string path)
|
||||
=> RemotingHardening.Validate(new AkkaRemotingOptions { AdditionalTrustedSelectionPaths = [path] })
|
||||
.ShouldHaveSingleItem().ShouldContain("AdditionalTrustedSelectionPaths");
|
||||
|
||||
[Fact]
|
||||
public void Tls_needs_exactly_one_certificate_source()
|
||||
{
|
||||
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions { Enabled = true }))
|
||||
.ShouldContain(m => m.Contains("exactly one of CertificatePath"));
|
||||
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions
|
||||
{
|
||||
Enabled = true, CertificatePath = "/x.pfx", CertificateThumbprint = new string('A', 40),
|
||||
}))
|
||||
.ShouldContain(m => m.Contains("exactly one of CertificatePath"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tls_refuses_a_relative_or_missing_certificate_file_and_bad_thumbprints()
|
||||
{
|
||||
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions { Enabled = true, CertificatePath = "node.pfx" }))
|
||||
.ShouldContain(m => m.Contains("absolute"));
|
||||
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions
|
||||
{
|
||||
Enabled = true, CertificatePath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N") + ".pfx"),
|
||||
}))
|
||||
.ShouldContain(m => m.Contains("does not exist"));
|
||||
RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions
|
||||
{
|
||||
Enabled = true, CertificateThumbprint = "nope", AllowedThumbprints = ["12:34"],
|
||||
}))
|
||||
.Count().ShouldBe(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Tls_options_are_not_validated_while_tls_is_off()
|
||||
=> RemotingHardening.Validate(Tls(new AkkaRemotingTlsOptions { Enabled = false, CertificatePath = "relative" }))
|
||||
.ShouldBeEmpty();
|
||||
|
||||
[Fact]
|
||||
public void The_cluster_options_validator_reports_remoting_problems()
|
||||
{
|
||||
var validator = new AkkaClusterOptionsValidator();
|
||||
var result = validator.Validate(null, new AkkaClusterOptions
|
||||
{
|
||||
Remoting = new AkkaRemotingOptions { Tls = new AkkaRemotingTlsOptions { Enabled = true } },
|
||||
});
|
||||
result.Failed.ShouldBeTrue();
|
||||
result.FailureMessage.ShouldContain("Cluster:Remoting:Tls");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("operating in UntrustedMode, dropping inbound actor selection to [/user/x/y], allow itby adding the path", "/user/x/y")]
|
||||
[InlineData("operating in UntrustedMode, dropping inbound IPossiblyHarmful message of type Akka.Actor.PoisonPill", "IPossiblyHarmful Akka.Actor.PoisonPill")]
|
||||
[InlineData("dropping daemon message in untrusted mode", "remote daemon (remote deployment)")]
|
||||
public void A_drop_message_is_recognised(string message, string expected)
|
||||
{
|
||||
RemotingHardening.TryParseDrop(message, out var what).ShouldBeTrue();
|
||||
what.ShouldBe(expected);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void An_ordinary_debug_message_is_not_a_drop()
|
||||
=> RemotingHardening.TryParseDrop("Cluster Node [x] - Received InitJoin message", out _).ShouldBeFalse();
|
||||
|
||||
private static AkkaRemotingOptions Tls(AkkaRemotingTlsOptions tls) => new() { Tls = tls };
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Cluster;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1003: Akka untrusted-mode is ON by default. On the full two-node harness — the shipped bootstrap with every
|
||||
/// ControlPlane singleton and proxy, the cluster-scoped redundancy singleton, the runtime actors and DistributedPubSub —
|
||||
/// a deployment through the AdminOperations proxy, the diagnostics selection to each node's driver host, and node B
|
||||
/// leaving and rejoining (singleton proxies re-identifying) leave NO untrusted-mode drop on either node.
|
||||
/// </summary>
|
||||
public sealed class UntrustedModeHarnessTests
|
||||
{
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
[Fact]
|
||||
public async Task The_full_two_node_stack_runs_under_untrusted_mode_without_a_single_dropped_message()
|
||||
{
|
||||
await using var harness = await TwoNodeClusterHarness.StartAsync();
|
||||
harness.NodeASystem.Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue("the default, effective");
|
||||
harness.NodeBSystem.Settings.Config.GetBoolean("akka.remote.untrusted-mode").ShouldBeTrue();
|
||||
await harness.SeedDefaultClusterAsync();
|
||||
|
||||
// Deploy from EACH node: one of them reaches the singletons through a cross-node proxy.
|
||||
foreach (var node in new[] { harness.NodeA, harness.NodeB })
|
||||
{
|
||||
await using var scope = node.Services.CreateAsyncScope();
|
||||
var adminOps = scope.ServiceProvider.GetRequiredService<IAdminOperationsClient>();
|
||||
var deploy = await adminOps.StartDeploymentAsync(createdBy: "alice@test", Ct);
|
||||
deploy.Outcome.ShouldBeOneOf(StartDeploymentOutcome.Accepted, StartDeploymentOutcome.NoChanges,
|
||||
StartDeploymentOutcome.AnotherDeploymentInFlight); // any of these is the singleton answering
|
||||
}
|
||||
|
||||
// The diagnostics selection (/user/driver-host) to both nodes, from node A.
|
||||
await using (var scope = harness.NodeA.Services.CreateAsyncScope())
|
||||
{
|
||||
var diagnostics = scope.ServiceProvider.GetRequiredService<IFleetDiagnosticsClient>();
|
||||
foreach (var member in Akka.Cluster.Cluster.Get(harness.NodeASystem).State.Members)
|
||||
{
|
||||
var nodeId = Commons.Types.NodeId.Parse($"{member.Address.Host}:{member.Address.Port}");
|
||||
(await diagnostics.GetDiagnosticsAsync(nodeId, Ct)).NodeId.ShouldBe(nodeId, "answered, not the empty fallback");
|
||||
}
|
||||
}
|
||||
|
||||
// Node B leaves and rejoins: hand-over / re-identification on the remaining managers and proxies.
|
||||
await harness.RestartNodeBAsync();
|
||||
await using (var scope = harness.NodeB.Services.CreateAsyncScope())
|
||||
{
|
||||
var adminOps = scope.ServiceProvider.GetRequiredService<IAdminOperationsClient>();
|
||||
var deploy = await adminOps.StartDeploymentAsync(createdBy: "alice@test", Ct);
|
||||
deploy.Outcome.ShouldBeOneOf(StartDeploymentOutcome.Accepted, StartDeploymentOutcome.NoChanges,
|
||||
StartDeploymentOutcome.AnotherDeploymentInFlight); // any of these is the singleton answering
|
||||
}
|
||||
|
||||
var drops = RemotingHardening.DroppedFor(harness.NodeASystem).Concat(RemotingHardening.DroppedFor(harness.NodeBSystem)).ToArray();
|
||||
drops.ShouldBeEmpty($"untrusted-mode dropped: {string.Join(", ", drops)}");
|
||||
|
||||
// Positive control — the empty list above is not vacuous: the drop monitor runs on this stack and records a
|
||||
// selection to a path that is not trusted.
|
||||
var addressA = Akka.Cluster.Cluster.Get(harness.NodeASystem).SelfAddress;
|
||||
harness.NodeBSystem.ActorSelection($"{addressA}/user/not-a-trusted-path").Tell(new Akka.Actor.Identify(1));
|
||||
var deadline = DateTime.UtcNow + TimeSpan.FromSeconds(10);
|
||||
while (!RemotingHardening.DroppedFor(harness.NodeASystem).Contains("/user/not-a-trusted-path") && DateTime.UtcNow < deadline)
|
||||
await Task.Delay(100, Ct);
|
||||
RemotingHardening.DroppedFor(harness.NodeASystem).ShouldContain("/user/not-a-trusted-path");
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
using System.Reflection;
|
||||
using System.Text.RegularExpressions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Cluster;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Host.Tests.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1003: Akka untrusted-mode is ON by default, so a cross-node <c>ActorSelection</c> to a path missing from
|
||||
/// <see cref="RemotingHardening.TrustedSelectionPaths"/> is dropped. These guards keep the trusted set in step with the
|
||||
/// code: every cluster singleton the ControlPlane registers, the driver host actor's name, and the one application-level
|
||||
/// selection in <c>src/</c>.
|
||||
/// </summary>
|
||||
public sealed class RemotingTrustedPathsCoverageTests
|
||||
{
|
||||
[Fact]
|
||||
public void Every_registered_cluster_singleton_is_trusted()
|
||||
{
|
||||
var names = typeof(ZB.MOM.WW.OtOpcUa.ControlPlane.ServiceCollectionExtensions)
|
||||
.GetFields(BindingFlags.Public | BindingFlags.Static)
|
||||
.Where(f => f.IsLiteral && f.Name.EndsWith("SingletonName", StringComparison.Ordinal))
|
||||
.Select(f => (string)f.GetRawConstantValue()!)
|
||||
.ToArray();
|
||||
names.ShouldNotBeEmpty("positive control: the constants are found");
|
||||
foreach (var name in names)
|
||||
{
|
||||
RemotingHardening.SingletonNames.ShouldContain(name,
|
||||
$"singleton '{name}' must be added to RemotingHardening.SingletonNames or its proxy/hand-over selections are dropped");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void The_driver_host_path_is_the_runtime_actor_name()
|
||||
=> RemotingHardening.DriverHostPath.ShouldBe("/user/" + ZB.MOM.WW.OtOpcUa.Runtime.ServiceCollectionExtensions.DriverHostActorName);
|
||||
|
||||
/// <summary>
|
||||
/// The only <c>ActorSelection</c> in <c>src/</c> is the diagnostics client (which targets <c>/user/driver-host</c>).
|
||||
/// A new one must come with its path in the trusted set — then add its file here.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void No_new_cross_node_actor_selection_appears_without_a_trusted_path()
|
||||
{
|
||||
var allowed = new HashSet<string>(StringComparer.Ordinal) { "FleetDiagnosticsClient.cs" };
|
||||
var call = new Regex(@"\.ActorSelection\s*\(", RegexOptions.Compiled);
|
||||
var offenders = Directory.EnumerateFiles(Path.Combine(SolutionRoot(), "src"), "*.cs", SearchOption.AllDirectories)
|
||||
.Where(f => !f.Contains($"{Path.DirectorySeparatorChar}obj{Path.DirectorySeparatorChar}", StringComparison.Ordinal))
|
||||
.Where(f => File.ReadLines(f).Any(l => !l.TrimStart().StartsWith("//", StringComparison.Ordinal) && call.IsMatch(l)))
|
||||
.Select(Path.GetFileName)
|
||||
.Where(n => !allowed.Contains(n!))
|
||||
.ToArray();
|
||||
offenders.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
private static string SolutionRoot()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir is not null && !File.Exists(Path.Combine(dir.FullName, "ZB.MOM.WW.OtOpcUa.slnx")))
|
||||
dir = dir.Parent;
|
||||
dir.ShouldNotBeNull("Could not find solution root (ZB.MOM.WW.OtOpcUa.slnx).");
|
||||
return dir!.FullName;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public sealed class PeCacheStoreTests
|
||||
{
|
||||
@@ -77,6 +80,32 @@ public sealed class PeCacheStoreTests
|
||||
File.Exists(path).ShouldBeFalse("a rejected entry is evicted");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -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<VirtualTagContext, object?>.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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#1014 (review K-1 option 4): the worker is never handed the cache's HMAC key. Before, <c>Hello</c> 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.
|
||||
/// </summary>
|
||||
[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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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<VirtualTagContext, object?>.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");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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();
|
||||
}
|
||||
|
||||
/// <summary>A compile error is never cached (the host's negative cache covers it) and does not poison the directory.</summary>
|
||||
[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();
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user