feat(deploy): #971 follow-up deploy-time script compile gate
The deploy gate never compiled scripts, so a stored script the #971 allow-list now refuses only failed after the deploy (VirtualTag/Calculation Bad "sandbox violation", scripted-alarm load failing for every alarm on the node). - Core.Scripting.Abstractions: IDeployScriptChecker (Roslyn-free) + request/result records; ScriptContextKind moved here (same namespace). - Core.Scripting: ScriptEvaluator.Verify shares a private BuildCheckedCompilation factory with CompileToImage (wrap, injection guard, sandbox compile, ForbiddenTypeAnalyzer; no stack-guard rewrite, no emit). RoslynDeployScriptChecker checks per seam (VT/Calc as VirtualTagContext->object?, passthrough/blank skipped; predicates DependencyExtractor first then AlarmPredicateContext->bool), caches by (compile identity, SHA-256), parallel, bounded. - ControlPlane: DeployScriptGate collects enabled VTs / enabled alarm predicates / Calculation tags, resolves {{equip}} through EquipmentReferenceMap exactly as the compose seams do (template compiled once when SubstitutionPreservesCompilation, else the resolved source), groups findings per script naming its users. AdminOperationsActor warms the cache before the snapshot transaction and runs the authoritative pass on the same snapshot; Deployment:ScriptCompileGateMode = Error (default) | Warn | Off; an absent checker or an internal failure never blocks. - Host binds RoslynDeployScriptChecker on admin nodes. - Docs: VirtualTags.md (gate + upgrade note), ScriptEditor.md, security.md, CLAUDE.md. Found while testing: {{equip}} substitution pastes RawPaths into C# literals unescaped, so a segment containing \ or " breaks (or silently alters) the script; the gate now reports it at deploy.
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.VirtualTags;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
|
||||
|
||||
/// <summary>
|
||||
/// The Roslyn implementation of the deploy-time script compile gate (lmxopcua#971 follow-up). For each request it
|
||||
/// runs exactly what the runtime seam runs before a script can execute, minus the emit:
|
||||
/// <list type="bullet">
|
||||
/// <item><b>VirtualTag / Calculation</b> — the passthrough mirror shape (<see cref="PassthroughScript"/>) and a
|
||||
/// blank source never reach Roslyn at runtime, so they pass; anything else goes through
|
||||
/// <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> as <c>VirtualTagContext → object?</c>.</item>
|
||||
/// <item><b>AlarmPredicate</b> — <see cref="DependencyExtractor"/> first (the scripted-alarm load rejects a
|
||||
/// non-literal tag path before compiling), then <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> as
|
||||
/// <c>AlarmPredicateContext → bool</c>. No passthrough shortcut: the alarm engine always compiles.</item>
|
||||
/// </list>
|
||||
/// <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> builds its compilation through the same private factory
|
||||
/// <see cref="ScriptEvaluator{TContext, TResult}.CompileToImage"/> uses, so the gate and the runtime cannot drift.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Results are cached by (compile identity, SHA-256 of the source). VirtualTag and Calculation share one
|
||||
/// identity — they compile against the same context and result type. The allow-list and the compiler only
|
||||
/// change with the binary, so a cached verdict stays valid for the life of the process; the cache is bounded
|
||||
/// by <c>capacity</c> (cleared wholesale when full — re-checking is only a cost, never a wrong answer).
|
||||
/// Verdicts from an unexpected internal exception are not cached.
|
||||
/// </para>
|
||||
/// <para>Distinct uncached sources are checked in parallel, bounded by <c>maxParallelism</c>.</para>
|
||||
/// </remarks>
|
||||
public sealed class RoslynDeployScriptChecker : IDeployScriptChecker
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, Lazy<CachedVerdict>> _cache = new(StringComparer.Ordinal);
|
||||
private readonly int _capacity;
|
||||
private readonly int _maxParallelism;
|
||||
private long _compiles;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="RoslynDeployScriptChecker"/> class.</summary>
|
||||
/// <param name="capacity">Cached verdicts kept before the cache is cleared; default 4096.</param>
|
||||
/// <param name="maxParallelism">Concurrent checks; default half the processors, between 1 and 8.</param>
|
||||
public RoslynDeployScriptChecker(int capacity = 4096, int? maxParallelism = null)
|
||||
{
|
||||
_capacity = Math.Max(1, capacity);
|
||||
_maxParallelism = Math.Max(1, maxParallelism ?? Math.Clamp(Environment.ProcessorCount / 2, 1, 8));
|
||||
}
|
||||
|
||||
/// <summary>Gets how many sources this instance has actually run through Roslyn (cache misses).</summary>
|
||||
public long CompilesPerformed => Interlocked.Read(ref _compiles);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<DeployScriptCheckResult> Check(
|
||||
IReadOnlyList<DeployScriptCheckRequest> requests, CancellationToken cancellationToken = default)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(requests);
|
||||
var keys = new string?[requests.Count];
|
||||
var pending = new Dictionary<string, DeployScriptCheckRequest>(StringComparer.Ordinal);
|
||||
for (var i = 0; i < requests.Count; i++)
|
||||
{
|
||||
var request = requests[i] ?? throw new ArgumentException("A request is null.", nameof(requests));
|
||||
if (SkipsCompile(request)) continue;
|
||||
var key = CacheKey(request);
|
||||
keys[i] = key;
|
||||
if (!_cache.ContainsKey(key)) pending.TryAdd(key, request);
|
||||
}
|
||||
|
||||
if (pending.Count > 0)
|
||||
{
|
||||
if (_cache.Count + pending.Count > _capacity) _cache.Clear();
|
||||
Parallel.ForEach(
|
||||
pending,
|
||||
new ParallelOptions { MaxDegreeOfParallelism = _maxParallelism, CancellationToken = cancellationToken },
|
||||
kv => _ = Resolve(kv.Key, kv.Value));
|
||||
}
|
||||
|
||||
var results = new DeployScriptCheckResult[requests.Count];
|
||||
for (var i = 0; i < requests.Count; i++)
|
||||
{
|
||||
cancellationToken.ThrowIfCancellationRequested();
|
||||
results[i] = new DeployScriptCheckResult(
|
||||
requests[i], keys[i] is { } key ? Resolve(key, requests[i]).Problems : []);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
private CachedVerdict Resolve(string key, DeployScriptCheckRequest request)
|
||||
{
|
||||
var lazy = _cache.GetOrAdd(key, _ => new Lazy<CachedVerdict>(
|
||||
() => Run(request), LazyThreadSafetyMode.ExecutionAndPublication));
|
||||
var verdict = lazy.Value;
|
||||
if (!verdict.Cacheable)
|
||||
_cache.TryRemove(new KeyValuePair<string, Lazy<CachedVerdict>>(key, lazy));
|
||||
return verdict;
|
||||
}
|
||||
|
||||
/// <summary>True when the runtime seam answers the source without compiling it.</summary>
|
||||
private static bool SkipsCompile(DeployScriptCheckRequest request) =>
|
||||
request.Kind is ScriptContextKind.VirtualTag or ScriptContextKind.Calculation
|
||||
&& (string.IsNullOrWhiteSpace(request.Source) || PassthroughScript.TryMatch(request.Source, out _));
|
||||
|
||||
private static string CacheKey(DeployScriptCheckRequest request)
|
||||
{
|
||||
var identity = request.Kind == ScriptContextKind.AlarmPredicate ? "alarm" : "value";
|
||||
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(request.Source ?? string.Empty));
|
||||
return identity + ":" + Convert.ToHexString(hash);
|
||||
}
|
||||
|
||||
private CachedVerdict Run(DeployScriptCheckRequest request)
|
||||
{
|
||||
Interlocked.Increment(ref _compiles);
|
||||
var source = request.Source ?? string.Empty;
|
||||
try
|
||||
{
|
||||
if (request.Kind == ScriptContextKind.AlarmPredicate)
|
||||
{
|
||||
var extraction = DependencyExtractor.Extract(source);
|
||||
if (!extraction.IsValid)
|
||||
return new CachedVerdict(
|
||||
["dependency extraction rejected — " + string.Join("; ", extraction.Rejections.Select(r => r.Message))],
|
||||
Cacheable: true);
|
||||
ScriptEvaluator<AlarmPredicateContext, bool>.Verify(source);
|
||||
}
|
||||
else
|
||||
{
|
||||
ScriptEvaluator<VirtualTagContext, object?>.Verify(source);
|
||||
}
|
||||
return new CachedVerdict([], Cacheable: true);
|
||||
}
|
||||
catch (CompilationErrorException ex)
|
||||
{
|
||||
return new CachedVerdict(["compile error: " + OneLine(ex.Message)], Cacheable: true);
|
||||
}
|
||||
catch (ScriptSandboxViolationException ex)
|
||||
{
|
||||
return new CachedVerdict(["sandbox violation: " + OneLine(ex.Message)], Cacheable: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
return new CachedVerdict(["compile failure: " + OneLine(ex.Message)], Cacheable: false);
|
||||
}
|
||||
}
|
||||
|
||||
private static string OneLine(string text) =>
|
||||
string.Join(" ", text.Split(['\r', '\n'], StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()));
|
||||
|
||||
private sealed record CachedVerdict(IReadOnlyList<string> Problems, bool Cacheable);
|
||||
}
|
||||
Reference in New Issue
Block a user