Files
lmxopcua/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptSandboxBuildTests.cs
T
Joseph Doherty c00ebf1320 fix(scripting): #971 the script sandbox is an allow-list — the K-1 bypasses (CreateDelegate, Expressions, XML/Tar I/O, X509Store, Timers/BackgroundWorker/AsParallel, Serilog.Log) are refused
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>
2026-12-03 10:09:39 -05:00

99 lines
4.8 KiB
C#

using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Scripting;
namespace ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests;
/// <summary>
/// Covers the <see cref="ScriptSandbox.Build"/> argument-validation guards. The
/// guards are the only call-site protection against a typo / mis-wired context
/// type silently producing a sandbox missing the concrete context's assembly
/// reference; without coverage, the guards could be deleted by a refactor without
/// any test failing. (Core.Scripting-011.)
/// </summary>
[Trait("Category", "Unit")]
public sealed class ScriptSandboxBuildTests
{
/// <summary>Verifies that a null context type throws ArgumentNullException.</summary>
[Fact]
public void Null_context_type_throws_ArgumentNullException()
{
Should.Throw<ArgumentNullException>(() => ScriptSandbox.Build(null!));
}
/// <summary>Verifies that a non-ScriptContext type throws ArgumentException.</summary>
[Fact]
public void Non_ScriptContext_type_throws_ArgumentException()
{
// ScriptSandbox must reject types that don't derive from ScriptContext —
// ScriptGlobals<TContext> is constrained where TContext : ScriptContext, so
// sneaking a non-derived type past Build would later blow up inside Roslyn.
Should.Throw<ArgumentException>(() => ScriptSandbox.Build(typeof(string)))
.ParamName.ShouldBe("contextType");
}
/// <summary>Verifies that the abstract ScriptContext base type is accepted by the sandbox builder.</summary>
[Fact]
public void Abstract_ScriptContext_base_type_is_accepted()
{
// The base ScriptContext type satisfies the IsAssignableFrom check, so the
// factory must not reject it even though it cannot be instantiated directly.
// Callers wiring a base-typed sandbox up for diagnostics rely on this.
var options = ScriptSandbox.Build(typeof(ScriptContext));
options.ShouldNotBeNull();
}
/// <summary>Verifies that a concrete subclass is accepted and its assembly is referenced in the sandbox.</summary>
[Fact]
public void Concrete_subclass_is_accepted_and_its_assembly_referenced()
{
// The concrete context type's assembly must end up in the allow-listed
// references — otherwise Roslyn cannot resolve ScriptGlobals<TContext> at
// compile. We can't easily inspect the ScriptOptions metadata references
// by-assembly cross-version, so we exercise the end-to-end path instead: a
// script compiled against FakeScriptContext must successfully reach a
// FakeScriptContext member.
var evaluator = ScriptEvaluator<FakeScriptContext, double>.Compile(
"""return (double)ctx.GetTag("X").Value;""");
evaluator.ShouldNotBeNull();
}
/// <summary>#603: the BCL reference set is built once per process, so two Build calls share the same
/// <c>MetadataReference</c> instances rather than re-reading ~170 DLLs per compile.</summary>
[Fact]
public void Build_reuses_metadata_reference_instances_across_calls()
{
var first = ScriptSandbox.Build(typeof(ScriptContext));
var second = ScriptSandbox.Build(typeof(ScriptContext));
first.References.Count.ShouldBeGreaterThan(ScriptSandbox.BclAssemblyNames.Count);
first.References.Count.ShouldBe(second.References.Count);
for (var i = 0; i < first.References.Count; i++)
ReferenceEquals(first.References[i], second.References[i]).ShouldBeTrue($"reference {i} was rebuilt");
}
/// <summary>
/// lmxopcua#971: the BCL half of the reference set is exactly <see cref="ScriptSandbox.BclAssemblyNames"/> — every
/// listed assembly is found, and nothing carrying I/O, networking, XML, archives, expression trees, component
/// model, crypto, the console or processes is referenced.
/// </summary>
[Fact]
public void Bcl_reference_set_is_the_narrow_listed_set()
{
var bcl = ScriptSandbox.ReferenceIdentities(typeof(ScriptContext))
.Where(i => i.EndsWith(".dll", StringComparison.Ordinal))
.Select(Path.GetFileName)
.ToArray();
bcl.Order(StringComparer.Ordinal).ShouldBe(ScriptSandbox.BclAssemblyNames.Order(StringComparer.Ordinal));
string[] mustBeAbsent =
[
"System.Xml.Linq.dll", "System.Private.Xml.dll", "System.Formats.Tar.dll", "System.Linq.Expressions.dll",
"System.ComponentModel.dll", "System.Security.Cryptography.dll", "System.Console.dll",
"System.Diagnostics.Process.dll", "System.Net.Http.dll", "System.IO.FileSystem.dll", "System.Linq.Parallel.dll",
"System.Linq.Queryable.dll", "Microsoft.Win32.Registry.dll", "mscorlib.dll",
];
bcl.ShouldNotContain(n => mustBeAbsent.Contains(n));
}
}