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