Files
lmxopcua/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.OutOfProcess/HostPeCache.cs
T
Joseph Doherty bed9620e31 fix(scripting): #1014 host owns the compiled-PE cache; the worker never holds the HMAC key
Review 2026-12-02 K-1 option 4 (#971 follow-up). The ScriptWorker used to read, verify and
WRITE the PE cache with the key it received 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.

- Hello no longer carries pe_cache_dir / pe_cache_key (fields reserved).
- HostPeCache: the host verifies an entry under its host-only key and ships the image in
  ScriptSource.pe_image; on a miss the worker compiles as before and, only after that compile
  succeeded, the host queues its OWN compile (one background thread, de-duplicated) and writes
  the signed entry. The worker loads a supplied image or compiles; it never opens the directory.
- Images go only to a worker whose Ready.pe_image_abi equals ScriptSandbox.ImageAbi (runtime +
  pinned assembly names); pre-#1014 workers report none and just compile.
- Entry format v2: every worker-written (possibly forged) v1 entry is rejected and refilled.
- Scripting:Worker:PeCacheDir and the directory layout are unchanged.
2026-12-03 15:12:17 -05:00

218 lines
10 KiB
C#

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);
}