using ZB.MOM.WW.ScadaBridge.ScriptAnalysis; namespace ZB.MOM.WW.ScadaBridge.ScriptAnalysis.Tests; /// /// Code review 2026-12-02 CMN-1 (WP1 task 1.1): the reflection-gateway check used to run /// only inside VisitMemberAccessExpression, so the same member reached through a /// conditional access (recv?.GetMethod(...) — a MemberBindingExpression) was /// never inspected, and Delegate.CreateDelegate turned the resulting /// MethodInfo into a callable delegate without naming any forbidden scope. These /// tests pin the ?. form of every .-form rejection in /// , plus the probe script from the review. /// public class ScriptTrustValidatorConditionalAccessTests { /// /// The review's probe: reach Type.GetType(string) and File.ReadAllText /// with nothing but ?. member bindings on permitted types and /// Delegate.CreateDelegate. The forbidden type is named only in a string /// literal. Before the fix this produced zero violations and compiled clean. /// private const string ProbeScript = """ var getType = (Func)Delegate.CreateDelegate( typeof(Func), typeof(Type)?.GetMethod("GetType", new[] { typeof(string) })); var fileType = getType("System.IO.File"); var read = (Func)Delegate.CreateDelegate( typeof(Func), fileType?.GetMethod("ReadAllText", new[] { typeof(string) })); return read("/etc/passwd"); """; /// The probe is a real program: it compiles against the script reference set. [Fact] public void Probe_CompilesCleanly_SoTheValidatorIsTheOnlyGate() { Assert.Empty(RoslynScriptCompiler.Compile(ProbeScript)); } /// The probe script is rejected by the trust validator. [Fact] public void Probe_IsRejected() { var violations = ScriptTrustValidator.FindViolations(ProbeScript); Assert.Contains(violations, v => v.Contains("'.GetMethod'", StringComparison.Ordinal)); Assert.Contains(violations, v => v.Contains("'.CreateDelegate'", StringComparison.Ordinal)); } /// The probe is also rejected on the degraded (TPA-fallback) reference set. [Fact] public void Probe_IsRejected_OnMinimalFallbackReferences() { var minimal = ScriptTrustPolicy.BuildMinimalFallbackReferences(); Assert.NotEmpty(ScriptTrustValidator.FindViolations(ProbeScript, minimal)); } /// The ?. half of the probe alone (no CreateDelegate) is rejected. [Fact] public void ConditionalGetMethod_OffPermittedType_IsRejected() { var code = "var m = typeof(Type)?.GetMethod(\"GetType\", new[] { typeof(string) });"; Assert.NotEmpty(ScriptTrustValidator.FindViolations(code)); } /// Delegate.CreateDelegate is a reflection gateway in both access forms. /// The script source. [Theory] [InlineData("var d = Delegate.CreateDelegate(typeof(Action), null, \"x\");")] [InlineData("var d = System.Delegate.CreateDelegate(typeof(Action), null, \"x\");")] [InlineData("Action a = () => {}; var d = a.Method?.CreateDelegate(typeof(Action));")] public void CreateDelegate_IsRejected(string code) { Assert.NotEmpty(ScriptTrustValidator.FindViolations(code)); } /// Every reflection-gateway member is rejected when reached through ?.. /// A name. [Theory] [MemberData(nameof(GatewayMembers))] public void EveryGatewayMember_ViaConditionalAccess_IsRejected(string member) { Assert.NotEmpty(ScriptTrustValidator.FindViolations($"object o = null; var x = o?.{member};")); Assert.NotEmpty(ScriptTrustValidator.FindViolations($"object o = null; var x = o?.{member}();")); // Chained: the gateway sits mid-chain behind another binding. Assert.NotEmpty(ScriptTrustValidator.FindViolations($"string s = null; var x = s?.Length.ToString()?.{member};")); } /// Every reflection-gateway member is still rejected through plain . (control). /// A name. [Theory] [MemberData(nameof(GatewayMembers))] public void EveryGatewayMember_ViaMemberAccess_IsRejected(string member) { Assert.NotEmpty(ScriptTrustValidator.FindViolations($"object o = null; var x = o.{member};")); } /// The gateway member names, as theory data. /// One row per gateway member. public static IEnumerable GatewayMembers() => ScriptTrustPolicy.ReflectionGatewayMembers.Order(StringComparer.Ordinal).Select(m => new object[] { m }); /// /// The ?. form of every .-form rejection test in /// (where a ?. spelling exists). Some of /// these are not valid C# for a static receiver, but the validator judges syntax and /// symbols, not compilability, and must reject them all. /// /// The script source. [Theory] // MG1_RejectsRuntimeEscapeApis [InlineData("object o = new object(); System.Runtime.CompilerServices.Unsafe?.As(ref o);")] [InlineData("System.Runtime.CompilerServices.RuntimeHelpers?.GetUninitializedObject(typeof(object));")] [InlineData("using U = System.Runtime.CompilerServices.Unsafe; object o = new object(); U?.As(ref o);")] // Rejects_SystemIo_* [InlineData("using System.IO; var x = File?.ReadAllText(\"/etc/passwd\");")] [InlineData("var x = global::System.IO.File?.ReadAllText(\"x\");")] [InlineData("using IO = System.IO; var f = IO.File?.ReadAllText(\"x\");")] // Rejects_ReflectionGateway_OffPermittedType [InlineData("var t = typeof(string)?.Assembly?.GetType(\"System.IO.File\");")] [InlineData("var t = typeof(string)?.Assembly.GetType(\"System.IO.File\");")] [InlineData("var t = typeof(string).Assembly?.GetType(\"System.IO.File\");")] [InlineData("var a = typeof(string)?.Assembly;")] // Rejects_Dynamic_Keyword [InlineData("dynamic d = 5; d?.Foo();")] // Rejects_Activator_CreateInstance (+ verbatim / unicode-escape spellings) [InlineData("var o = Activator?.CreateInstance(typeof(string));")] [InlineData("var o = @Activator?.CreateInstance(typeof(string));")] [InlineData("var o = \\u0041ctivator?.CreateInstance(typeof(string));")] // Rejects_RuntimeInteropServices / Rejects_MicrosoftWin32 [InlineData("using System.Runtime.InteropServices; var h = Marshal?.SizeOf();")] [InlineData("using Microsoft.Win32; var k = Registry?.LocalMachine;")] // Rejects_Threading_Thread_Sleep / Rejects_DirectThreadingMutex_NotThreadSleep [InlineData("System.Threading.Thread?.Sleep(10);")] [InlineData("var m = new System.Threading.Mutex()?.SafeWaitHandle;")] // Rejects_All_SystemNet [InlineData("var w = new System.Net.WebClient()?.BaseAddress;")] // Rejects_ReflectionGateway_OffAllowedTaskType [InlineData("var a = System.Threading.Tasks.Task.CompletedTask?.GetType()?.Assembly;")] [InlineData("var a = System.Threading.Tasks.Task.CompletedTask?.GetType().Assembly;")] // Rejects_ForbiddenIo_NestedInAllowedTaskRunLambda [InlineData("await System.Threading.Tasks.Task.Run(() => System.IO.File?.ReadAllText(\"x\"));")] // Rejects_Process_QualifiedType / Rejects_Process_BareIdentifier_ViaUsing [InlineData("var p = System.Diagnostics.Process?.Start(\"x\");")] [InlineData("using System.Diagnostics; var p = Process?.Start(\"x\");")] // Rejects_ExtensionMethod_InForbiddenNamespace [InlineData("using System.Reflection; Assembly asm = null; var a = asm?.GetCustomAttribute();")] // Rejects_ForbiddenApi_InsideUnsafeBlock [InlineData("unsafe { var t = typeof(string)?.Assembly; }")] // FindViolations_Flags [InlineData("Environment?.Exit(0);")] [InlineData("var s = Environment?.GetEnvironmentVariable(\"SCADABRIDGE_API_KEY\");")] [InlineData("var c = new Microsoft.Data.SqlClient.SqlConnection(\"Server=attacker\")?.Database;")] // SyntacticPass_Flags [InlineData("typeof(string)?.Assembly?.GetTypes()")] [InlineData("typeof(string).Assembly?.GetTypes()")] [InlineData("asm?.EntryPoint")] public void ConditionalAccessVariant_IsRejected(string code) { Assert.NotEmpty(ScriptTrustValidator.FindViolations(code)); } /// /// A gateway member reached as a bare identifier through using static never /// appears as a member access or binding; the semantic pass flags it by symbol name. /// /// The script source. [Theory] [InlineData("using static System.Delegate; var d = CreateDelegate(typeof(Action), null, \"x\");")] [InlineData("using static System.Type; var t = GetType(\"System.IO.File\");")] public void UsingStaticGatewayMember_IsRejected(string code) { Assert.NotEmpty(ScriptTrustValidator.FindViolations(code)); } /// Legitimate ?. use stays clean (no false positive from the new binding check). /// The script source. [Theory] [InlineData("string s = null; var n = s?.Length;")] [InlineData("string s = null; var u = s?.Trim()?.ToUpperInvariant();")] [InlineData("Func f = null; var r = f?.Invoke(3);")] [InlineData("var l = new List(); var c = l?.Count;")] public void LegitimateConditionalAccess_IsAllowed(string code) { Assert.Empty(ScriptTrustValidator.FindViolations(code)); } }