c00ebf1320
ForbiddenTypeAnalyzer inverted from a BCL deny-list to an allow-list of types/members (ctx API, value/time/maths types, collections, LINQ-to-objects, string/Regex/formatting; System.Type and CancellationToken with member allow-lists). Every named type, expression type and used member (incl. return type and generic args) is checked; __makeref/__arglist, lock and extern local functions refused syntactically. ScriptSandbox references only eight BCL assemblies (defence in depth). The Monaco editor and the publish gate share both, so parity holds. Tests: theory over the K-1 snippets (publish gate + analyzer alone against the full host), every-public-type enumeration, shipped-sample + idiom regression, editor/publish parity. Differential over every script-shaped literal in src/tests: all 511 previously-compiling scripts still compile (one expression-tree test intentionally refused). PE cache signing by the host (option 4) deferred as a follow-up. Co-Authored-By: Claude <noreply@anthropic.com>
121 lines
7.1 KiB
C#
121 lines
7.1 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.AdminUI.ScriptAnalysis;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.ScriptAnalysis;
|
|
|
|
public sealed class DiagnoseTests
|
|
{
|
|
private static readonly ScriptAnalysisService Svc = new();
|
|
private static IReadOnlyList<DiagnosticMarker> Diag(string code) => Svc.Diagnose(new DiagnoseRequest(code)).Markers;
|
|
|
|
[Fact] public void Clean_script_has_no_markers()
|
|
=> Diag("""return (double)ctx.GetTag("A").Value * 2.0;""").ShouldBeEmpty();
|
|
|
|
[Fact] public void Roslyn_error_is_reported_on_user_line_1()
|
|
{
|
|
var m = Diag("return ctx.NoSuchMember();");
|
|
m.ShouldNotBeEmpty();
|
|
m.ShouldContain(x => x.Severity == 8);
|
|
m.First(x => x.Severity == 8).StartLineNumber.ShouldBe(1); // #line 1 → user coords (GetMappedLineSpan)
|
|
}
|
|
|
|
[Fact] public void Roslyn_error_maps_to_correct_user_line()
|
|
{
|
|
// error on the THIRD user line — proves mapping isn't off by the preamble height
|
|
var m = Diag("var a = 1;\nvar b = 2;\nreturn ctx.Nope();");
|
|
m.ShouldContain(x => x.Severity == 8 && x.StartLineNumber == 3);
|
|
}
|
|
|
|
[Fact] public void Forbidden_or_unresolved_dangerous_type_is_flagged()
|
|
=> Diag("""var c = new System.Net.Http.HttpClient(); return 0;""")
|
|
.ShouldContain(x => x.Severity == 8);
|
|
|
|
// Sandbox hardening parity (R05:10): the editor runs the SAME ForbiddenTypeAnalyzer the publish gate
|
|
// runs, so every newly-denied form must surface as an OTSCRIPT_FORBIDDEN marker here — editor accepts
|
|
// ⇔ publish accepts. One case per deny mechanism (namespace, member, type), plus the allow-list.
|
|
[Theory]
|
|
[InlineData("""new System.Threading.SemaphoreSlim(0).Wait(); return 0;""")] // System.Threading namespace
|
|
[InlineData("""System.Threading.SpinWait.SpinUntil(() => false); return 0;""")]
|
|
[InlineData("""var t = System.Type.GetType("System.IO.File"); return t is null ? 0 : 1;""")] // forbidden member
|
|
[InlineData("""return typeof(string).GetMethods().Length;""")]
|
|
[InlineData("""var o = System.Runtime.CompilerServices.RuntimeHelpers.GetUninitializedObject(typeof(string)); return 0;""")] // forbidden type
|
|
public void Hardened_sandbox_forms_are_flagged_in_the_editor(string code)
|
|
=> Diag(code).ShouldContain(x => x.Code == "OTSCRIPT_FORBIDDEN" && x.Severity == 8);
|
|
|
|
[Theory]
|
|
[InlineData("""var t = System.Threading.CancellationToken.None; return t.IsCancellationRequested ? 1 : 0;""")]
|
|
[InlineData("""var x = 41; System.Threading.Interlocked.Increment(ref x); return x;""")]
|
|
[InlineData("""var x = 42; return System.Threading.Volatile.Read(ref x);""")]
|
|
[InlineData("""object o = 42; return o.GetType().IsValueType ? 1 : 0;""")]
|
|
[InlineData("""ctx.CancellationToken.ThrowIfCancellationRequested(); return ctx.CancellationToken.IsCancellationRequested ? 1 : 0;""")]
|
|
public void Allow_listed_forms_are_not_flagged_in_the_editor(string code)
|
|
=> Diag(code).ShouldBeEmpty();
|
|
|
|
// lmxopcua#971 (review 2026-12-02 K-1): the allow-list sandbox. Each bypass the old deny-list let through is now an
|
|
// error marker in the editor — OTSCRIPT_FORBIDDEN where the API still binds against the narrowed reference set,
|
|
// a compiler error where it no longer binds at all — and the editor's verdict matches the publish gate's.
|
|
[Theory]
|
|
[InlineData("""var g = (Func<string, Type>)Delegate.CreateDelegate(typeof(Func<string, Type>), typeof(Type), "GetType"); return 0;""", true)]
|
|
[InlineData("""Serilog.Log.Logger = Serilog.Core.Logger.None; return 0;""", true)]
|
|
[InlineData("""return typeof(int).Assembly.Location;""", true)]
|
|
[InlineData("""ctx.CancellationToken.Register(() => { }); return 0;""", true)]
|
|
[InlineData("""Func<int> f = () => 1; return f.DynamicInvoke();""", true)]
|
|
[InlineData("""int i = 1; var r = __makeref(i); return 0;""", true)]
|
|
[InlineData("""return System.Xml.Linq.XDocument.Load("/etc/hosts").ToString();""", false)]
|
|
[InlineData("""System.Formats.Tar.TarFile.CreateFromDirectory("/tmp", "/tmp/x.tar", false); return 0;""", false)]
|
|
[InlineData("""var t = new System.Timers.Timer(50); t.Start(); return 0;""", false)]
|
|
[InlineData("""return Enumerable.Range(0, 100).AsParallel().Sum();""", false)]
|
|
[InlineData("""return new System.Security.Cryptography.X509Certificates.X509Store().Name;""", false)]
|
|
public void K1_bypass_is_an_error_marker_in_the_editor(string code, bool bindsAndIsForbidden)
|
|
{
|
|
var markers = Diag(code);
|
|
if (bindsAndIsForbidden) markers.ShouldContain(x => x.Code == "OTSCRIPT_FORBIDDEN" && x.Severity == 8);
|
|
else markers.ShouldContain(x => x.Severity == 8);
|
|
}
|
|
|
|
// Editor ⇔ publish parity over both refused and accepted scripts: an error marker exactly when the publish gate
|
|
// (ScriptEvaluator over the same VirtualTagContext) refuses.
|
|
[Theory]
|
|
[InlineData("""var g = (Func<string, Type>)Delegate.CreateDelegate(typeof(Func<string, Type>), typeof(Type), "GetType"); return 0;""")]
|
|
[InlineData("""return typeof(int).Assembly.Location;""")]
|
|
[InlineData("""return System.Xml.Linq.XDocument.Load("/etc/hosts").ToString();""")]
|
|
[InlineData("""lock (typeof(string)) { } return 0;""")]
|
|
[InlineData("""return typeof(int).Name + System.Math.Round(1.25, 1).ToString(System.Globalization.CultureInfo.InvariantCulture);""")]
|
|
[InlineData("""var d = new System.Collections.Generic.Dictionary<string, int> { ["a"] = 1 }; return d.Values.Sum();""")]
|
|
[InlineData("""return System.Text.RegularExpressions.Regex.IsMatch("T-1", @"T-\d") ? ctx.Now.Hour : 0;""")]
|
|
[InlineData("""ctx.Logger.Information("v {V}", ctx.GetTag("A").Value); return ctx.GetTag("A").StatusCode == 0u;""")]
|
|
public void Editor_and_publish_gate_agree(string code)
|
|
{
|
|
bool publishRefuses;
|
|
try
|
|
{
|
|
ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptEvaluator<ZB.MOM.WW.OtOpcUa.Core.VirtualTags.VirtualTagContext, object?>.CompileToImage(code);
|
|
publishRefuses = false;
|
|
}
|
|
catch (Exception ex) when (ex is ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptSandboxViolationException
|
|
or ZB.MOM.WW.OtOpcUa.Core.Scripting.CompilationErrorException)
|
|
{
|
|
publishRefuses = true;
|
|
}
|
|
Diag(code).Any(x => x.Severity == 8).ShouldBe(publishRefuses);
|
|
}
|
|
|
|
[Fact] public void Dynamic_tag_path_is_flagged()
|
|
=> Diag("""var p = "A"; return ctx.GetTag(p).Value;""")
|
|
.ShouldContain(x => x.Message.Contains("literal"));
|
|
|
|
[Fact] public void Missing_return_does_not_produce_a_phantom_preamble_marker()
|
|
=> Diag("var x = 1;").ShouldNotContain(m => m.Code == "CS0161");
|
|
|
|
[Fact] public void Empty_code_has_no_markers()
|
|
=> Diag("").ShouldBeEmpty();
|
|
|
|
[Fact] public void Crlf_source_maps_dynamic_path_to_the_correct_line()
|
|
{
|
|
// \r\n line endings; the dynamic-path rejection must land on user line 3, not be column-shifted.
|
|
var m = Diag("var a = 1;\r\nvar b = 2;\r\nreturn ctx.GetTag(b > 0 ? \"x\" : \"y\").Value;");
|
|
m.ShouldContain(x => x.Message.Contains("literal") && x.StartLineNumber == 3);
|
|
}
|
|
}
|