6e912bb070
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.
164 lines
8.0 KiB
C#
164 lines
8.0 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// 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
|
|
/// <c>VirtualTagContext → object?</c>, a scripted-alarm predicate as <c>AlarmPredicateContext → bool</c> after the
|
|
/// dependency extractor), and cached so a redeploy does not re-enter Roslyn.
|
|
/// </summary>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parity with the runtime compile: <see cref="ScriptEvaluator{TContext, TResult}.Verify"/> shares the
|
|
/// compilation factory with <see cref="ScriptEvaluator{TContext, TResult}.CompileToImage"/>, so for every
|
|
/// sample the gate passes exactly when the runtime compile succeeds.
|
|
/// </summary>
|
|
[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<TContext, TResult>(string s) where TContext : ScriptContext
|
|
{
|
|
try { _ = ScriptEvaluator<TContext, TResult>.CompileToImage(s); return true; }
|
|
catch (CompilationErrorException) { return false; }
|
|
catch (ScriptSandboxViolationException) { return false; }
|
|
}
|
|
|
|
CheckOne(checker, ScriptContextKind.VirtualTag, source).Passed
|
|
.ShouldBe(RuntimeCompiles<VirtualTagContext, object?>(source));
|
|
var predicateRuntime = DependencyExtractor.Extract(source).IsValid && RuntimeCompiles<AlarmPredicateContext, bool>(source);
|
|
CheckOne(checker, ScriptContextKind.AlarmPredicate, source).Passed.ShouldBe(predicateRuntime);
|
|
}
|
|
}
|