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\");")] [InlineData("if (ctx.GetTag(\"A\").Value is null) return 1;")] // CS0161 on the wrapper (lmxopcua#1063) [InlineData("var x = 1;")] 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); } /// /// lmxopcua#1065: a Calculation tag is raw/device-level — no equipment — and its seam never substitutes /// {{equip}}, so a Calculation script carrying it in a path literal is refused (it used to deploy and read /// Bad forever). Every literal form, the passthrough mirror shape included (which never reaches Roslyn). /// [Theory] [InlineData("return ctx.GetTag(\"{{equip}}/Speed\").Value;")] // passthrough shape [InlineData("return (double)ctx.GetTag(\"{{equip}}/Speed\").Value * 2;")] [InlineData("return ctx.GetTag(@\"{{equip}}/Speed\").Value;")] [InlineData("return ctx.GetTag($\"{{equip}}/Speed\").Value;")] [InlineData("return ctx.GetTag(\"Plant/{{equip}}/Speed\").Value;")] [InlineData("ctx.SetVirtualTag(\"{{equip}}/Out\", 1); return 1;")] public void An_equip_token_in_a_calculation_script_is_refused(string source) { var verdict = CheckOne(new RoslynDeployScriptChecker(), ScriptContextKind.Calculation, source); verdict.Passed.ShouldBeFalse(); verdict.Problems.Single().ShouldStartWith("equip token in a Calculation script — "); verdict.Problems.Single().ShouldContain("no equipment"); } [Fact] public void The_calculation_equip_rule_is_kind_specific_and_not_shared_through_the_cache() { // VirtualTag and Calculation share one cached compile verdict; the #1065 rule must not leak through it in // either order. Positive control: the regular-literal template is the normal VirtualTag form. const string source = "return (double)ctx.GetTag(\"{{equip}}/Speed\").Value * 2;"; var vtFirst = new RoslynDeployScriptChecker(); CheckOne(vtFirst, ScriptContextKind.VirtualTag, source).Passed.ShouldBeTrue(); CheckOne(vtFirst, ScriptContextKind.Calculation, source).Passed.ShouldBeFalse(); var calcFirst = new RoslynDeployScriptChecker(); CheckOne(calcFirst, ScriptContextKind.Calculation, source).Passed.ShouldBeFalse(); CheckOne(calcFirst, ScriptContextKind.VirtualTag, source).Passed.ShouldBeTrue(); // One batch with both kinds answers each in request order. var both = vtFirst.Check( [new DeployScriptCheckRequest(ScriptContextKind.Calculation, source), new DeployScriptCheckRequest(ScriptContextKind.VirtualTag, source)], TestContext.Current.CancellationToken); both[0].Passed.ShouldBeFalse(); both[1].Passed.ShouldBeTrue(); } [Fact] public void A_calculation_script_without_the_token_is_unaffected_positive_control() { var checker = new RoslynDeployScriptChecker(); CheckOne(checker, ScriptContextKind.Calculation, "return ctx.GetTag(\"Plant/Dev/Speed\").Value;").Passed.ShouldBeTrue(); // The token in a non-path string (a log message) is not a path and is not refused. CheckOne(checker, ScriptContextKind.Calculation, "ctx.Logger.Information(\"{{equip}} n/a\"); return 1;").Passed.ShouldBeTrue(); } }