From e840ec1fbcbdfaf122b281251ce5f0b5e1ad2015 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 15:05:40 -0500 Subject: [PATCH] =?UTF-8?q?fix(scripting):=20#1056=20refuse=20a=20{{equip}?= =?UTF-8?q?}=20token=20in=20a=20verbatim/raw/interpolated=20path=20literal?= =?UTF-8?q?=20=E2=80=94=20editor=20diagnostic=20+=20deploy-gate=20refusal?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/ScriptEditor.md | 8 +- .../EquipTokenLiteralScanner.cs | 85 +++++++++++++++++++ .../RoslynDeployScriptChecker.cs | 7 ++ .../ScriptAnalysis/ScriptAnalysisService.cs | 4 + .../EquipTokenLiteralScannerTests.cs | 80 +++++++++++++++++ .../EquipLiteralDiagnosticTests.cs | 29 +++++++ 6 files changed, 211 insertions(+), 2 deletions(-) create mode 100644 src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs create mode 100644 tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/EquipTokenLiteralScannerTests.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipLiteralDiagnosticTests.cs diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index b1a780d86..7d896e49e 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -527,8 +527,12 @@ hold `\`, `"`, braces, line breaks or non-ASCII text (`RawPaths.ValidateSegment` A `` with a malformed escape (`\e`) is left as written for the compiler to report. Only regular `"…"` literals are path literals: a `{{equip}}/…` token inside a verbatim (`@"…"`), -interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted** (and not checked) — keep the -token in a regular literal. +interpolated (`$"…"`) or raw (`"""…"""`) literal is **not substituted**, so since #1056 it is refused +instead of silently reading Bad at runtime: the editor flags it (`OTSCRIPT_EQUIPLITERAL`, an error) and +the deploy gate fails the script (`equip token not substituted — …`), both through +`EquipTokenLiteralScanner`. Keep the token in a regular literal. (Only a `ctx.GetTag` / +`ctx.SetVirtualTag` path argument is scanned; a `{{equip}}` token in a Calculation script is not +substituted in any literal form — the seam does no substitution.) --- diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs new file mode 100644 index 000000000..208eb3703 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/EquipTokenLiteralScanner.cs @@ -0,0 +1,85 @@ +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.CSharp.Syntax; +using Microsoft.CodeAnalysis.Text; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; + +/// +/// Finds ctx.GetTag(…) / ctx.SetVirtualTag(…) calls whose path argument carries the +/// {{equip}} token in a literal form the substitution does NOT rewrite (lmxopcua#1056). +/// +/// +/// +/// EquipmentScriptPaths.SubstituteEquipmentToken rewrites the token only inside a REGULAR "…" +/// path literal. A verbatim (@"…"), raw ("""…""") or interpolated ($"…") literal used to pass +/// the editor and the deploy gate and then reach the runtime with the token still in the path — the tag read +/// Bad for as long as it was deployed, with no error anywhere. Both the editor +/// (OTSCRIPT_EQUIPLITERAL) and the deploy gate () now run this +/// one scan and refuse such a script, so "the editor accepts ⇔ publish accepts" holds. +/// +/// +/// Same receiver guard as (a member access on the identifier ctx), so +/// comments, other receivers and a token in a string that is not a path argument are never flagged. +/// +/// +public static class EquipTokenLiteralScanner +{ + private const string EquipToken = "{{equip}}"; + + /// One offending path literal. + /// The offending literal's span in the scanned source. + /// The operator-facing explanation. + public sealed record Finding(TextSpan Span, string Message); + + /// The offending path literals of , in source order. + /// The script source (any {{equip}} token still unresolved is fine). + /// The findings; empty when none. + public static IReadOnlyList Find(string? source) + { + if (string.IsNullOrEmpty(source) || !source.Contains(EquipToken, StringComparison.Ordinal)) + return []; + var tree = CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(kind: SourceCodeKind.Script)); + var findings = new List(); + foreach (var inv in tree.GetRoot().DescendantNodes().OfType()) + { + if (inv.Expression is not MemberAccessExpressionSyntax + { + Expression: IdentifierNameSyntax { Identifier.ValueText: "ctx" }, + Name.Identifier.ValueText: "GetTag" or "SetVirtualTag", + } member) + continue; + if (inv.ArgumentList.Arguments.Count == 0) continue; + var path = inv.ArgumentList.Arguments[0].Expression; + var form = OffendingForm(path); + if (form is null) continue; + findings.Add(new Finding( + path.Span, + $"The {EquipToken} token is inside a {form} string literal in ctx.{member.Name.Identifier.ValueText}(...), " + + "where it is NOT substituted — the path would reach the runtime unresolved and read Bad. " + + $"Use a regular \"…\" literal: ctx.{member.Name.Identifier.ValueText}(\"{EquipToken}/\").")); + } + return findings; + } + + private static string? OffendingForm(ExpressionSyntax path) + { + switch (path) + { + case LiteralExpressionSyntax lit when lit.IsKind(SyntaxKind.StringLiteralExpression): + { + var text = lit.Token.Text; + var form = text.StartsWith("@\"", StringComparison.Ordinal) ? "verbatim" + : text.StartsWith("\"\"\"", StringComparison.Ordinal) ? "raw" + : null; + return form is not null && ((string?)lit.Token.Value ?? "").StartsWith(EquipToken, StringComparison.Ordinal) + ? form : null; + } + case InterpolatedStringExpressionSyntax interpolated + when interpolated.ToString().Contains(EquipToken, StringComparison.Ordinal): + return "interpolated"; + default: + return null; + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs index 4445cfffb..0a7fa361f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/RoslynDeployScriptChecker.cs @@ -112,6 +112,13 @@ public sealed class RoslynDeployScriptChecker : IDeployScriptChecker var source = request.Source ?? string.Empty; try { + // lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted, so the + // script would compile and then read a tag path that cannot resolve. The editor runs the same scan. + var unsubstituted = EquipTokenLiteralScanner.Find(source); + if (unsubstituted.Count > 0) + return new CachedVerdict( + ["equip token not substituted — " + string.Join("; ", unsubstituted.Select(f => f.Message))], + Cacheable: true); if (request.Kind == ScriptContextKind.AlarmPredicate) { var extraction = DependencyExtractor.Extract(source); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs index 9831c791f..48e8e9b45 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/ScriptAnalysis/ScriptAnalysisService.cs @@ -162,6 +162,10 @@ public sealed class ScriptAnalysisService // (3) DependencyExtractor — spans are offsets in the normalized user source; map directly. foreach (var r in DependencyExtractor.Extract(code).Rejections) markers.Add(ToUserMarker(code, r.Span, r.Message, "OTSCRIPT_DYNPATH")); + // (3b) lmxopcua#1056: a {{equip}} token in a verbatim/raw/interpolated path literal is never substituted — + // the deploy gate refuses it (RoslynDeployScriptChecker runs this same scan), so the editor does too. + foreach (var f in EquipTokenLiteralScanner.Find(code)) + markers.Add(ToUserMarker(code, f.Span, f.Message, "OTSCRIPT_EQUIPLITERAL")); // (4) ctx.SetVirtualTag(...) is inert at runtime — a WARNING (severity 4), never an error: publish // accepts the script, so the editor must too; the marker just puts the hover's caveat in the Problems list. foreach (var inv in SetVirtualTagCalls(tree.GetRoot(ct), preambleLength)) diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/EquipTokenLiteralScannerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/EquipTokenLiteralScannerTests.cs new file mode 100644 index 000000000..f7a49a6c8 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/EquipTokenLiteralScannerTests.cs @@ -0,0 +1,80 @@ +using Shouldly; +using Xunit; + +namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests; + +/// +/// lmxopcua#1056 — {{equip}}/<RefName> is only substituted inside a REGULAR "…" path literal. In a +/// verbatim (@"…"), raw ("""…""") or interpolated ($"…") literal the token used to be +/// silently left in the path, so the tag read Bad at runtime while the editor and the deploy gate were green. The +/// scanner finds those forms; the editor (OTSCRIPT_EQUIPLITERAL) and the deploy gate both refuse them. +/// +[Trait("Category", "Unit")] +public sealed class EquipTokenLiteralScannerTests +{ + [Theory] + [InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value;")] + [InlineData("return ctx.GetTag(\"\"\"{{equip}}/speed\"\"\").Value;")] + [InlineData("return ctx.GetTag($\"{{equip}}/speed\").Value;")] + [InlineData("return ctx.GetTag($@\"{{equip}}/speed\").Value;")] + [InlineData("ctx.SetVirtualTag(@\"{{equip}}/speed\", 1); return 0;")] + public void A_token_inside_a_non_regular_path_literal_is_found(string source) + { + var findings = EquipTokenLiteralScanner.Find(source); + findings.ShouldHaveSingleItem(); + findings[0].Message.ShouldContain("regular"); + source.Substring(findings[0].Span.Start, findings[0].Span.Length).ShouldContain("{{equip}}"); + } + + [Theory] + [InlineData("return ctx.GetTag(\"{{equip}}/speed\").Value;")] // the supported form + [InlineData("return ctx.GetTag(@\"Plant/Drv/speed\").Value;")] // verbatim without the token + [InlineData("return ctx.GetTag(\"A\").Value; // @\"{{equip}}/speed\"")] // a comment + [InlineData("var s = @\"{{equip}}/speed\"; return ctx.GetTag(\"A\").Value;")] // not a path argument + [InlineData("return other.GetTag(@\"{{equip}}/speed\");")] // not ctx + [InlineData("return ctx.GetTag($\"Plant/{1}\").Value;")] // interpolated, no token + [InlineData("return 1;")] + public void Everything_else_is_not_flagged_positive_controls(string source) + => EquipTokenLiteralScanner.Find(source).ShouldBeEmpty(); + + [Fact] + public void Every_offending_call_is_reported_in_source_order() + { + var findings = EquipTokenLiteralScanner.Find( + "var a = ctx.GetTag(@\"{{equip}}/a\"); var b = ctx.GetTag(\"{{equip}}/ok\"); var c = ctx.GetTag($\"{{equip}}/c\"); return 0;"); + findings.Count.ShouldBe(2); + findings[0].Span.Start.ShouldBeLessThan(findings[1].Span.Start); + } + + [Fact] + public void The_regular_literal_form_really_is_the_one_substitution_handles() + { + // Pins the premise: the same source with a regular literal substitutes, the verbatim one does not. + var map = new Dictionary { ["speed"] = "Plant/Drv/dev/speed" }; + ZB.MOM.WW.OtOpcUa.Commons.Types.EquipmentScriptPaths + .SubstituteEquipmentToken("return ctx.GetTag(\"{{equip}}/speed\").Value;", map) + .ShouldContain("Plant/Drv/dev/speed"); + ZB.MOM.WW.OtOpcUa.Commons.Types.EquipmentScriptPaths + .SubstituteEquipmentToken("return ctx.GetTag(@\"{{equip}}/speed\").Value;", map) + .ShouldContain("{{equip}}/speed"); + } + + [Theory] + [InlineData(ScriptContextKind.VirtualTag)] + [InlineData(ScriptContextKind.AlarmPredicate)] + public void The_deploy_gate_refuses_such_a_script(ScriptContextKind kind) + { + var source = kind == ScriptContextKind.AlarmPredicate + ? "return ctx.GetTag(@\"{{equip}}/speed\").Value is not null;" + : "return ctx.GetTag(@\"{{equip}}/speed\").Value;"; + var result = new RoslynDeployScriptChecker().Check( + [new DeployScriptCheckRequest(kind, source)], TestContext.Current.CancellationToken).Single(); + result.Passed.ShouldBeFalse(); + result.Problems.ShouldContain(p => p.Contains("{{equip}}") && p.Contains("regular")); + + // positive control: the supported spelling of the same script passes + var ok = new RoslynDeployScriptChecker().Check( + [new DeployScriptCheckRequest(kind, source.Replace("@\"", "\""))], TestContext.Current.CancellationToken).Single(); + ok.Passed.ShouldBeTrue(string.Join("; ", ok.Problems)); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipLiteralDiagnosticTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipLiteralDiagnosticTests.cs new file mode 100644 index 000000000..59ce2fc2d --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/ScriptAnalysis/EquipLiteralDiagnosticTests.cs @@ -0,0 +1,29 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis; + +namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis; + +/// lmxopcua#1056 — the editor refuses a {{equip}} token in a verbatim/raw/interpolated path literal, as the deploy gate does. +public sealed class EquipLiteralDiagnosticTests +{ + private static readonly ScriptAnalysisService Svc = new(); + + [Theory] + [InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value;", null)] + [InlineData("return ctx.GetTag(\"\"\"{{equip}}/speed\"\"\").Value;", null)] + [InlineData("return ctx.GetTag(@\"{{equip}}/speed\").Value is not null;", ScriptAnalysisModes.AlarmPredicate)] + public void A_token_in_a_non_regular_literal_is_an_error_marker_on_its_line(string code, string? mode) + { + var m = Svc.Diagnose(new DiagnoseRequest("var a = 1;\n" + code, Mode: mode), TestContext.Current.CancellationToken).Markers + .Single(x => x.Code == "OTSCRIPT_EQUIPLITERAL"); + m.Severity.ShouldBe(8); + m.StartLineNumber.ShouldBe(2); + m.Message.ShouldContain("regular"); + } + + [Fact] + public void The_regular_literal_form_is_not_flagged_positive_control() + => Svc.Diagnose(new DiagnoseRequest("return ctx.GetTag(\"{{equip}}/speed\").Value;"), TestContext.Current.CancellationToken).Markers + .ShouldNotContain(x => x.Code == "OTSCRIPT_EQUIPLITERAL"); +}