Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/RoslynDeployScriptCheckerTests.cs
T
Joseph Doherty 73f49eaf32 fix(scripting): #1063 one compile-refusal authority for editor and deploy gate (ScriptCompileRules + the runtime's own wrapper text) — CS0161 and wrapper injection are now flagged in the editor; #1065 {{equip}} in a Calculation script is refused by the gate and by a new Calculation editor mode
#1063: the Monaco diagnostics dropped every Roslyn error located in the synthesized
wrapper as 'phantom', so CS0161 (not all code paths return a value, pinned on Run)
passed the editor and failed the deploy gate. ScriptCompileRules (Core.Scripting) now
states which diagnostics refuse (every Error, wherever located; LMX001/002 injection)
and which sources skip the compile (blank/passthrough value scripts); ScriptEvaluator
and the editor both use it, and the editor wraps with ScriptEvaluator.WrapperPreamble/
WrapperSuffix instead of its own copy. Wrapper-located refusals are drawn on the
script's last line. EditorGateParityTests runs one corpus through editor and gate in
all three modes.

#1065: a Calculation tag is raw/device-level with no equipment and its seam never
substitutes {{equip}}, so such a script deployed clean and read Bad forever. Refused
rather than substituted: EquipTokenLiteralScanner.FindInCalculation is run by
RoslynDeployScriptChecker for every Calculation use (before the passthrough shortcut,
outside the shared VT/Calc cache) and by the editor in the new 'calculation' mode
(Calculation tag editor; ScriptEdit defaults to it when a Calculation tag uses the
script).
2026-12-03 16:47:14 -05:00

217 lines
11 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\");")]
[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<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);
}
/// <summary>
/// lmxopcua#1065: a Calculation tag is raw/device-level — no equipment — and its seam never substitutes
/// <c>{{equip}}</c>, 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).
/// </summary>
[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();
}
}