Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests/Scripts/ScriptCompilationServiceTests.cs
T
Joseph Doherty 1930f19b1a fix(test): relax exact compile-cache hit-count assertion to >= 1
SiteScriptCompileCache.Hits is a process-global counter; other test classes in
the assembly compile scripts concurrently (not in this serialized collection),
so an exact post-Clear count is non-deterministic under a full-assembly parallel
run. Assert.Same(r1,r2) remains the definitive proof of one shared Roslyn
compile. Integration-surfaced; belongs with plan R2-03 T5/T6.
2026-07-13 11:24:06 -04:00

207 lines
7.3 KiB
C#

using Microsoft.Extensions.Logging.Abstractions;
using ZB.MOM.WW.ScadaBridge.SiteRuntime.Scripts;
namespace ZB.MOM.WW.ScadaBridge.SiteRuntime.Tests.Scripts;
/// <summary>
/// WP-19: Script Trust Model tests — validates forbidden API detection and compilation.
///
/// As of the M3.3 consolidation, <c>ScriptCompilationService.ValidateTrustModel</c>
/// delegates its forbidden-API verdict to the shared authoritative
/// <c>ScriptAnalysis.ScriptTrustValidator</c>, which is stricter than SiteRuntime's
/// original deny-list: ALL of <c>System.Net</c> is forbidden (not just Sockets/Http),
/// plus reflection gateways, <c>dynamic</c>, <c>Activator</c>,
/// <c>System.Runtime.InteropServices</c> and <c>Microsoft.Win32</c>. Only
/// <c>System.Diagnostics.Process</c> is blocked under System.Diagnostics —
/// <c>Stopwatch</c> stays allowed. The real execution-path compile against
/// <c>ScriptGlobals</c> / <c>TriggerExpressionGlobals</c> is unchanged.
/// </summary>
[Collection("SiteScriptCompileCache")]
public class ScriptCompilationServiceTests
{
private readonly ScriptCompilationService _service;
public ScriptCompilationServiceTests()
{
_service = new ScriptCompilationService(NullLogger<ScriptCompilationService>.Instance);
}
[Fact]
public void Compile_ValidScript_Succeeds()
{
var result = _service.Compile("test", "1 + 1");
Assert.True(result.IsSuccess);
Assert.NotNull(result.CompiledScript);
Assert.Empty(result.Errors);
}
[Fact]
public void Compile_SameCodeTwice_SharesOneRoslynCompile()
{
SiteScriptCompileCache.Clear();
var r1 = _service.Compile("deploy-gate-copy", "return 1 + 1;");
var r2 = _service.Compile("prestart-copy", "return 1 + 1;");
Assert.True(r1.IsSuccess);
Assert.Same(r1.CompiledScript, r2.CompiledScript); // one compile, shared Script<T> (N4) — the definitive proof
// Hits is a process-global counter; other test classes in this assembly compile scripts
// concurrently (they are not in this serialized collection), so the exact post-Clear count
// is not deterministic under a full-assembly parallel run. The shared-Script<T> assertion
// above is the real proof of cache reuse; here we only require the second lookup registered
// a hit (>= 1) rather than pinning an exact global count.
Assert.True(SiteScriptCompileCache.Hits >= 1);
}
[Fact]
public void Compile_ScriptAndTriggerExpression_DoNotCrossContaminate()
{
SiteScriptCompileCache.Clear();
var script = _service.Compile("s", "1 > 0");
var trigger = _service.CompileTriggerExpression("t", "1 > 0");
Assert.NotSame(script.CompiledScript, trigger.CompiledScript); // different globals surfaces
}
[Fact]
public void Compile_InvalidSyntax_ReturnsErrors()
{
var result = _service.Compile("bad", "this is not valid C# {{{");
Assert.False(result.IsSuccess);
Assert.NotEmpty(result.Errors);
}
[Fact]
public void ValidateTrustModel_SystemIO_Forbidden()
{
var violations = _service.ValidateTrustModel("System.IO.File.ReadAllText(\"test\")");
Assert.NotEmpty(violations);
Assert.Contains(violations, v => v.Contains("System.IO"));
}
[Fact]
public void ValidateTrustModel_Process_Forbidden()
{
var violations = _service.ValidateTrustModel(
"System.Diagnostics.Process.Start(\"cmd\")");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Reflection_Forbidden()
{
var violations = _service.ValidateTrustModel(
"typeof(string).GetType().GetMethods(System.Reflection.BindingFlags.Public)");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Sockets_Forbidden()
{
var violations = _service.ValidateTrustModel(
"new System.Net.Sockets.TcpClient()");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_HttpClient_Forbidden()
{
var violations = _service.ValidateTrustModel(
"new System.Net.Http.HttpClient()");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_AsyncAwait_Allowed()
{
// System.Threading.Tasks should be allowed (async/await support)
var violations = _service.ValidateTrustModel(
"await System.Threading.Tasks.Task.Delay(100)");
Assert.Empty(violations);
}
[Fact]
public void ValidateTrustModel_CancellationToken_Allowed()
{
var violations = _service.ValidateTrustModel(
"System.Threading.CancellationToken.None");
Assert.Empty(violations);
}
[Fact]
public void ValidateTrustModel_CleanCode_NoViolations()
{
var code = @"
var x = 1 + 2;
var list = new List<int> { 1, 2, 3 };
var sum = list.Sum();
sum";
var violations = _service.ValidateTrustModel(code);
Assert.Empty(violations);
}
[Fact]
public void Compile_ForbiddenApi_FailsValidation()
{
var result = _service.Compile("evil", "System.IO.File.Delete(\"/tmp/test\")");
Assert.False(result.IsSuccess);
Assert.NotEmpty(result.Errors);
}
// ── M3.3: stricter shared-validator behavior ──
[Fact]
public void ValidateTrustModel_SystemNetDns_Forbidden()
{
// The shared validator forbids ALL of System.Net — not just Sockets/Http.
// System.Net.Dns was allowed under the old SiteRuntime list; now blocked.
var violations = _service.ValidateTrustModel(
"System.Net.Dns.GetHostName()");
Assert.NotEmpty(violations);
Assert.Contains(violations, v => v.Contains("System.Net"));
}
[Fact]
public void ValidateTrustModel_ReflectionGatewayViaPermittedType_Forbidden()
{
// typeof(x).Assembly.GetType(...) never spells a forbidden namespace, but
// the shared validator rejects the reflection-gateway members regardless of
// receiver — this was NOT caught by the old SiteRuntime list.
var violations = _service.ValidateTrustModel(
"typeof(string).Assembly.GetType(\"System.IO.File\")");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Dynamic_Forbidden()
{
var violations = _service.ValidateTrustModel("dynamic d = 1; return d;");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Activator_Forbidden()
{
var violations = _service.ValidateTrustModel(
"Activator.CreateInstance(typeof(string))");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_InteropServices_Forbidden()
{
var violations = _service.ValidateTrustModel(
"System.Runtime.InteropServices.Marshal.SizeOf<int>()");
Assert.NotEmpty(violations);
}
[Fact]
public void ValidateTrustModel_Stopwatch_Allowed()
{
// Only System.Diagnostics.Process is blocked under System.Diagnostics —
// Stopwatch stays allowed.
var violations = _service.ValidateTrustModel(
"var sw = System.Diagnostics.Stopwatch.StartNew(); return sw.ElapsedMilliseconds;");
Assert.Empty(violations);
}
}