diff --git a/CLAUDE.md b/CLAUDE.md index a3892dfa8..cec0eccf5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -400,6 +400,7 @@ exactly. The backend lives in endpoints under `/api/script-analysis/*`, gated by the `ConfigEditor` policy (Administrator or Designer) via `RequireAuthorization` in `ScriptAnalysisEndpoints.MapScriptAnalysisEndpoints`). +**The deploy gate compiles scripts too** (lmxopcua#971 follow-up): `AdminOperationsActor` runs every in-use script (enabled VirtualTags / scripted-alarm predicates / Calculation tags, `{{equip}}` resolved) through `IDeployScriptChecker` (Roslyn impl bound by the Host; ControlPlane stays Roslyn-free) — `Deployment:ScriptCompileGateMode` = `Error` (default, rejects `ScriptCompileFailed`) | `Warn` | `Off`. See `docs/VirtualTags.md` §"Deploy-time script compile gate". `Core.VirtualTags` is now just `DependencyGraph`, `ITagUpstreamSource` and `IHistoryWriter` — the dormant `VirtualTagEngine`/Source/Definition and `TimerTriggerScheduler` were deleted. See `docs/ScriptEditor.md` for the full guide. Scripts may use the `{{equip}}` token for equipment-relative tag paths that resolve per-equipment at deploy time — see the "Equipment-relative tag paths" section in `docs/ScriptEditor.md`. diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 5bcb1b004..55e07d6c9 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -178,6 +178,22 @@ editor ⇔ publish parity (`Editor_and_publish_gate_agree`). Each violation is mapped via `tree.GetMappedLineSpan(span)` to user-source coordinates and emitted as an error marker with code `OTSCRIPT_FORBIDDEN`. +### The deploy gate compiles too (lmxopcua#971 follow-up) + +Saving a script is not compile-gated — the editor's diagnostics are advisory while +you type. The **deploy** is: before a deployment is sealed, every script it will +run (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags) is +compiled through the same `ScriptEvaluator` pipeline the runtime uses, with +`{{equip}}/` already resolved per equipment exactly as the compose seams +resolve it. Under the default `Deployment:ScriptCompileGateMode=Error`, a script +the runtime would refuse rejects the deploy with `ScriptCompileFailed`, naming the +script, the seam it was compiled for and the entities using it — so an error the +editor showed can no longer be deployed silently. Two differences from the editor +to know: the gate compiles each script **as the seam that uses it** (a predicate +must return `bool`; the editor analyses every script as a VirtualTag body), and it +only checks scripts something enabled uses. See `docs/VirtualTags.md` +§"Deploy-time script compile gate" for modes, caching and the upgrade note. + ### Runtime safety (what happens after publish) The editor cannot catch a script that compiles cleanly but never returns or diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 8d5d6d133..cdc6c1211 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -48,7 +48,24 @@ The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type a **Adding to the list.** Add a type only if it has no I/O, no process-wide state, no background work, no blocking wait, and no member that returns or accepts a reflection handle; prefer a new `ScriptContext` helper to opening BCL surface. The editor's completions, diagnostics and the publish gate all follow the list automatically (one authority). -**Upgrading.** A deployed script that used an API now off the list (the 2026-12 differential over every script in the repo found none apart from an expression-tree test) is refused when the upgraded node compiles it (the deploy gate does not compile scripts): a virtual tag or Calculation tag publishes Bad with `sandbox violation: …` and a Warning log line, and a scripted alarm's predicate fails to load. Re-run the analyzer over stored scripts before upgrading — open each in the script editor (same analyzer), or compile them through `ScriptEvaluator`. +**Upgrading.** A deployed script that used an API now off the list (the 2026-12 differential over every script in the repo found none apart from an expression-tree test) is refused when the upgraded node compiles it: a virtual tag or Calculation tag publishes Bad with `sandbox violation: …` and a Warning log line, and a scripted alarm's predicate fails to load — which fails the **whole** scripted-alarm load on that node. Nodes recompile the running artifact on restart, so this happens on upgrade regardless of the deploy gate. What changes with the [deploy-time compile gate](#deploy-time-script-compile-gate-deploymentscriptcompilegatemode) is the **next deploy**: in its default `Error` mode it is rejected, naming each refused script and the entities that use it. Fix the script, disable the using VirtualTag / scripted alarm, or set `Deployment:ScriptCompileGateMode=Warn` to deploy anyway. To find them before upgrading, open each stored script in the script editor (same analyzer). + +### Deploy-time script compile gate (`Deployment:ScriptCompileGateMode`) + +The deploy gate compiles every script the deployment will run before the deployment is sealed (lmxopcua#971 follow-up), so **editor rejects ⇔ publish rejects** holds for deploys too — before this, `DraftValidator` never compiled a script, and a refused script surfaced only as a Bad tag or a failed alarm load after the deploy. + +- **What is checked** is what runs: **enabled** VirtualTags (as `VirtualTagContext → object?`), **enabled** scripted-alarm predicates (`DependencyExtractor` first, as the alarm load does, then `AlarmPredicateContext → bool`), and Calculation tags of **enabled** Calculation drivers (`VirtualTagContext → object?`). Disabled ones are skipped (they never compile at runtime); a passthrough mirror VirtualTag/Calculation body is skipped (the runtime never compiles it); orphan scripts are not checked. The same source can fail as one seam and pass as another — `return 1.5;` is a fine VirtualTag and a refused predicate. +- **`{{equip}}` is resolved first**, through the same `EquipmentReferenceMap` + RawPath resolver both compose seams use. When `EquipmentScriptPaths.SubstitutionPreservesCompilation` proves the substitution only rewrites escape-free string-literal text (it cannot change a compile), the template is compiled once for every equipment instead of once per equipment; otherwise the resolved source is compiled. That fallback is not theoretical: a RawPath segment may contain `\` or `"`, and substitution pastes it into a C# literal unescaped, so `{{equip}}/speed` over a device named `de\qv` does not compile — the gate reports it. +- **Same compile as the runtime.** `ScriptEvaluator.Verify` and `CompileToImage` share one private factory (wrap, injection guard, sandbox compile, `ForbiddenTypeAnalyzer`); `Verify` stops before the stack-guard rewrite and the emit. Problems carry the runtime's own text (`compile error: …`, `sandbox violation: …`, `dependency extraction rejected — …`). +- **Shape.** ControlPlane (which owns the gate) is Roslyn-free: it depends on `IDeployScriptChecker` (`Core.Scripting.Abstractions`); the Host binds `RoslynDeployScriptChecker` on admin nodes. No checker registered ⇒ the gate is skipped. Verdicts are cached by (compile identity, source SHA-256) for the life of the process (VirtualTag and Calculation share an identity), and distinct uncached sources compile in parallel (half the cores, 1–8). The compose warms that cache from the `Script`/`VirtualTag`/`ScriptedAlarm` tables **before** opening its snapshot transaction and compose lock, then runs the authoritative check on the same snapshot it validates and composes (R03:3.2) — normally all cache hits. An internal checker failure skips the gate for that deploy (logged, noted in the accepted message), never blocks it. + +| `Deployment:ScriptCompileGateMode` | Behaviour | +|---|---| +| `Error` (default) | A refused script is a `ScriptCompileFailed` reject, one per (script, seam, problem), naming the script, the seam and up to five using entities (`+N more`). | +| `Warn` | Logged and appended to the accepted deployment message; the deploy succeeds. | +| `Off` | The gate does not run. | + +Absent, blank or unrecognised values mean `Error` — a typo never silently weakens the gate. **Why `Error` by default** (unlike `TagConfigValidationMode`, default `Warn`): a refused script never runs — its tag is Bad for as long as it is deployed, and one refused predicate takes every scripted alarm on the node dark — so blocking such a deploy blocks no working behaviour. A tolerated TagConfig typo used to *run* (silently defaulted), which is why that gate stayed `Warn`. Cost: the first deploy after a restart compiles each distinct in-use script once (tens to hundreds of ms each, more for the very first Roslyn compile in the process); the AdminUI waits 10 s for a deploy answer, so on a very large fleet the first deploy after a restart can report a timeout while it carries on — the next is cached. #### Known resource limits (accepted trade-offs) diff --git a/docs/security.md b/docs/security.md index 221dbd40d..a51b80271 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1940,6 +1940,18 @@ reflection handle can be reached. `ScriptSandbox` compiles against eight BCL ass not even bind. The publish gate and the script editor share both, so the editor shows exactly what publish refuses. Full list and rules: `docs/VirtualTags.md` §"The sandbox is an allow-list". +**The deploy gate enforces it before a deployment ships** (lmxopcua#971 follow-up). Every script a deployment will +run — enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags — is compiled through the same +pipeline and analyzer on the central node (`IDeployScriptChecker`, bound by the Host on admin nodes; compile only, +nothing is emitted or loaded there) with `{{equip}}` already resolved. `Deployment:ScriptCompileGateMode` defaults +to **`Error`**: a script the allow-list refuses rejects the deploy (`ScriptCompileFailed`, naming the script and its +users) instead of reaching nodes. This is not a second security boundary — the runtime compile on each node remains +the enforcement point, and a refused script never runs either way — but it makes a sandbox refusal an authoring +error the operator sees at deploy, not a Bad tag or a dark alarm set afterwards. `Warn` ships anyway (findings in +the accepted message); `Off` disables the check. **Upgrade note:** after upgrading to an allow-list build, the first +deploy is rejected if any in-use stored script uses an API now refused; see `docs/VirtualTags.md` +§"Deploy-time script compile gate". + 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 diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs index be6472508..531c459d7 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Commons/Types/EquipmentScriptPaths.cs @@ -87,6 +87,35 @@ public static class EquipmentScriptPaths + m.Groups[3].Value); } + /// + /// True when cannot change how COMPILES: every + /// path-literal content it would replace, and every replacement RawPath, is free of \, ", CR and LF. + /// Substitution only ever rewrites the content of a ctx.GetTag/ctx.SetVirtualTag string literal; + /// with no escape sequence, quote or line break on either side the literal stays one well-formed regular string + /// token of type string, and a C# compile (binding, overload resolution, the sandbox analyzer) never depends + /// on such a literal's characters. So the resolved source compiles exactly as the template does — which lets the + /// deploy-time script compile gate (lmxopcua#971 follow-up) compile a template once instead of once per + /// equipment. False ⇒ compile the resolved source itself. Identity cases (no token, empty map) are true. + /// + /// The template script source. + /// The owning equipment's reference map: effective name → backing-tag RawPath. + /// True when the substituted source compiles identically to . + public static bool SubstitutionPreservesCompilation(string? source, IReadOnlyDictionary referenceMap) + { + if (string.IsNullOrEmpty(source) || referenceMap is null || referenceMap.Count == 0) return true; + if (!source.Contains(EquipTokenPrefix, StringComparison.Ordinal)) return true; + foreach (Match m in PathLiteralRegex.Matches(source)) + { + var content = m.Groups[2].Value; + var replaced = SubstituteContent(content, referenceMap); + if (ReferenceEquals(replaced, content) || replaced == content) continue; + if (!IsPlainLiteralText(content) || !IsPlainLiteralText(replaced)) return false; + } + return true; + } + + private static bool IsPlainLiteralText(string text) => text.AsSpan().IndexOfAny("\\\"\r\n") < 0; + // Substitute the reference-relative token inside a single path-literal's content. The content is one // whole tag path; when it starts with the {{equip}}/ prefix the remainder is the reference name. private static string SubstituteContent(string content, IReadOnlyDictionary referenceMap) diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs index 9f41ba6f1..3808d7723 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DraftValidator.cs @@ -402,8 +402,9 @@ public static class DraftValidator /// not edges) and run (Tarjan SCC). Any SCC / self-loop is a /// deploy error naming the cycle members — an undetected calc cycle is a live oscillation loop. /// - /// Compile is deliberately NOT hard-gated (VirtualTag parity — the editor's live diagnostics mirror it and - /// a runtime compile failure lands as Bad quality + a script-log). + /// Compile is not checked HERE — this validator is Roslyn-free. The deploy gate compiles every in-use script + /// (VirtualTag, Calculation, scripted-alarm predicate) separately, through IDeployScriptChecker in + /// AdminOperationsActor (Deployment:ScriptCompileGateMode, lmxopcua#971 follow-up). private static void ValidateCalculationTags(DraftSnapshot draft, List errors) { var driverTypeByInstance = draft.DriverInstances @@ -673,8 +674,11 @@ public static class DraftValidator } /// Builds the shared from the draft's raw topology so the - /// tagname-length rule computes the SAME RawPath the deploy artifact injects into drivers. - private static RawPathResolver BuildRawPathResolver(DraftSnapshot draft) + /// tagname-length rule computes the SAME RawPath the deploy artifact injects into drivers. Public so the + /// deploy-time script compile gate resolves {{equip}} over the same topology (lmxopcua#971 follow-up). + /// The draft snapshot. + /// The resolver over the draft's raw folder/driver/device/tag-group topology. + public static RawPathResolver BuildRawPathResolver(DraftSnapshot draft) { var folders = draft.RawFolders.GroupBy(f => f.RawFolderId, StringComparer.Ordinal) .ToDictionary(g => g.Key, g => ((string?)g.First().ParentRawFolderId, g.First().Name), StringComparer.Ordinal); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/IDeployScriptChecker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/IDeployScriptChecker.cs new file mode 100644 index 000000000..fd213ac0d --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/IDeployScriptChecker.cs @@ -0,0 +1,56 @@ +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; + +/// Which script context (and result type) a script compiles against. +/// +/// Physically defined in the Roslyn-free Core.Scripting.Abstractions assembly (moved from Core.Scripting by the +/// lmxopcua#971 follow-up) so the deploy gate's can name it from ControlPlane; +/// the namespace is unchanged, so consumers' using-directives are too. +/// +public enum ScriptContextKind +{ + /// A virtual tag: VirtualTagContext → object?. + VirtualTag = 1, + + /// A Calculation tag: VirtualTagContext → object?. + Calculation = 2, + + /// A scripted-alarm predicate: AlarmPredicateContext → bool. + AlarmPredicate = 3, +} + +/// One script to check: the source the runtime will compile, and the seam it will compile for. +/// The seam — decides the globals/context type and result type the source compiles against. +/// The source exactly as the runtime receives it (any {{equip}} token already resolved). +public sealed record DeployScriptCheckRequest(ScriptContextKind Kind, string Source); + +/// The outcome for one . +/// The request this answers. +/// +/// Why the runtime would refuse the script — each the same text the runtime reports (compile error: …, +/// sandbox violation: …, dependency extraction rejected — …). Empty = the runtime compile accepts it. +/// +public sealed record DeployScriptCheckResult(DeployScriptCheckRequest Request, IReadOnlyList Problems) +{ + /// True when the runtime compile accepts the script. + public bool Passed => Problems.Count == 0; +} + +/// +/// The deploy-time script compile gate (lmxopcua#971 follow-up). Answers, for each script a deployment carries, +/// whether the runtime would compile it — the same Roslyn compile + ForbiddenTypeAnalyzer allow-list the +/// VirtualTag, Calculation and scripted-alarm seams run — without emitting or loading anything. +/// +/// +/// Compiler-free on purpose: ControlPlane (which owns the deploy gate) is Roslyn-free, so it depends on this +/// interface and the Host binds the Roslyn implementation (RoslynDeployScriptChecker in Core.Scripting). +/// Absent ⇒ the deploy gate skips the check. Implementations must be thread-safe. +/// +public interface IDeployScriptChecker +{ + /// Checks every request; results are in request order. + /// The scripts to check. + /// Cancels the remaining checks. + /// One result per request, same order. + IReadOnlyList Check( + IReadOnlyList requests, CancellationToken cancellationToken = default); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs index 3cdf6e3ca..a1548667d 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/IScriptRunner.cs @@ -69,18 +69,8 @@ public interface IScriptRunner /// A runner that owns invocation physical leases until underlying execution actually completes. public interface IPhysicalScriptRunner : IScriptRunner { } -/// Which script context (and result type) a script compiles against. -public enum ScriptContextKind -{ - /// A virtual tag: VirtualTagContext → object?. - VirtualTag = 1, - - /// A Calculation tag: VirtualTagContext → object?. - Calculation = 2, - - /// A scripted-alarm predicate: AlarmPredicateContext → bool. - AlarmPredicate = 3, -} +// ScriptContextKind lives in Core.Scripting.Abstractions (same namespace) since the lmxopcua#971 follow-up, so the +// Roslyn-free deploy gate (IDeployScriptChecker) can name it. /// One evaluation handed to an . /// The script instance key (virtual-tag id, calc RawPath, alarm id). diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs new file mode 100644 index 000000000..4445cfffb --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs @@ -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; + +/// +/// 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: +/// +/// VirtualTag / Calculation — the passthrough mirror shape () and a +/// blank source never reach Roslyn at runtime, so they pass; anything else goes through +/// as VirtualTagContext → object?. +/// AlarmPredicate — first (the scripted-alarm load rejects a +/// non-literal tag path before compiling), then as +/// AlarmPredicateContext → bool. No passthrough shortcut: the alarm engine always compiles. +/// +/// builds its compilation through the same private factory +/// uses, so the gate and the runtime cannot drift. +/// +/// +/// +/// 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 capacity (cleared wholesale when full — re-checking is only a cost, never a wrong answer). +/// Verdicts from an unexpected internal exception are not cached. +/// +/// Distinct uncached sources are checked in parallel, bounded by maxParallelism. +/// +public sealed class RoslynDeployScriptChecker : IDeployScriptChecker +{ + private readonly ConcurrentDictionary> _cache = new(StringComparer.Ordinal); + private readonly int _capacity; + private readonly int _maxParallelism; + private long _compiles; + + /// Initializes a new instance of the class. + /// Cached verdicts kept before the cache is cleared; default 4096. + /// Concurrent checks; default half the processors, between 1 and 8. + 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)); + } + + /// Gets how many sources this instance has actually run through Roslyn (cache misses). + public long CompilesPerformed => Interlocked.Read(ref _compiles); + + /// + public IReadOnlyList Check( + IReadOnlyList requests, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(requests); + var keys = new string?[requests.Count]; + var pending = new Dictionary(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( + () => Run(request), LazyThreadSafetyMode.ExecutionAndPublication)); + var verdict = lazy.Value; + if (!verdict.Cacheable) + _cache.TryRemove(new KeyValuePair>(key, lazy)); + return verdict; + } + + /// True when the runtime seam answers the source without compiling it. + 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.Verify(source); + } + else + { + ScriptEvaluator.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 Problems, bool Cacheable); +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs index 038b0334a..ab0639ed3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptEvaluator.cs @@ -82,6 +82,49 @@ public sealed class ScriptEvaluator : IDisposable /// The source does not compile. /// The source uses a forbidden API. public static byte[] CompileToImage(string scriptSource) + { + var compilation = BuildCheckedCompilation(scriptSource, out var syntaxTree); + + // Step 3a — stack-depth guard (lmxopcua#779). Insert ScriptStackGuard.Check() at the entry of the script + // body and of every lambda / anonymous method / local function, so unbounded recursion fails the script with + // a catchable exception instead of a StackOverflowException that terminates the server. After the analyzer, + // so the analyzer and its diagnostics only ever see the user's code. The rewrite is designed to bind exactly + // as the original did; an emit failure here is an internal defect, reported like any other emit failure. + var guardedTree = ScriptStackGuardInjector.Inject(compilation, syntaxTree); + compilation = compilation.ReplaceSyntaxTree(syntaxTree, guardedTree); + + // Step 4 — emit to an in-memory PE stream and load into a collectible ALC. + using var peStream = new MemoryStream(); + var emitResult = compilation.Emit(peStream); + if (!emitResult.Success) + { + var emitErrors = emitResult.Diagnostics + .Where(d => d.Severity == DiagnosticSeverity.Error) + .ToArray(); + throw new CompilationErrorException(emitErrors); + } + + return peStream.ToArray(); + } + + /// + /// Every step of that can reject a USER script — wrap + parse, the + /// wrapper-injection guard, the sandbox compile and — with no stack-guard + /// rewrite and no emit (those fail only on internal defects). The deploy-time script compile gate + /// (lmxopcua#971 follow-up, RoslynDeployScriptChecker) calls this, and it builds its compilation + /// through the SAME the runtime compile does, so the gate accepts a + /// source exactly when the runtime compile would. + /// + /// The user script source code to check. + /// The source does not compile. + /// The source uses a forbidden API. + public static void Verify(string scriptSource) => _ = BuildCheckedCompilation(scriptSource, out _); + + /// + /// Steps 1–3 of the compile pipeline, shared by (runtime) and + /// (deploy gate): returns the checked compilation and its wrapper tree, or throws. + /// + private static CSharpCompilation BuildCheckedCompilation(string scriptSource, out SyntaxTree syntaxTree) { if (scriptSource is null) throw new ArgumentNullException(nameof(scriptSource)); @@ -91,7 +134,7 @@ public sealed class ScriptEvaluator : IDisposable // wrapper's `Run` method is what we invoke at runtime; the user's source is // pasted in as its body so explicit `return` semantics apply. var wrapperSource = BuildWrapperSource(scriptSource, sandbox.Imports); - var syntaxTree = CSharpSyntaxTree.ParseText(wrapperSource); + syntaxTree = CSharpSyntaxTree.ParseText(wrapperSource); // Step 1a — defend against wrapper-source injection. // A script body of `return 0; } public static int Evil() { return 0;` would @@ -134,26 +177,7 @@ public sealed class ScriptEvaluator : IDisposable if (rejections.Count > 0) throw new ScriptSandboxViolationException(rejections); - // Step 3a — stack-depth guard (lmxopcua#779). Insert ScriptStackGuard.Check() at the entry of the script - // body and of every lambda / anonymous method / local function, so unbounded recursion fails the script with - // a catchable exception instead of a StackOverflowException that terminates the server. After the analyzer, - // so the analyzer and its diagnostics only ever see the user's code. The rewrite is designed to bind exactly - // as the original did; an emit failure here is an internal defect, reported like any other emit failure. - var guardedTree = ScriptStackGuardInjector.Inject(compilation, syntaxTree); - compilation = compilation.ReplaceSyntaxTree(syntaxTree, guardedTree); - - // Step 4 — emit to an in-memory PE stream and load into a collectible ALC. - using var peStream = new MemoryStream(); - var emitResult = compilation.Emit(peStream); - if (!emitResult.Success) - { - var emitErrors = emitResult.Diagnostics - .Where(d => d.Severity == DiagnosticSeverity.Error) - .ToArray(); - throw new CompilationErrorException(emitErrors); - } - - return peStream.ToArray(); + return compilation; } /// diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs index f90f970d7..247fbe0a7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/AdminOperationsActor.cs @@ -28,6 +28,11 @@ public sealed class AdminOperationsActor : ReceiveActor private readonly IReadOnlyDictionary _probesByType; private readonly TagConfigValidationMode _tagConfigValidationMode; + /// lmxopcua#971 follow-up: the deploy-time script compile gate; null = not wired, or mode Off. + private readonly IDeployScriptChecker? _scriptChecker; + + private readonly ScriptCompileGateMode _scriptCompileGateMode; + /// /// The coordinator's apply deadline. A Dispatching row with no expected-ack rows that is older /// than this is a lost dispatch, closed by the in-flight check (fix round 1 / I7). @@ -59,6 +64,8 @@ public sealed class AdminOperationsActor : ReceiveActor /// /// The coordinator's apply deadline; defaults to (the coordinator's default source). /// #950: how long an /alerts ack/shelve waits for the nodes' verdicts; defaults to . + /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. + /// How a refused script is treated (Error default | Warn | Off). /// Props configured to create an AdminOperationsActor. public static Props Props( IDbContextFactory dbFactory, @@ -67,9 +74,12 @@ public sealed class AdminOperationsActor : ReceiveActor TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn, IActorRef? meshRouter = null, TimeSpan? applyDeadline = null, - TimeSpan? alarmVerdictWindow = null) => + TimeSpan? alarmVerdictWindow = null, + IDeployScriptChecker? scriptChecker = null, + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) => Akka.Actor.Props.Create(() => - new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, alarmVerdictWindow)); + new AdminOperationsActor(dbFactory, coordinator, probes, tagConfigValidationMode, meshRouter, applyDeadline, + alarmVerdictWindow, scriptChecker, scriptCompileGateMode)); /// Initializes a new instance of the AdminOperationsActor. /// Factory for creating config database contexts. @@ -79,6 +89,8 @@ public sealed class AdminOperationsActor : ReceiveActor /// Central comm actor, or for the mediator. /// The coordinator's apply deadline; defaults to (the coordinator's default source). /// #950: the /alerts verdict collection window. + /// lmxopcua#971 follow-up: the deploy-time script compile gate, or to skip it. + /// How a refused script is treated (Error default | Warn | Off). public AdminOperationsActor( IDbContextFactory dbFactory, IActorRef coordinator, @@ -86,8 +98,12 @@ public sealed class AdminOperationsActor : ReceiveActor TagConfigValidationMode tagConfigValidationMode = TagConfigValidationMode.Warn, IActorRef? meshRouter = null, TimeSpan? applyDeadline = null, - TimeSpan? alarmVerdictWindow = null) + TimeSpan? alarmVerdictWindow = null, + IDeployScriptChecker? scriptChecker = null, + ScriptCompileGateMode scriptCompileGateMode = ScriptCompileGateMode.Error) { + _scriptChecker = scriptCompileGateMode == ScriptCompileGateMode.Off ? null : scriptChecker; + _scriptCompileGateMode = scriptCompileGateMode; _alarmVerdictWindow = alarmVerdictWindow ?? AlarmCommandVerdictCollector.DefaultWindow; // The same source the coordinator's default reads (ConfigPublishCoordinator.DefaultApplyDeadline IS // DeployTimings.ApplyDeadline), so the lost-dispatch closure and the coordinator's own deadline agree. @@ -466,6 +482,15 @@ public sealed class AdminOperationsActor : ReceiveActor /// private async Task ComposeDeploymentAsync(StartDeployment msg, string sourceNode, ComposePhaseTimer phases) { + // lmxopcua#971 follow-up: warm the script compile gate's cache BEFORE the snapshot transaction + compose app + // lock, so the Roslyn work does not run while they are held. The authoritative check runs on the snapshot + // below; with the cache warm it is (almost always) all hits. + if (_scriptChecker is not null) + { + await WarmScriptCompileGateAsync(_scriptChecker).ConfigureAwait(false); + phases.Mark("script-gate-warm"); + } + // lmxopcua#949: phase timings, logged only when the deploy is slow (see ComposePhaseTimer). await using var db = await _dbFactory.CreateDbContextAsync(); // ONE transaction holds the snapshot read, the scope-revision advance and the Deployment row, committed @@ -585,6 +610,35 @@ public sealed class AdminOperationsActor : ReceiveActor _log.Warning("StartDeployment: data-connection warning (non-blocking): {Warning}", w); phases.Mark("validate"); + + // lmxopcua#971 follow-up — the deploy-time script compile gate: every script the runtime will compile + // (enabled VirtualTags, enabled scripted-alarm predicates, Calculation tags), {{equip}} resolved exactly as the + // compose seams resolve it, through the same compile + allow-list analyzer the runtime runs. On the SAME + // snapshot as everything else (R03:3.2); the warm-up above means this is normally all cache hits. + var scriptWarnings = new List(); + if (_scriptChecker is not null) + { + try + { + foreach (var f in DeployScriptGate.Run(_scriptChecker, draft)) + { + if (_scriptCompileGateMode == ScriptCompileGateMode.Error) + errors.Add(new ValidationError(DeployScriptGate.ErrorCode, f.Text, f.ScriptId)); + else + { + scriptWarnings.Add(f.Text); + _log.Warning("StartDeployment: script compile warning (Warn mode, non-blocking): {Warning}", f.Text); + } + } + } + catch (Exception ex) + { + // An internal checker failure must not block every deploy; the gate is skipped and says so. + _log.Error(ex, "StartDeployment: script compile gate failed internally; skipped for this deploy (correlation {CorrelationId})", msg.CorrelationId); + scriptWarnings.Add("script compile gate skipped (internal error; see the central log)"); + } + phases.Mark("script-gate"); + } if (errors.Count > 0) { phases.LogIfSlow(_log, msg, outcome: "rejected"); @@ -677,6 +731,7 @@ public sealed class AdminOperationsActor : ReceiveActor if (advisory is not null) messageParts.Add(advisory); messageParts.AddRange(tagConfigWarnings.Select(x => x.Text)); messageParts.AddRange(writableWarnings); + messageParts.AddRange(scriptWarnings); var acceptedMessage = messageParts.Count > 0 ? string.Join("; ", messageParts) : null; return new ComposeOutcome( @@ -689,6 +744,34 @@ public sealed class AdminOperationsActor : ReceiveActor new DispatchDeployment(deploymentId, revHash, msg.CorrelationId)); } + /// + /// lmxopcua#971 follow-up: warms the script compile gate's cache from the three small script tables (no + /// Tags read), outside any transaction. Best-effort — a failure here is logged and the authoritative + /// in-transaction pass does the work instead. + /// + /// The compile checker. + private async Task WarmScriptCompileGateAsync(IDeployScriptChecker checker) + { + try + { + await using var db = await _dbFactory.CreateDbContextAsync().ConfigureAwait(false); + var scripts = await db.Scripts.AsNoTracking() + .Select(s => new { s.ScriptId, s.SourceCode }) + .ToListAsync().ConfigureAwait(false); + if (scripts.Count == 0) return; + var vtScriptIds = await db.VirtualTags.AsNoTracking().Where(v => v.Enabled) + .Select(v => v.ScriptId).Distinct().ToListAsync().ConfigureAwait(false); + var predicateScriptIds = await db.ScriptedAlarms.AsNoTracking().Where(a => a.Enabled) + .Select(a => a.PredicateScriptId).Distinct().ToListAsync().ConfigureAwait(false); + checker.Check(DeployScriptGate.WarmRequests( + scripts.Select(s => (s.ScriptId, s.SourceCode)), vtScriptIds, predicateScriptIds)); + } + catch (Exception ex) + { + _log.Warning(ex, "StartDeployment: script compile gate warm-up failed; the in-snapshot check runs cold"); + } + } + /// /// Test Connect runs on the thread pool and pipes its reply straight to the requester: a probe /// against a black-holed PLC (60 s clamp) must not suspend the singleton's mailbox (R03:3.1). Every diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployScriptGate.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployScriptGate.cs new file mode 100644 index 000000000..543642694 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/DeployScriptGate.cs @@ -0,0 +1,220 @@ +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; + +/// +/// The deploy-time script compile gate's draft side (lmxopcua#971 follow-up): turns a +/// into the scripts the runtime will compile — each with the seam it compiles for and the source exactly as that +/// seam receives it — hands them to an , and folds the verdicts back onto the +/// scripts and the entities that use them. Roslyn-free; the compile itself lives behind the checker. +/// +/// +/// What is checked mirrors what runs: +/// +/// Enabled VirtualTags (a disabled one is materialised but never evaluated) — source with the +/// owning equipment's {{equip}}/<RefName> substituted, exactly as both compose seams +/// (AddressSpaceComposer / DeploymentArtifact) do, through the shared +/// over . +/// Enabled scripted alarms (a disabled plan is skipped by the alarm host) — predicate source, +/// substituted the same way. +/// Calculation tags of enabled Calculation drivers — the source verbatim (the artifact injects it +/// into the tag's TagConfig with no substitution). +/// +/// +/// When proves the substitution cannot +/// change how the source compiles (the common case), the TEMPLATE is what is sent — so a VirtualTag template +/// shared by 500 equipments is one compile, not 500. Otherwise the resolved source itself is compiled. +/// +/// +public static class DeployScriptGate +{ + /// The finding code a refused script is reported under (Error mode). + public const string ErrorCode = "ScriptCompileFailed"; + + /// Most using entities named in one finding before it says "+N more". + internal const int MaxUsersNamed = 5; + + /// One script use: which script, as what seam, by which entity, and what will be compiled. + /// The Script row. + /// The seam it compiles for. + /// The using entity, for the operator (e.g. VirtualTag 'vt-1' (equipment 'EQ-1')). + /// The using entity's id. + /// The source sent to the checker (resolved, or the equivalent template). + public sealed record ScriptUse(string ScriptId, ScriptContextKind Kind, string UsedBy, string EntityId, string CompileSource); + + /// A refused script, grouped over every entity that uses it the same way. + /// The Script row. + /// The seam it was compiled for. + /// Every using entity, ordinal. + /// Why the runtime would refuse it (the runtime's own failure text). + public sealed record Finding(string ScriptId, ScriptContextKind Kind, IReadOnlyList UsedBy, IReadOnlyList Problems) + { + /// The operator-facing sentence: names the script, the seam, the users and the problems. + public string Text + { + get + { + var named = string.Join(", ", UsedBy.Take(MaxUsersNamed)); + var more = UsedBy.Count > MaxUsersNamed ? $" (+{UsedBy.Count - MaxUsersNamed} more)" : string.Empty; + return $"script '{ScriptId}' does not compile as a {KindLabel(Kind)} (used by {named}{more}): " + + string.Join("; ", Problems); + } + } + } + + /// Human label for a seam. + /// The seam. + /// The label. + public static string KindLabel(ScriptContextKind kind) => kind switch + { + ScriptContextKind.VirtualTag => "VirtualTag script", + ScriptContextKind.Calculation => "Calculation script", + ScriptContextKind.AlarmPredicate => "scripted-alarm predicate", + _ => kind.ToString(), + }; + + /// Every script use the runtime will compile, in a deterministic order. + /// The draft snapshot being deployed. + /// The uses. + public static IReadOnlyList CollectUses(DraftSnapshot draft) + { + ArgumentNullException.ThrowIfNull(draft); + var uses = new List(); + var sourceById = draft.Scripts + .GroupBy(s => s.ScriptId, StringComparer.Ordinal) + .ToDictionary(g => g.Key, g => g.First().SourceCode ?? string.Empty, StringComparer.Ordinal); + if (sourceById.Count == 0) return uses; + + // {{equip}}/ → RawPath — the same authority + resolver as the compose seams and DraftValidator. + var resolver = DraftValidator.BuildRawPathResolver(draft); + var tagsById = draft.Tags + .GroupBy(t => t.TagId, StringComparer.Ordinal) + .ToDictionary( + g => g.Key, + g => new EquipmentReferenceMap.TagRow(g.First().Name, g.First().DeviceId, g.First().TagGroupId), + StringComparer.Ordinal); + var referenceMapByEquip = EquipmentReferenceMap.Build( + draft.UnsTagReferences.Select(r => new EquipmentReferenceMap.ReferenceRow( + r.UnsTagReferenceId, r.EquipmentId, r.TagId, r.DisplayNameOverride)), + tagsById, resolver); + var noRefs = (IReadOnlyDictionary)new Dictionary(StringComparer.Ordinal); + + string Resolve(string template, string equipmentId) + { + var map = referenceMapByEquip.GetValueOrDefault(equipmentId, noRefs); + return EquipmentScriptPaths.SubstitutionPreservesCompilation(template, map) + ? template + : EquipmentScriptPaths.SubstituteEquipmentToken(template, map); + } + + foreach (var v in draft.VirtualTags.Where(v => v.Enabled).OrderBy(v => v.VirtualTagId, StringComparer.Ordinal)) + { + if (!sourceById.TryGetValue(v.ScriptId, out var src)) continue; // dangling id: DraftValidator's finding + uses.Add(new ScriptUse(v.ScriptId, ScriptContextKind.VirtualTag, + $"VirtualTag '{v.VirtualTagId}' (equipment '{v.EquipmentId}')", v.VirtualTagId, Resolve(src, v.EquipmentId))); + } + + foreach (var a in draft.ScriptedAlarms.Where(a => a.Enabled).OrderBy(a => a.ScriptedAlarmId, StringComparer.Ordinal)) + { + if (!sourceById.TryGetValue(a.PredicateScriptId, out var src)) continue; + uses.Add(new ScriptUse(a.PredicateScriptId, ScriptContextKind.AlarmPredicate, + $"ScriptedAlarm '{a.ScriptedAlarmId}' (equipment '{a.EquipmentId}')", a.ScriptedAlarmId, + Resolve(src, a.EquipmentId))); + } + + var enabledCalcDrivers = draft.DriverInstances + .Where(d => d.Enabled && string.Equals(d.DriverType, DriverTypeNames.Calculation, StringComparison.Ordinal)) + .Select(d => d.DriverInstanceId) + .ToHashSet(StringComparer.Ordinal); + if (enabledCalcDrivers.Count > 0) + { + var calcDevices = draft.Devices + .Where(d => enabledCalcDrivers.Contains(d.DriverInstanceId)) + .Select(d => d.DeviceId) + .ToHashSet(StringComparer.Ordinal); + foreach (var t in draft.Tags.Where(t => calcDevices.Contains(t.DeviceId)).OrderBy(t => t.TagId, StringComparer.Ordinal)) + { + var scriptId = DraftValidator.ParseScriptId(t.TagConfig); + if (scriptId is null || !sourceById.TryGetValue(scriptId, out var src)) continue; + var rawPath = resolver.TryBuildTagPath(t.DeviceId, t.TagGroupId, t.Name); + uses.Add(new ScriptUse(scriptId, ScriptContextKind.Calculation, + rawPath is null ? $"Calculation tag '{t.TagId}'" : $"Calculation tag '{t.TagId}' ({rawPath})", + t.TagId, src)); + } + } + + return uses; + } + + /// + /// The cache-warming request set, from the three small tables only — no Tags read. Sent BEFORE the deploy's + /// snapshot transaction so the authoritative in-transaction pass is (almost always) all cache hits. Each + /// script is warmed as the seams that can use it: a predicate of an enabled scripted alarm as + /// ; any other script as a value script (VirtualTag and + /// Calculation share one compile). Templates only — that is what the gate sends whenever substitution + /// preserves compilation. + /// + /// Script id + source. + /// Script ids of enabled VirtualTags. + /// Predicate script ids of enabled scripted alarms. + /// The warm-up requests. + public static IReadOnlyList WarmRequests( + IEnumerable<(string ScriptId, string Source)> scripts, + IEnumerable enabledVirtualTagScriptIds, + IEnumerable enabledPredicateScriptIds) + { + var vt = enabledVirtualTagScriptIds.ToHashSet(StringComparer.Ordinal); + var predicates = enabledPredicateScriptIds.ToHashSet(StringComparer.Ordinal); + var requests = new List(); + foreach (var (id, source) in scripts) + { + var isPredicate = predicates.Contains(id); + if (isPredicate) requests.Add(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, source ?? string.Empty)); + if (!isPredicate || vt.Contains(id)) + requests.Add(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source ?? string.Empty)); + } + return requests; + } + + /// Checks every use in and returns the refused scripts, grouped. + /// The compile checker. + /// The draft snapshot being deployed. + /// Cancellation. + /// The findings, ordered by script id then seam; empty when every used script compiles. + public static IReadOnlyList Run(IDeployScriptChecker checker, DraftSnapshot draft, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(checker); + var uses = CollectUses(draft); + if (uses.Count == 0) return []; + + // One request per distinct (seam, source); the checker caches across deploys as well. + var requestIndex = new Dictionary<(ScriptContextKind, string), int>(); + var requests = new List(); + foreach (var u in uses) + { + if (requestIndex.ContainsKey((u.Kind, u.CompileSource))) continue; + requestIndex[(u.Kind, u.CompileSource)] = requests.Count; + requests.Add(new DeployScriptCheckRequest(u.Kind, u.CompileSource)); + } + var results = checker.Check(requests, cancellationToken); + if (results.Count != requests.Count) + throw new InvalidOperationException( + $"IDeployScriptChecker returned {results.Count} result(s) for {requests.Count} request(s)."); + + return uses + .Select(u => (Use: u, Problems: results[requestIndex[(u.Kind, u.CompileSource)]].Problems)) + .Where(x => x.Problems.Count > 0) + .GroupBy(x => (x.Use.ScriptId, x.Use.Kind, Problems: string.Join("\n", x.Problems))) + .OrderBy(g => g.Key.ScriptId, StringComparer.Ordinal) + .ThenBy(g => g.Key.Kind) + .Select(g => new Finding( + g.Key.ScriptId, + g.Key.Kind, + g.Select(x => x.Use.UsedBy).Distinct(StringComparer.Ordinal).OrderBy(s => s, StringComparer.Ordinal).ToList(), + g.First().Problems)) + .ToList(); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ScriptCompileGateMode.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ScriptCompileGateMode.cs new file mode 100644 index 000000000..4507dda09 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/AdminOperations/ScriptCompileGateMode.cs @@ -0,0 +1,38 @@ +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; + +/// +/// How the deploy gate treats a script the runtime would refuse to compile (lmxopcua#971 follow-up). Sourced from +/// Deployment:ScriptCompileGateMode in appsettings; defaults to . Takes effect only when +/// an IDeployScriptChecker is registered (the Host binds one on admin nodes). +/// +/// +/// +/// Why is the default (unlike , which defaults to +/// Warn): a script that fails this gate never runs — a VirtualTag or Calculation tag publishes Bad +/// (compile error / sandbox violation) for as long as it is deployed, and one failing +/// scripted-alarm predicate fails the whole scripted-alarm load, so EVERY scripted alarm on the node goes dark. +/// Blocking the deploy therefore blocks no working behaviour — only a deployment that carries a definitely +/// broken script — and it is the only mode in which "the editor rejects ⇔ publish rejects" holds. A tolerated +/// TagConfig typo, by contrast, used to run (the runtime silently defaulted it), which is why that gate stayed +/// Warn. +/// +/// +/// Upgrade note: lmxopcua#971 narrowed the script sandbox to an allow-list, so a stored, in-use script +/// that compiled before the upgrade can now be refused. The first deploy after upgrading is then REJECTED, +/// naming each script and the entities that use it — fix the script, disable the using VirtualTag / scripted +/// alarm, or set Deployment:ScriptCompileGateMode=Warn to ship anyway (the script stays broken at +/// runtime either way: nodes recompile the running artifact on restart, so the gate cannot make a refused +/// script work — it only stops new deploys from carrying one silently). +/// +/// +public enum ScriptCompileGateMode +{ + /// Blocking: a refused script folds into the reject list (ScriptCompileFailed). The default. + Error, + + /// Non-blocking: findings are logged and appended to the accepted StartDeploymentResult.Message. + Warn, + + /// The gate does not run (no compile cost at deploy time). + Off, +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs index 048613739..9849f0530 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.ControlPlane/ServiceCollectionExtensions.cs @@ -18,6 +18,7 @@ using ZB.MOM.WW.OtOpcUa.ControlPlane.Fleet; using ZB.MOM.WW.OtOpcUa.ControlPlane.Redundancy; using ZB.MOM.WW.OtOpcUa.ControlPlane.Retention; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; namespace ZB.MOM.WW.OtOpcUa.ControlPlane; @@ -34,6 +35,19 @@ public static class ServiceCollectionExtensions public const string ClusterNodeAddressReconcilerSingletonName = "cluster-node-address-reconciler"; public const string DeploymentRetentionSingletonName = "deployment-retention"; + /// + /// Parses Deployment:ScriptCompileGateMode (lmxopcua#971 follow-up). Absent, blank or unrecognised ⇒ + /// : a typo never silently weakens the gate (and never stops the + /// admin singleton from starting, which a throw inside its props factory would). + /// + /// The configured value. + /// The mode. + public static ScriptCompileGateMode ParseScriptCompileGateMode(string? value) => + Enum.TryParse(value?.Trim(), ignoreCase: true, out var mode) + && Enum.IsDefined(mode) && !int.TryParse(value, out _) + ? mode + : ScriptCompileGateMode.Error; + /// /// Registers the admin-role cluster singletons on the AkkaConfigurationBuilder — three with /// registry proxies, plus the address reconciler, which is proxy-less because nothing addresses it. @@ -132,11 +146,18 @@ public static class ServiceCollectionExtensions var mode = Enum.TryParse( resolver.GetService()?["Deployment:TagConfigValidationMode"], ignoreCase: true, out var m) ? m : TagConfigValidationMode.Warn; + // lmxopcua#971 follow-up: the deploy-time script compile gate. The checker is optional (the Host binds + // the Roslyn one on admin nodes; this project stays Roslyn-free) — through IServiceProvider for + // GetService's null-for-absent contract. Mode: Deployment:ScriptCompileGateMode = Error default | Warn | Off. + var scriptChecker = resolver.GetService()?.GetService(); + var scriptMode = ParseScriptCompileGateMode( + resolver.GetService()?["Deployment:ScriptCompileGateMode"]); var meshRouter = registry.Get(); // The SAME deadline source as the coordinator above: AdminOps closes a lost dispatch only once it // is past the coordinator's deadline, so the two must never drift. return AdminOperationsActor.Props(dbFactory, coordinator, probes, mode, meshRouter, - applyDeadline: DeployTimings.ApplyDeadline); + applyDeadline: DeployTimings.ApplyDeadline, + scriptChecker: scriptChecker, scriptCompileGateMode: scriptMode); }, singletonOptions); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs index a4aa95f68..612cf4edc 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Program.cs @@ -181,6 +181,10 @@ if (hasAdmin) // lmxopcua#868: the deploy coordinator singleton reports its ConfigDb recovery-load state here; the // config-publish health check (AddOtOpcUaHealth) reads it — Degraded while deployments are queued. builder.Services.AddSingleton(); + // lmxopcua#971 follow-up: the deploy-time script compile gate. ControlPlane is Roslyn-free and resolves this + // optionally (absent ⇒ the gate is skipped); Deployment:ScriptCompileGateMode picks Error (default) | Warn | Off. + builder.Services.AddSingleton(_ => new ZB.MOM.WW.OtOpcUa.Core.Scripting.RoslynDeployScriptChecker()); } else Log.Information("Driver-only node — no ConfigDb registered; configuration via ConfigSource:Mode=FetchAndCache"); diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs index ffec2c83c..a0ae6e865 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Commons.Tests/EquipmentScriptPathsTests.cs @@ -255,4 +255,41 @@ public class EquipmentScriptPathsTests EquipmentScriptPaths.TryParseRelayBody(src, out var r).ShouldBeFalse(); r.ShouldBeNull(); } + + // ---- SubstitutionPreservesCompilation (lmxopcua#971 follow-up: the deploy compile gate's template dedupe) ---- + + [Theory] + [InlineData("return ctx.GetTag(\"{{equip}}/Speed\").Value;")] // plain substitution + [InlineData("return ctx.GetTag(\"Plant/Literal\").Value;")] // no token + [InlineData("return ctx.GetTag(\"{{equip}}/Missing\").Value;")] // unresolved: unchanged + [InlineData("ctx.SetVirtualTag(\"{{equip}}/Out\", 1); return ctx.GetTag(\"{{equip}}/A\").Value;")] + [InlineData("")] + public void SubstitutionPreservesCompilation_true_when_only_escape_free_literal_text_changes(string src) + { + EquipmentScriptPaths.SubstitutionPreservesCompilation(src, RefMap).ShouldBeTrue(); + } + + [Fact] + public void SubstitutionPreservesCompilation_false_when_a_replacement_carries_an_escape_character() + { + // A backslash in a RawPath would become an escape sequence inside the literal — compile the resolved source. + var map = new Dictionary(StringComparer.Ordinal) { ["Speed"] = @"Cell1\Dev\Speed" }; + EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Speed\").Value;", map) + .ShouldBeFalse(); + } + + [Fact] + public void SubstitutionPreservesCompilation_false_when_the_replaced_text_carries_an_escape() + { + var map = new Dictionary(StringComparer.Ordinal) { [@"Sp\eed"] = "Cell1/Dev/Speed" }; + EquipmentScriptPaths.SubstitutionPreservesCompilation("return ctx.GetTag(\"{{equip}}/Sp\\eed\").Value;", map) + .ShouldBeFalse(); + } + + [Fact] + public void SubstitutionPreservesCompilation_empty_map_is_identity() + { + EquipmentScriptPaths.SubstitutionPreservesCompilation( + "return ctx.GetTag(\"{{equip}}/Speed\").Value;", new Dictionary()).ShouldBeTrue(); + } } diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs new file mode 100644 index 000000000..653f9a066 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs @@ -0,0 +1,163 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.ScriptedAlarms; +using ZB.MOM.WW.OtOpcUa.Core.VirtualTags; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// lmxopcua#971 follow-up — the deploy-time script compile gate's Roslyn side. The gate must answer exactly as the +/// runtime seam would: same compile, same allow-list, per seam (a VirtualTag/Calculation compiles as +/// VirtualTagContext → object?, a scripted-alarm predicate as AlarmPredicateContext → bool after the +/// dependency extractor), and cached so a redeploy does not re-enter Roslyn. +/// +[Trait("Category", "Unit")] +public sealed class RoslynDeployScriptCheckerTests +{ + private const string Legit = "var v = ctx.GetTag(\"A\").Value; return v is null ? 0.0 : Convert.ToDouble(v) * 2;"; + private const string Forbidden = "return System.IO.File.ReadAllText(\"/etc/passwd\");"; + private const string Broken = "return undefinedThing + 1;"; + + private static DeployScriptCheckResult CheckOne(IDeployScriptChecker checker, ScriptContextKind kind, string source) => + checker.Check([new DeployScriptCheckRequest(kind, source)], TestContext.Current.CancellationToken).Single(); + + [Fact] + public void A_legitimate_script_passes_positive_control() + { + var checker = new RoslynDeployScriptChecker(); + CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue(); + CheckOne(checker, ScriptContextKind.Calculation, Legit).Passed.ShouldBeTrue(); + CheckOne(checker, ScriptContextKind.AlarmPredicate, "return Convert.ToDouble(ctx.GetTag(\"A\").Value ?? 0.0) > 5;") + .Passed.ShouldBeTrue(); + } + + [Fact] + public void A_forbidden_api_is_a_sandbox_violation() + { + var result = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.VirtualTag, Forbidden); + result.Passed.ShouldBeFalse(); + result.Problems.Single().ShouldStartWith("sandbox violation: "); + result.Problems.Single().ShouldContain("File"); + result.Problems.Single().ShouldNotContain("\n"); + } + + [Fact] + public void A_compile_error_is_reported_as_the_runtime_reports_it() + { + var result = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.VirtualTag, Broken); + result.Problems.Single().ShouldStartWith("compile error: "); + result.Problems.Single().ShouldContain("undefinedThing"); + } + + [Fact] + public void The_seam_decides_the_compile_a_non_bool_result_fails_only_as_an_alarm_predicate() + { + var checker = new RoslynDeployScriptChecker(); + const string returnsDouble = "return 1.5;"; + CheckOne(checker, ScriptContextKind.VirtualTag, returnsDouble).Passed.ShouldBeTrue(); + var asPredicate = CheckOne(checker, ScriptContextKind.AlarmPredicate, returnsDouble); + asPredicate.Passed.ShouldBeFalse(); + asPredicate.Problems.Single().ShouldStartWith("compile error: "); + } + + [Fact] + public void An_alarm_predicate_runs_the_dependency_extractor_first_a_virtual_tag_does_not() + { + // A non-literal tag path: the scripted-alarm load rejects it before compiling; the VirtualTag seam never + // runs the extractor, so the same source compiles there. + const string dynamicPath = "var p = \"A\"; return ctx.GetTag(p).Value is null;"; + var checker = new RoslynDeployScriptChecker(); + CheckOne(checker, ScriptContextKind.VirtualTag, dynamicPath).Passed.ShouldBeTrue(); + CheckOne(checker, ScriptContextKind.AlarmPredicate, dynamicPath) + .Problems.Single().ShouldStartWith("dependency extraction rejected — "); + } + + [Fact] + public void A_passthrough_mirror_never_reaches_roslyn_for_value_seams_but_does_for_a_predicate() + { + const string mirror = "return ctx.GetTag(\"Plant/Dev/Speed\").Value;"; + var checker = new RoslynDeployScriptChecker(); + CheckOne(checker, ScriptContextKind.VirtualTag, mirror).Passed.ShouldBeTrue(); + CheckOne(checker, ScriptContextKind.Calculation, mirror).Passed.ShouldBeTrue(); + checker.CompilesPerformed.ShouldBe(0); + // The alarm engine always compiles — and object is not bool. + CheckOne(checker, ScriptContextKind.AlarmPredicate, mirror).Passed.ShouldBeFalse(); + checker.CompilesPerformed.ShouldBe(1); + } + + [Fact] + public void Verdicts_are_cached_by_source_and_compile_identity() + { + var checker = new RoslynDeployScriptChecker(); + CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse(); + checker.CompilesPerformed.ShouldBe(1); + + // Cache hit: same source, same seam — and Calculation shares the VirtualTag compile. + CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse(); + CheckOne(checker, ScriptContextKind.Calculation, Forbidden).Passed.ShouldBeFalse(); + checker.CompilesPerformed.ShouldBe(1); + + // A different compile identity is a miss. + CheckOne(checker, ScriptContextKind.AlarmPredicate, Forbidden).Passed.ShouldBeFalse(); + checker.CompilesPerformed.ShouldBe(2); + } + + [Fact] + public void A_batch_compiles_each_distinct_source_once_and_answers_in_request_order() + { + var checker = new RoslynDeployScriptChecker(maxParallelism: 4); + var requests = new[] + { + new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit), + new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Forbidden), + new DeployScriptCheckRequest(ScriptContextKind.Calculation, Legit), + new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Broken), + new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Forbidden), + }; + var results = checker.Check(requests, TestContext.Current.CancellationToken); + results.Select(r => r.Request).ShouldBe(requests); + results.Select(r => r.Passed).ShouldBe([true, false, true, false, false]); + checker.CompilesPerformed.ShouldBe(3); + } + + [Fact] + public void A_full_cache_is_cleared_and_still_answers_correctly() + { + var checker = new RoslynDeployScriptChecker(capacity: 1); + CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue(); + CheckOne(checker, ScriptContextKind.VirtualTag, Forbidden).Passed.ShouldBeFalse(); + CheckOne(checker, ScriptContextKind.VirtualTag, Legit).Passed.ShouldBeTrue(); + checker.CompilesPerformed.ShouldBe(3); + } + + /// + /// Parity with the runtime compile: shares the + /// compilation factory with , so for every + /// sample the gate passes exactly when the runtime compile succeeds. + /// + [Theory] + [InlineData(Legit)] + [InlineData(Forbidden)] + [InlineData(Broken)] + [InlineData("return 1.5;")] + [InlineData("return true;")] + [InlineData("return 0; } public static int Evil() { return 0;")] + [InlineData("var t = typeof(string).Assembly; return t.FullName;")] + [InlineData("return Environment.GetEnvironmentVariable(\"PATH\");")] + public void The_gate_accepts_exactly_what_the_runtime_compile_accepts(string source) + { + var checker = new RoslynDeployScriptChecker(); + + static bool RuntimeCompiles(string s) where TContext : ScriptContext + { + try { _ = ScriptEvaluator.CompileToImage(s); return true; } + catch (CompilationErrorException) { return false; } + catch (ScriptSandboxViolationException) { return false; } + } + + CheckOne(checker, ScriptContextKind.VirtualTag, source).Passed + .ShouldBe(RuntimeCompiles(source)); + var predicateRuntime = DependencyExtractor.Extract(source).IsValid && RuntimeCompiles(source); + CheckOne(checker, ScriptContextKind.AlarmPredicate, source).Passed.ShouldBe(predicateRuntime); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs new file mode 100644 index 000000000..940369c40 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.ControlPlane.Tests/AdminOperationsActorScriptCompileGateTests.cs @@ -0,0 +1,321 @@ +using System.Collections.Concurrent; +using Akka.Actor; +using Microsoft.EntityFrameworkCore; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin; +using ZB.MOM.WW.OtOpcUa.Commons.Messages.Deploy; +using ZB.MOM.WW.OtOpcUa.Commons.Types; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations; +using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Scripting; + +namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests; + +/// +/// lmxopcua#971 follow-up — the deploy-time script compile gate, exercised THROUGH the actor with the real Roslyn +/// checker (and a recording fake where the test is about what is sent). A script the runtime would refuse blocks +/// the deploy in Error mode (the default) and rides the accepted message in Warn mode; a legitimate draft deploys +/// clean (the positive control every reject test leans on); each seam compiles as itself; {{equip}} is resolved +/// before compiling; an absent checker or mode Off skips the gate. +/// +public sealed class AdminOperationsActorScriptCompileGateTests : ControlPlaneActorTestBase +{ + private const string Legit = "var v = ctx.GetTag(\"{{equip}}/speed\").Value; return v is null ? 0.0 : Convert.ToDouble(v) * 2;"; + // Reads a tag so the draft is otherwise valid (a VirtualTag with no input never triggers — a DraftValidator error). + private const string Forbidden = + "var v = ctx.GetTag(\"{{equip}}/speed\").Value; return v is null ? null : System.IO.File.ReadAllText(\"/etc/passwd\");"; + private const string LegitPredicate = "return Convert.ToDouble(ctx.GetTag(\"{{equip}}/speed\").Value ?? 0.0) > 5;"; + private const string LegitCalc = "return Convert.ToDouble(ctx.GetTag(\"plant/drv/dev/speed\").Value ?? 0.0) + 1;"; + private const string CleanModbus = "{\"region\":\"HoldingRegisters\",\"address\":1,\"dataType\":\"Int16\"}"; + + private sealed record Seed( + string VtSource = Legit, string PredicateSource = LegitPredicate, string CalcSource = LegitCalc, + bool VtEnabled = true, bool AlarmEnabled = true, int Equipments = 1, bool SharedVtScript = true, string DeviceName = "dev"); + + /// A complete, DraftValidator-clean draft: area/line/equipment(s), a Modbus tag referenced into each + /// equipment as speed, a VirtualTag + scripted alarm per equipment, and one Calculation tag. + private static IDbContextFactory SeedDraft(Seed seed) + { + var dbFactory = NewInMemoryDbFactory(); + using var db = dbFactory.CreateDbContext(); + db.RawFolders.Add(new RawFolder { RawFolderId = "rf-plant", ClusterId = "", Name = "plant" }); + db.DriverInstances.Add(new DriverInstance + { + DriverInstanceId = "d-1", ClusterId = "", RawFolderId = "rf-plant", Name = "drv", DriverType = "Modbus", DriverConfig = "{}", + }); + db.Devices.Add(new Device { DeviceId = "dev-1", DriverInstanceId = "d-1", Name = seed.DeviceName, DeviceConfig = "{}" }); + db.Tags.Add(new Tag + { + TagId = "tag-speed", DeviceId = "dev-1", Name = "speed", DataType = "Int16", + AccessLevel = TagAccessLevel.Read, TagConfig = CleanModbus, + }); + + db.DriverInstances.Add(new DriverInstance + { + DriverInstanceId = "d-calc", ClusterId = "", RawFolderId = "rf-plant", Name = "calc", + DriverType = DriverTypeNames.Calculation, DriverConfig = "{}", + }); + db.Devices.Add(new Device { DeviceId = "dev-calc", DriverInstanceId = "d-calc", Name = "cdev", DeviceConfig = "{}" }); + db.Tags.Add(new Tag + { + TagId = "tag-calc", DeviceId = "dev-calc", Name = "sum", DataType = "Double", + AccessLevel = TagAccessLevel.Read, TagConfig = "{\"scriptId\":\"s-calc\"}", + }); + + db.UnsAreas.Add(new UnsArea { UnsAreaId = "area-1", ClusterId = "", Name = "area" }); + db.UnsLines.Add(new UnsLine { UnsLineId = "line-1", UnsAreaId = "area-1", Name = "line" }); + + db.Scripts.Add(new Script { ScriptId = "s-pred", Name = "pred", SourceCode = seed.PredicateSource, SourceHash = "h-pred" }); + db.Scripts.Add(new Script { ScriptId = "s-calc", Name = "calc", SourceCode = seed.CalcSource, SourceHash = "h-calc" }); + for (var i = 1; i <= seed.Equipments; i++) + { + var uuid = Guid.NewGuid(); + var equipmentId = DraftValidator.DeriveEquipmentId(uuid); + db.Equipment.Add(new Equipment + { + EquipmentUuid = uuid, EquipmentId = equipmentId, Name = $"eq{i}", UnsLineId = "line-1", MachineCode = $"m{i}", + }); + db.UnsTagReferences.Add(new UnsTagReference { UnsTagReferenceId = $"ref-{i}", EquipmentId = equipmentId, TagId = "tag-speed" }); + var vtScriptId = seed.SharedVtScript ? "s-vt" : $"s-vt-{i}"; + if (!seed.SharedVtScript || i == 1) + db.Scripts.Add(new Script { ScriptId = vtScriptId, Name = vtScriptId, SourceCode = seed.VtSource, SourceHash = "h-" + vtScriptId }); + db.VirtualTags.Add(new VirtualTag + { + VirtualTagId = $"vt-{i}", EquipmentId = equipmentId, Name = "doubled", DataType = "Double", + ScriptId = vtScriptId, Enabled = seed.VtEnabled, + }); + db.ScriptedAlarms.Add(new ScriptedAlarm + { + ScriptedAlarmId = $"al-{i}", EquipmentId = equipmentId, Name = "high", AlarmType = "LimitAlarm", + MessageTemplate = "speed high", PredicateScriptId = "s-pred", Enabled = seed.AlarmEnabled, + }); + } + db.SaveChanges(); + return dbFactory; + } + + private StartDeploymentResult Deploy( + IDbContextFactory dbFactory, IDeployScriptChecker? checker, + ScriptCompileGateMode mode = ScriptCompileGateMode.Error, bool expectDispatch = true) + { + var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(AdminOperationsActor.Props( + dbFactory, coordinator.Ref, Enumerable.Empty(), + scriptChecker: checker, scriptCompileGateMode: mode)); + actor.Tell(new StartDeployment("joe", CorrelationId.NewId())); + if (expectDispatch) coordinator.ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + else coordinator.ExpectNoMsg(TimeSpan.FromMilliseconds(300), TestContext.Current.CancellationToken); + return ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken); + } + + /// Records every request and answers from a rule; optionally throws. + private sealed class RecordingChecker(Func>? rule = null, bool @throw = false) + : IDeployScriptChecker + { + public ConcurrentQueue Requests { get; } = new(); + + public ConcurrentQueue> Calls { get; } = new(); + + public IReadOnlyList Check(IReadOnlyList requests, CancellationToken cancellationToken = default) + { + Calls.Enqueue(requests.ToList()); + foreach (var r in requests) Requests.Enqueue(r); + if (@throw) throw new InvalidOperationException("checker exploded"); + return requests.Select(r => new DeployScriptCheckResult(r, rule?.Invoke(r) ?? [])).ToList(); + } + } + + [Fact] + public void A_legitimate_draft_deploys_clean_positive_control() + { + var checker = new RoslynDeployScriptChecker(); + var reply = Deploy(SeedDraft(new Seed()), checker); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + (reply.Message ?? string.Empty).ShouldNotContain("does not compile"); + checker.CompilesPerformed.ShouldBeGreaterThan(0); // the gate really ran + } + + [Fact] + public void A_forbidden_api_blocks_the_deploy_in_error_mode_naming_the_script_and_its_users() + { + var dbFactory = SeedDraft(new Seed(VtSource: Forbidden, Equipments: 2)); + var reply = Deploy(dbFactory, new RoslynDeployScriptChecker(), expectDispatch: false); + + reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); + reply.Message.ShouldNotBeNull(); + reply.Message.ShouldContain(DeployScriptGate.ErrorCode); + reply.Message.ShouldContain("script 's-vt'"); + reply.Message.ShouldContain("VirtualTag 'vt-1'"); + reply.Message.ShouldContain("VirtualTag 'vt-2'"); // one finding, both users + reply.Message.ShouldContain("sandbox violation"); + using var verify = dbFactory.CreateDbContext(); + verify.Deployments.Count().ShouldBe(0); + } + + [Fact] + public void Error_is_the_default_mode() + { + var dbFactory = SeedDraft(new Seed(VtSource: Forbidden)); + var coordinator = CreateTestProbe(); + var actor = Sys.ActorOf(AdminOperationsActor.Props( + dbFactory, coordinator.Ref, Enumerable.Empty(), scriptChecker: new RoslynDeployScriptChecker())); + actor.Tell(new StartDeployment("joe", CorrelationId.NewId())); + ExpectMsg(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken) + .Outcome.ShouldBe(StartDeploymentOutcome.Rejected); + ServiceCollectionExtensions.ParseScriptCompileGateMode(null).ShouldBe(ScriptCompileGateMode.Error); + ServiceCollectionExtensions.ParseScriptCompileGateMode("Warning").ShouldBe(ScriptCompileGateMode.Error); + ServiceCollectionExtensions.ParseScriptCompileGateMode("7").ShouldBe(ScriptCompileGateMode.Error); + ServiceCollectionExtensions.ParseScriptCompileGateMode("warn").ShouldBe(ScriptCompileGateMode.Warn); + ServiceCollectionExtensions.ParseScriptCompileGateMode(" Off ").ShouldBe(ScriptCompileGateMode.Off); + } + + [Fact] + public void Warn_mode_accepts_and_surfaces_the_finding_in_the_message() + { + var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden)), new RoslynDeployScriptChecker(), ScriptCompileGateMode.Warn); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted); + reply.Message.ShouldNotBeNull(); + reply.Message.ShouldContain("script 's-vt'"); + reply.Message.ShouldContain("sandbox violation"); + } + + [Fact] + public void Each_seam_compiles_as_itself_a_value_script_used_as_a_predicate_is_refused() + { + // `return 1.5;` is a fine VirtualTag / Calculation body and a non-bool predicate. + const string returnsDouble = "return 1.5;"; + var reply = Deploy(SeedDraft(new Seed(VtSource: returnsDouble, PredicateSource: returnsDouble, CalcSource: returnsDouble)), + new RoslynDeployScriptChecker(), expectDispatch: false); + + reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); + reply.Message.ShouldNotBeNull(); + reply.Message.ShouldContain("script 's-pred' does not compile as a scripted-alarm predicate"); + reply.Message.ShouldContain("ScriptedAlarm 'al-1'"); + reply.Message.ShouldNotContain("script 's-vt'"); + reply.Message.ShouldNotContain("script 's-calc'"); + } + + [Fact] + public void A_forbidden_calculation_script_names_the_calculation_tag() + { + var reply = Deploy(SeedDraft(new Seed(CalcSource: Forbidden)), new RoslynDeployScriptChecker(), expectDispatch: false); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); + reply.Message.ShouldNotBeNull(); + reply.Message.ShouldContain("script 's-calc' does not compile as a Calculation script"); + reply.Message.ShouldContain("Calculation tag 'tag-calc' (plant/calc/cdev/sum)"); + } + + [Fact] + public void Disabled_users_are_not_checked_they_never_compile_at_runtime() + { + var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden, PredicateSource: Forbidden, VtEnabled: false, AlarmEnabled: false)), + new RoslynDeployScriptChecker()); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + } + + [Fact] + public void An_absent_checker_skips_the_gate() + { + var reply = Deploy(SeedDraft(new Seed(VtSource: Forbidden)), checker: null); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + } + + [Fact] + public void Mode_off_skips_the_gate_and_never_calls_the_checker() + { + var checker = new RecordingChecker(_ => ["compile error: nope"]); + var reply = Deploy(SeedDraft(new Seed()), checker, ScriptCompileGateMode.Off); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + checker.Requests.ShouldBeEmpty(); + } + + [Fact] + public void Equip_tokens_resolve_before_compiling_and_a_template_is_sent_once_for_every_equipment() + { + // Three equipments share one VT template: substitution only rewrites escape-free literal text, so the gate + // sends the template once per seam rather than three resolved copies. + var checker = new RecordingChecker(); + var reply = Deploy(SeedDraft(new Seed(Equipments: 3)), checker); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted, reply.Message); + + // Two passes: the warm-up outside the transaction, then the authoritative in-snapshot pass. + checker.Calls.Count.ShouldBe(2); + var inSnapshotPass = checker.Calls.Last(); + // One request per (seam, source): the shared template once — no per-equipment resolved copies. + inSnapshotPass.Count.ShouldBe(3); + inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); + inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.AlarmPredicate, LegitPredicate)); + inSnapshotPass.ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.Calculation, LegitCalc)); + // The warm-up asked for the same template, so the in-snapshot pass is a cache hit on a real checker. + checker.Calls.First().ShouldContain(new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, Legit)); + } + + [Fact] + public async Task Collected_uses_resolve_equip_exactly_as_the_compose_seams_do() + { + // The draft-side collection on its own: the substitution the gate reasons about is the compose seams' one. + var dbFactory = SeedDraft(new Seed(Equipments: 1)); + using var db = dbFactory.CreateDbContext(); + var draft = await DraftSnapshotFactory.FromConfigDbAsync(db, TestContext.Current.CancellationToken); + var uses = DeployScriptGate.CollectUses(draft); + + var vt = uses.Single(u => u.Kind == ScriptContextKind.VirtualTag); + vt.CompileSource.ShouldBe(Legit); // equivalent template sent… + EquipmentScriptPaths.SubstituteEquipmentToken(Legit, + new Dictionary { ["speed"] = "plant/drv/dev/speed" }) + .ShouldContain("ctx.GetTag(\"plant/drv/dev/speed\")"); // …for what the seams will run + uses.Single(u => u.Kind == ScriptContextKind.AlarmPredicate).UsedBy.ShouldContain("ScriptedAlarm 'al-1'"); + uses.Single(u => u.Kind == ScriptContextKind.Calculation).UsedBy.ShouldContain("Calculation tag 'tag-calc'"); + } + + /// + /// A RawPath segment may legally contain a backslash, and substitution pastes the RawPath into a C# string + /// literal — so {{equip}}/speed over a device named de\qv becomes an invalid escape the runtime + /// refuses to compile. The template compiles fine; only compiling the RESOLVED source (what the gate does + /// whenever substitution is not provably compile-neutral) catches it. + /// + [Fact] + public void An_equip_substitution_that_breaks_the_literal_is_caught_by_compiling_the_resolved_source() + { + var reply = Deploy(SeedDraft(new Seed(DeviceName: @"de\qv")), new RoslynDeployScriptChecker(), expectDispatch: false); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Rejected); + reply.Message.ShouldNotBeNull(); + reply.Message.ShouldContain("script 's-vt' does not compile as a VirtualTag script"); + reply.Message.ShouldContain("compile error"); + reply.Message.ShouldContain("script 's-pred'"); // the predicate resolves through the same reference + } + + [Fact] + public void The_cache_makes_a_redeploy_compile_nothing() + { + var checker = new RoslynDeployScriptChecker(); + var dbFactory = SeedDraft(new Seed(Equipments: 2)); + Deploy(dbFactory, checker).Outcome.ShouldBe(StartDeploymentOutcome.Accepted); + var afterFirst = checker.CompilesPerformed; + afterFirst.ShouldBeGreaterThan(0); + + // Close the first deployment so the next one is not refused as in-flight. + using (var db = dbFactory.CreateDbContext()) + { + foreach (var d in db.Deployments) d.Status = DeploymentStatus.Sealed; + db.SaveChanges(); + } + Deploy(dbFactory, checker).Outcome.ShouldBe(StartDeploymentOutcome.Accepted); + checker.CompilesPerformed.ShouldBe(afterFirst); + } + + [Fact] + public void An_internal_checker_failure_never_blocks_the_deploy() + { + var reply = Deploy(SeedDraft(new Seed()), new RecordingChecker(@throw: true)); + reply.Outcome.ShouldBe(StartDeploymentOutcome.Accepted); + reply.Message.ShouldNotBeNull(); + reply.Message.ShouldContain("script compile gate skipped"); + } +}