From 7ecaeea82e2237e8abf00c36ecfe04232046ddba Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:01:25 -0500 Subject: [PATCH 1/6] =?UTF-8?q?fix(scripting):=20#971=20review=20=E2=80=94?= =?UTF-8?q?=20refuse=20async=20lambdas/local=20functions,=20stackalloc=20a?= =?UTF-8?q?nd=20runtime-binding=20[MethodImpl]=20flags?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Three scripts passed the allow-list and the deploy gate and then terminated the host (exit 134): an async void local function / async lambda (the compiler's AsyncVoidMethodBuilder rethrows on the thread pool) and an over-sized stackalloc (overflows in one frame, before the #779 guard). IsForbiddenSyntax now refuses every async form (await included) and both stackalloc forms. Siblings: [MethodImpl] may set only the JIT-hint bits (InternalCall passed the gate then failed to load; Synchronized is a lock; numeric casts are checked by constant value), and a collection initializer's compiler-called Add is checked like a named member. Regression rows for each, plus rows pinning the lowered constructs that stay safe (iterators, goto, checked, filters, collection expressions, interpolation handlers, params Span, using/deconstruction) and the declarations the wrapper already refuses (records, local types, finalizers, static ctors, unsafe/fixed, SkipLocalsInit, ThreadStatic). Co-Authored-By: Claude --- docs/VirtualTags.md | 2 +- .../ForbiddenTypeAnalyzer.cs | 80 ++++++++++++++++++- .../ScriptStackGuardInjector.cs | 5 +- .../ForbiddenTypeAnalyzerTests.cs | 55 +++++++++++++ 4 files changed, 135 insertions(+), 7 deletions(-) diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index f2c93b3c3..7503ee98c 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -42,7 +42,7 @@ A script may name only: - `Interlocked` / `Volatile`, and `[MethodImpl]` on a local function. - **`System.Type` and `CancellationToken` as values, with a member allow-list** (`ForbiddenTypeAnalyzer.RestrictedTypeMembers`): `typeof(x)`, `o.GetType() == typeof(double)`, `t.Name` / `FullName` / `IsValueType` / `IsEnum` … work; `Assembly`, `Module`, `TypeHandle`, `GetMethod`, `MakeGenericType` do not. `ctx.CancellationToken` may be polled (`IsCancellationRequested`, `ThrowIfCancellationRequested`) but not `Register`ed against or waited on. -The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type an expression evaluates or converts to, must be allowed (generic arguments and array elements included); every member used must be declared on an allowed type (or be in `AllowedMembers`), must not be in `ForbiddenMembers` (`CultureInfo.CurrentCulture` and the other ambient-culture setters, `TimeZoneInfo.ClearCachedData`, `Encoding.RegisterProvider`, `Regex.CacheSize`), and its return type must be allowed — which is what keeps reflection handles out of reach (`Exception.TargetSite` is a member of an allowed type but returns a `MethodBase`; `Delegate.Method` / `DynamicInvoke` are declared on the un-listed `System.Delegate`). `__makeref` / `__refvalue` / `__reftype` / `__arglist`, `lock`, and `extern` local functions are refused syntactically. Pre-imported namespaces are unchanged (`System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`) — a collection still needs its full name (`System.Collections.Generic.List`). +The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type an expression evaluates or converts to, must be allowed (generic arguments and array elements included); every member used must be declared on an allowed type (or be in `AllowedMembers`), must not be in `ForbiddenMembers` (`CultureInfo.CurrentCulture` and the other ambient-culture setters, `TimeZoneInfo.ClearCachedData`, `Encoding.RegisterProvider`, `Regex.CacheSize`), and its return type must be allowed — which is what keeps reflection handles out of reach (`Exception.TargetSite` is a member of an allowed type but returns a `MethodBase`; `Delegate.Method` / `DynamicInvoke` are declared on the un-listed `System.Delegate`). `__makeref` / `__refvalue` / `__reftype` / `__arglist`, `lock`, and `extern` local functions are refused syntactically, and so — since the 2026-12-02 security review — are **`async` lambdas / anonymous methods / local functions** and **`stackalloc`**: each compiled through the allow-list *and* the deploy gate and then terminated the host (exit 134). An `async void` body's exception is rethrown on the thread pool by a compiler-synthesized builder no allow-list check sees, and one over-sized `stackalloc` overflows the stack inside a single frame, before any stack guard runs. `[MethodImpl]` on a local function may set only the JIT hints (`NoInlining` / `NoOptimization` / `AggressiveInlining` / `AggressiveOptimization`): `InternalCall` passed the gate and then failed to load, and `Synchronized` is a `lock`. Members the compiler calls without a name in the source — query operators, `foreach`'s enumerator pattern, `Deconstruct`, a collection initializer's `Add` — are checked like named ones. Pre-imported namespaces are unchanged (`System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`) — a collection still needs its full name (`System.Collections.Generic.List`). `ScriptSandbox.Build` compiles against the pinned OtOpcUa assemblies (`Core.Abstractions`, `Core.Scripting.Abstractions`, `Serilog`, the context type's assembly) plus only the BCL assemblies in `ScriptSandbox.BclAssemblyNames` — `System.Private.CoreLib`, `System.Runtime`, `netstandard`, `System.Collections`, `System.Collections.NonGeneric`, `System.ObjectModel`, `System.Linq`, `System.Text.RegularExpressions` — so most refused APIs (XML, archives, networking, expression trees, crypto, the console, processes) do not even bind and are reported as compile errors. That is defence in depth, not the gate: `System.Private.CoreLib` carries `File`, `Thread`, `Assembly` and `Environment`, so the analyzer decides. `ForbiddenTypeAnalyzerTests` compiles every K-1 bypass against *every* assembly the test host can load and asserts the analyzer alone rejects it, and enumerates every public type of the reference set to pin that nothing from a flagged namespace is allowed. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs index 21744aa9f..fbaa17fb1 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs @@ -49,7 +49,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// return-type check is what keeps reflection handles out of reach: Exception.TargetSite is a member /// of an allowed type but returns a MethodBase. (3) A few syntactic forms are refused outright /// (): __makeref/__refvalue/__reftype/__arglist, -/// lock (a blocking primitive on a possibly-shared object) and extern local functions. +/// lock (a blocking primitive on a possibly-shared object), extern local functions, +/// async lambdas / local functions and stackalloc (each terminated the host — +/// lmxopcua#971 review 2026-12-02); [MethodImpl] is limited to the JIT hint bits. (4) Members the +/// compiler calls without a name in the source — query operators, foreach's enumerator pattern, +/// Deconstruct, a collection initializer's Add — are checked like named ones. /// /// /// Defence in depth. also references only the handful of BCL assemblies @@ -255,9 +259,28 @@ public static class ForbiddenTypeAnalyzer /// /// Syntax refused regardless of binding: the undocumented TypedReference keywords, lock (a - /// blocking monitor on an object that may be shared with the host, e.g. lock (typeof(string))), and - /// extern local functions (a native entry point). + /// blocking monitor on an object that may be shared with the host, e.g. lock (typeof(string))), + /// extern local functions (a native entry point), async lambdas / anonymous methods / local + /// functions, and stackalloc. /// + /// + /// + /// async (lmxopcua#971 review 2026-12-02). The compiler lowers an async body into a state + /// machine driven by a method builder the script never names, so no allow-list check sees it. An + /// async void body's exception is not returned to the caller: AsyncVoidMethodBuilder + /// rethrows it on the thread pool, where nothing catches it and the runtime terminates the host + /// (async void Boom() { throw … } Boom(); — and an async lambda converted to + /// Action is the same thing). A script is synchronous by contract + /// () and System.Threading.Tasks is not + /// on the allow-list, so there is no legitimate async script code: every form is refused, which + /// also covers await, await foreach and await using (legal only inside one). + /// + /// + /// stackalloc. One stackalloc byte[1_500_000_000] overflows the thread's stack inside + /// a single frame — before the next ScriptStackGuard.Check() can run — and a stack overflow is + /// uncatchable. Scripts have heap arrays and Span over them; there is no need for stack buffers. + /// + /// /// The node. /// A description of the construct, or null when the node is allowed. internal static string? IsForbiddenSyntax(SyntaxNode node) => node switch @@ -268,9 +291,28 @@ public static class ForbiddenTypeAnalyzer ExpressionSyntax e when e.IsKind(SyntaxKind.ArgListExpression) => "__arglist", LockStatementSyntax => "lock", LocalFunctionStatementSyntax f when f.Modifiers.Any(SyntaxKind.ExternKeyword) => "extern local function", + LocalFunctionStatementSyntax f when f.Modifiers.Any(SyntaxKind.AsyncKeyword) => "async local function", + AnonymousFunctionExpressionSyntax f when f.AsyncKeyword.IsKind(SyntaxKind.AsyncKeyword) => "async lambda", + AwaitExpressionSyntax => "await", + StackAllocArrayCreationExpressionSyntax or ImplicitStackAllocArrayCreationExpressionSyntax => "stackalloc", _ => null, }; + /// + /// The bits a script's [MethodImpl] may + /// set: JIT inlining / optimization hints only. InternalCall / ForwardRef / Unmanaged / + /// PreserveSig change how the runtime binds the method (an InternalCall local function passes the + /// compiler and fails to load — the publish gate accepted what the runtime refuses), and Synchronized + /// takes a monitor (the lock the analyzer refuses). + /// + private const int AllowedMethodImplBits = + (int)(System.Runtime.CompilerServices.MethodImplOptions.NoInlining + | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization + | System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining + | System.Runtime.CompilerServices.MethodImplOptions.AggressiveOptimization); + + private const string MethodImplAttributeFullName = "System.Runtime.CompilerServices.MethodImplAttribute"; + private sealed class Walker(Compilation compilation, SemanticModel semantic, List rejections) { public void Visit(SyntaxNode node) @@ -283,9 +325,19 @@ public static class ForbiddenTypeAnalyzer } // Members the compiler calls with no name in the source: query-clause operators, foreach's - // GetEnumerator / MoveNext / Current, and a deconstruction's Deconstruct. + // GetEnumerator / MoveNext / Current, a deconstruction's Deconstruct, and a collection initializer's Add. switch (node) { + case AttributeSyntax attribute: + CheckMethodImpl(attribute); + break; + case InitializerExpressionSyntax initializer when initializer.IsKind(SyntaxKind.CollectionInitializerExpression): + foreach (var element in initializer.Expressions) + { + var addInfo = semantic.GetCollectionInitializerSymbolInfo(element); + CheckOptional(addInfo.Symbol, element.Span); + } + break; case QueryClauseSyntax clause: var clauseInfo = semantic.GetQueryClauseInfo(clause); CheckOptional(clauseInfo.OperationInfo.Symbol, clause.Span); @@ -318,6 +370,26 @@ public static class ForbiddenTypeAnalyzer CheckType(typeInfo.ConvertedType, expr.Span); } + /// Refuses [MethodImpl] flags outside , however spelled. + private void CheckMethodImpl(AttributeSyntax attribute) + { + if (semantic.GetSymbolInfo(attribute).Symbol is not IMethodSymbol { ContainingType: { } attributeType } + || TypeKey(attributeType.OriginalDefinition) != MethodImplAttributeFullName + || attribute.ArgumentList is null) + return; + + foreach (var argument in attribute.ArgumentList.Arguments) + { + if (argument.NameEquals is not null) continue; // named (MethodCodeType = …): its type is checked as usual + var constant = semantic.GetConstantValue(argument.Expression); + var bits = constant is { HasValue: true, Value: { } value } ? Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture) : -1; + if (bits < 0 || (bits & ~AllowedMethodImplBits) != 0) + Add(argument.Span, "MethodImplOptions", "System.Runtime.CompilerServices", + "[MethodImpl] may only set NoInlining, NoOptimization, AggressiveInlining or AggressiveOptimization " + + "in a script (sandbox: see ForbiddenTypeAnalyzer.AllowedMethodImplBits)."); + } + } + private void CheckOptional(ISymbol? symbol, TextSpan span) { if (symbol is not null) CheckSymbol(symbol, span); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs index fbd43b5da..bd9fed528 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs @@ -28,8 +28,9 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// compiler actually picked, so the block form is compatible with the same delegate type and nothing /// re-binds differently. Lambdas converted to an expression tree (Expression<T>) are left alone: /// a block body is not legal there and an expression tree does not execute script frames. Async lambdas and -/// local functions are left alone (the sandbox denies System.Threading.Tasks, so a script cannot -/// produce one that compiles). +/// local functions are left alone: refuses every async form +/// (lmxopcua#971 review — an async void one compiled without naming System.Threading.Tasks and +/// its exception terminated the host), so none reaches this rewrite. /// /// /// Runs after , so the analyzer only ever sees the user's code; the diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs index 9b6990d10..693be8107 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs @@ -77,8 +77,63 @@ public sealed class ForbiddenTypeAnalyzerTests { "AsQueryable", """return new[] { 1, 2 }.AsQueryable().Count();""" }, // ... and the undocumented TypedReference keywords. { "makeref", """int i = 1; var r = __makeref(i); return 0;""" }, + + // Review 2026-12-02 (lmxopcua#971): constructs that passed the allow-list AND the deploy gate and then + // terminated the host process (exit 134). An async void body's exception is rethrown on the thread pool, + // where nothing catches it; an over-sized stackalloc overflows the stack in one frame, before any guard. + { "async-void-local-function", """async void Boom() { throw new InvalidOperationException(); } Boom(); return 0;""" }, + { "static-async-local-function", """static async void Boom() { throw new InvalidOperationException(); } Boom(); return 0;""" }, + { "async-lambda", """Action a = async () => throw new InvalidOperationException(); a(); return 0;""" }, + { "async-simple-lambda", """Action a = async x => throw new InvalidOperationException(); a(1); return 0;""" }, + { "async-anonymous-method", """Action a = async delegate { throw new InvalidOperationException(); }; a(); return 0;""" }, + { "stackalloc", """Span s = stackalloc byte[1_500_000_000]; s[0] = 1; return s.Length;""" }, + { "stackalloc-implicit", """Span s = stackalloc[] { 1, 2, 3 }; return s.Length;""" }, + { "stackalloc-nested", """return M(stackalloc int[4]); static int M(Span s) => s.Length;""" }, + // Siblings: [MethodImpl] flags the runtime acts on. InternalCall passes the gate and then fails to LOAD + // (TypeLoadException at run time — the gate and the runtime disagree); Synchronized takes a monitor (the + // `lock` the analyzer already refuses); a numeric cast must not launder either. + { "MethodImpl-InternalCall", """[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] static int F() => 1; return F();""" }, + { "MethodImpl-Synchronized", """[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] static int F() => 1; return F();""" }, + { "MethodImpl-numeric", """[System.Runtime.CompilerServices.MethodImpl((System.Runtime.CompilerServices.MethodImplOptions)4096)] static int F() => 1; return F();""" }, + { "MethodImpl-short-ctor", """[System.Runtime.CompilerServices.MethodImpl((short)32)] static int F() => 1; return F();""" }, }; + /// + /// Siblings of the lmxopcua#971 review that are SAFE and must keep compiling: compiler-lowered constructs whose + /// synthesized code runs on the evaluating thread, inside the run, under the stack guard. + /// + /// The script body. + [Theory] + [InlineData("""System.Collections.Generic.IEnumerable F() { for (var i = 0; ; i++) yield return i; } return F().Take(3).Sum();""")] + [InlineData("""var i = 0; top: i++; if (i < 10) goto top; return i;""")] + [InlineData("""int x = int.MaxValue; try { return checked(x + 1); } catch (OverflowException) { return -1; }""")] + [InlineData("""try { throw new InvalidOperationException(); } catch (Exception e) when (e.Message.Length > 0) { return 1; }""")] + [InlineData("""System.Collections.Generic.List l = [1, 2, 3]; Span s = [4, 5]; int[] a = [.. l, .. s]; return a.Length;""")] + [InlineData("""var x = 1.5; return $"{x:F2} {x,8} {nameof(x)}";""")] + [InlineData("""static int F(params ReadOnlySpan xs) => xs.Length; return F(1, 2, 3);""")] + [InlineData("""using var e = new System.Collections.Generic.List { 1 }.GetEnumerator(); var (a, b) = (1, 2); return a + b;""")] + [InlineData("""[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] static int F() => 1; return F();""")] + public async Task Compiler_lowered_construct_still_compiles_and_runs(string source) + { + using var evaluator = ScriptEvaluator.Compile(source); + _ = await evaluator.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken); + } + + /// + /// Constructs the C# grammar or the wrapper already refuses — no type, record, finalizer, static constructor or + /// unsafe / fixed / pointer code can be declared in a script body — so no synthesized member + /// of a script-declared type can run outside the walker's view. + /// + /// The script body. + [Theory] + [InlineData("""record R(int A); return new R(1);""")] + [InlineData("""class C { ~C() { } static C() { } } return 0;""")] + [InlineData("""unsafe { int x = 1; int* p = &x; return *p; }""")] + [InlineData("""var a = new int[1]; unsafe { fixed (int* p = a) { return *p; } }""")] + [InlineData("""[System.Runtime.CompilerServices.SkipLocalsInit] static int F() => 1; return F();""")] + [InlineData("""[ThreadStatic] static int F() => 1; return F();""")] + public void Declaration_the_wrapper_cannot_hold_is_refused(string source) => SandboxRefusal.Refuses(source); + /// Each bypass snippet is refused by the publish gate. /// Row label. From 052fdf0769f3368bfe4745855a6bb45e5b248554 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:05:33 -0500 Subject: [PATCH 2/6] =?UTF-8?q?fix(scripting):=20#971=20review=20=E2=80=94?= =?UTF-8?q?=20guard=20script=20catch/finally=20handlers=20so=20unwinding?= =?UTF-8?q?=20cannot=20overflow=20the=20stack?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sibling hunt for the #779 stack guard: a catch or finally runs as a funclet on top of the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB/level). 'catch { throw; }' on every frame killed the host while unwinding from the guard's own exception, and 300 frames that each rethrow (or whose finally throws) killed it with no guard involvement. The stack-guard rewrite now gives every script catch the filter 'when (ScriptStackGuard.CanHandle() && (filter))' and wraps every finally body in 'if (ScriptStackGuard.CanHandle())'. Once the stack is low, script handlers are skipped and the in-flight exception reaches the host in one dispatch. Verified on 1.5 MB / 1 MB / 512 KB / 256 KB threads. Seven new child-process scenarios in ScriptRecursionContainmentTests (all crashed before), plus semantics-preservation rows for filters, declaration-less catch, pattern variables and finally on both paths. Co-Authored-By: Claude --- docs/ScriptEditor.md | 6 ++- docs/VirtualTags.md | 2 +- .../ScriptStackGuard.cs | 21 ++++++++++ .../ScriptStackGuardInjector.cs | 27 ++++++++++++ .../ScriptRecursionContainmentTests.cs | 41 +++++++++++++++++-- .../ScriptStackGuardInjectionTests.cs | 9 ++++ 6 files changed, 100 insertions(+), 6 deletions(-) diff --git a/docs/ScriptEditor.md b/docs/ScriptEditor.md index 2507a5a2f..8c382e090 100644 --- a/docs/ScriptEditor.md +++ b/docs/ScriptEditor.md @@ -242,8 +242,10 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`: `ScriptStackExhaustedException` (Bad, script log) instead of overflowing the stack, which would terminate the whole server. The runtime compile inserts a stack check at the entry of the script and of every lambda, anonymous method - and local function (lmxopcua#779); the editor does not show it and does not - flag recursion, and bounded recursion still works. + and local function (lmxopcua#779), and guards every `catch` / `finally` so a + handler that throws on every frame cannot overflow the stack while unwinding + (lmxopcua#971 review); the editor does not show it and does not flag + recursion, and bounded recursion still works. - **Configuration keys and their ranges.** All four knobs are node-wide (the `Scripting` appsettings section, shared by virtual tags, Calculation tags and scripted alarms) and are clamped when bound, with one startup Warning per diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 7503ee98c..55b791843 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -70,7 +70,7 @@ Absent, blank or unrecognised values mean `Error` — a typo never silently weak #### Known resource limits (accepted trade-offs) -The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen (the sandbox exposes no such API); a script can catch the exception, which only unwinds it. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". +The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen (the sandbox exposes no such API); a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs index b677ea4cd..9d887418a 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs @@ -26,6 +26,19 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// that remains, not by a fixed count: the same script may fail at a different depth on a thread with a /// different stack size (the platform's default thread stack size differs between Windows, Linux and macOS). /// +/// +/// Exception handlers (lmxopcua#971 review 2026-12-02). Checking frames is not enough on its own: a +/// catch or finally block runs as a funclet on top of the frames being unwound, so a +/// handler that throws (throw;, throw new …, a call that fails the check) starts a nested +/// exception dispatch deeper still — several KB per level. A script that catches-and-rethrows on every frame +/// therefore overflowed the stack while unwinding from the guard's own exception, and 300 frames that each +/// rethrow overflowed with no guard involvement at all. The rewrite also guards every script handler with +/// : a catch gains the filter when (CanHandle() && …) and a +/// finally body runs only if (CanHandle()). Once the stack is low, script handlers are skipped, +/// the exception in flight passes to the host in one dispatch (a filter runs and returns without growing the +/// stack), and the run fails with it. Skipping a finally is only possible on a run that is already +/// failing on an exhausted stack. +/// /// [EditorBrowsable(EditorBrowsableState.Never)] public static class ScriptStackGuard @@ -38,6 +51,14 @@ public static class ScriptStackGuard if (!RuntimeHelpers.TryEnsureSufficientExecutionStack()) throw new ScriptStackExhaustedException(); } + + /// + /// True while the current thread has stack to spare for a script exception handler (see the remarks). Called + /// by compiled scripts from every catch filter and finally block; not part of the script + /// authoring surface. + /// + /// False when the remaining stack is below the runtime's safety margin. + public static bool CanHandle() => RuntimeHelpers.TryEnsureSufficientExecutionStack(); } /// diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs index bd9fed528..bf95e4f3e 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ScriptStackGuardInjector.cs @@ -33,6 +33,13 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// its exception terminated the host), so none reaches this rewrite. /// /// +/// Exception handlers (lmxopcua#971 review). Every script catch also gets the filter +/// when (ScriptStackGuard.CanHandle() && (original filter)), and every finally body is +/// wrapped in if (ScriptStackGuard.CanHandle()) { … }: a handler runs on top of the frames being +/// unwound, so one that throws on every frame overflowed the stack while unwinding (see +/// ). On a healthy stack both are no-ops. +/// +/// /// Runs after , so the analyzer only ever sees the user's code; the /// inserted call names a type in Core.Scripting.Abstractions, which the sandbox already references. /// @@ -40,6 +47,7 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; internal static class ScriptStackGuardInjector { private const string CheckCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.Check()"; + private const string CanHandleCall = "global::ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptStackGuard.CanHandle()"; /// Returns with a stack check at the entry of every script-declared body. /// The compiled (error-free, analyzer-clean) wrapper compilation. @@ -65,6 +73,25 @@ internal static class ScriptStackGuardInjector private sealed class Rewriter(SemanticModel model) : CSharpSyntaxRewriter { + /// catch … when (f) becomes catch … when (CanHandle() && (f)) — see + /// 's "Exception handlers" remarks. + public override SyntaxNode? VisitCatchClause(CatchClauseSyntax node) + { + var visited = (CatchClauseSyntax)base.VisitCatchClause(node)!; + ExpressionSyntax canHandle = ParseExpression(CanHandleCall); + var condition = visited.Filter is { } filter + ? BinaryExpression(SyntaxKind.LogicalAndExpression, canHandle, ParenthesizedExpression(filter.FilterExpression)) + : canHandle; + return visited.WithFilter(CatchFilterClause(condition)); + } + + /// finally { b } becomes finally { if (CanHandle()) { b } }. + public override SyntaxNode? VisitFinallyClause(FinallyClauseSyntax node) + { + var visited = (FinallyClauseSyntax)base.VisitFinallyClause(node)!; + return visited.WithBlock(Block(IfStatement(ParseExpression(CanHandleCall), visited.Block))); + } + public override SyntaxNode? VisitMethodDeclaration(MethodDeclarationSyntax node) { // The only method in the wrapper is the synthesized CompiledScript.Run (ScriptEvaluator enforces that). diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs index 1098eccd1..e1ee662dd 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptRecursionContainmentTests.cs @@ -43,6 +43,40 @@ public sealed class ScriptRecursionContainmentTests "System.Action a = null!; System.Func h = n => { a(n); return n; }; a = n => h(n + 1); a(0); return 0;", ["anonymous-method"] = "System.Func f = null!; f = delegate (int n) { return f(n + 1) + 1; }; return f(0);", + + // lmxopcua#971 review: exception handlers on every frame. A catch / finally runs as a funclet ON TOP of the + // frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level on + // macOS). Before the fix each of these terminated the process — the unbounded ones after the guard fired + // (its margin cannot hold a nested dispatch per frame), the bounded ones with no guard involvement at all: + // 300 frames that each catch-and-rethrow are enough. + ["catch-rethrow-per-frame"] = + "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);", + ["catch-throw-new-per-frame"] = + "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw new System.InvalidOperationException(); } } return Rec(0);", + ["catch-recurse-again"] = + "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { return Rec(d + 1); } } return Rec(0);", + ["finally-throw-per-frame"] = + "int Rec(int d) { try { return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);", + ["bounded-catch-rethrow"] = + "int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);", + ["bounded-catch-wrap"] = + "int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.InvalidOperationException) { throw new System.ArgumentException(); } catch (System.ArgumentException) { throw new System.InvalidOperationException(); } } return Rec(0);", + ["bounded-finally-throw"] = + "int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);", + ["filter-recurses"] = + "int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) when (Rec(d + 1) > 0) { return 0; } } return Rec(0);", + }; + + /// + /// Scenarios whose surviving fault is not : the exception in flight + /// when the stack ran low is the script's own, and the run fails with it (null = any exception type). + /// + private static readonly Dictionary ExpectedFaultOverrides = new(StringComparer.Ordinal) + { + ["finally-throw-per-frame"] = null, + ["bounded-catch-rethrow"] = nameof(InvalidOperationException), + ["bounded-catch-wrap"] = null, + ["bounded-finally-throw"] = nameof(InvalidOperationException), }; public static TheoryData ScenarioNames => new(Scenarios.Keys); @@ -58,9 +92,10 @@ public sealed class ScriptRecursionContainmentTests var outcome = File.Exists(resultFile) ? await File.ReadAllTextAsync(resultFile, TestContext.Current.CancellationToken) : ""; // Assert the artifact first: what the child itself recorded about the run. - outcome.ShouldBe( - $"FAULTED:{nameof(ScriptStackExhaustedException)}", - $"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}"); + var context = $"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}"; + var expected = ExpectedFaultOverrides.TryGetValue(scenario, out var over) ? over : nameof(ScriptStackExhaustedException); + if (expected is null) outcome.ShouldStartWith("FAULTED:", Case.Sensitive, context); + else outcome.ShouldBe($"FAULTED:{expected}", context); exitCode.ShouldBe(0, $"the process must survive the script; stderr tail: {Tail(stderr)}"); } finally diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs index 7267ca684..87af7ffe5 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ScriptStackGuardInjectionTests.cs @@ -38,6 +38,15 @@ public sealed class ScriptStackGuardInjectionTests // Static lambda and a lambda capturing ctx. [InlineData("System.Func f = static x => x - 1; return f(9);", 8)] [InlineData("System.Func known = p => ctx.GetTag(p).StatusCode == 0u; return known(\"missing\") ? 1 : 0;", 0)] + // lmxopcua#971 review: guarded handlers keep their meaning on a healthy stack — an existing filter still + // decides, a declaration-less catch still catches, pattern variables from the filter stay in scope, and a + // finally still runs on both the normal and the exceptional path. + [InlineData("try { throw new InvalidOperationException(\"a\"); } catch (InvalidOperationException e) when (e.Message == \"b\") { return 1; } catch (Exception) { return 2; }", 2)] + [InlineData("try { throw new InvalidOperationException(); } catch { return 4; }", 4)] + [InlineData("try { throw new ArgumentException(\"x\"); } catch (Exception e) when (e is ArgumentException a && a.Message == \"x\") { return a.Message.Length + 2; }", 3)] + [InlineData("var n = 0; try { n = 1; } finally { n += 10; } return n;", 11)] + [InlineData("var n = 0; try { try { throw new Exception(); } finally { n = 5; } } catch { n += 1; } return n;", 6)] + [InlineData("int Rec(int d) { try { if (d >= 50) throw new InvalidOperationException(); return Rec(d + 1); } catch (InvalidOperationException) { throw; } } try { return Rec(0); } catch (InvalidOperationException) { return 50; }", 50)] public void Rewritten_lambdas_and_local_functions_keep_their_meaning(string source, int expected) => Run(source).ShouldBe(expected); From 31bf883e098707a24924c9607674217924f90edd Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:13:58 -0500 Subject: [PATCH 3/6] =?UTF-8?q?fix(scripting):=20#971=20review=20=E2=80=94?= =?UTF-8?q?=20refuse=20script-built=20deep/cyclic=20data=20that=20BCL=20or?= =?UTF-8?q?=20host=20code=20recurses=20over?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Sibling hunt for the #779 stack guard: recursion with NO script frame. A BCL or compiler-synthesized ToString/Equals/GetHashCode/CompareTo/Message recursing over a structure the script nested a million deep in a loop (or made cyclic) terminated the host with 'Stack overflow.' — Tuple/ValueTuple/KeyValuePair/ anonymous-type chains, a self-referencing Lazy, StructuralComparisons over a self-containing array, DictionaryEntry, FormattableString holes, inner-exception / AggregateException / ArgumentOutOfRange(actualValue) chains, DataValueSnapshot built or with-copied around itself. Host code does the same to a returned value: OwnedDataSample.CopyLegacy and VirtualTagActor.SameValue recurse over nested / self-containing object[] results. The analyzer now refuses what builds such a structure: holders with an open element type (object / ValueType / interface / type parameter; a tuple literal that is only deconstructed stays legal), arrays whose element can be an array, Array.CreateInstance, Lazy, the structural comparers, DictionaryEntry, AggregateException, exception constructors taking an inner exception or an object, FormattableString outside FormattableString.Invariant/CurrentCulture, and host-record construction / 'with' when the record has an open member. System.Comparison is dropped: Array/List Sort and BinarySearch rethrow a comparer's exception from a BCL catch block, so a comparer recursing through Sort overflowed while unwinding (use OrderBy/ThenBy). Regression rows for every vector (all failed first), plus closed-neighbour rows that must keep compiling. The script-literal differential over src/tests/docs/ scripts (238 accepted before) and the reviewer's 35 legit probes are unchanged. Co-Authored-By: Claude --- docs/VirtualTags.md | 8 +- .../ScriptStackGuard.cs | 10 +- .../ForbiddenTypeAnalyzer.cs | 208 ++++++++++++++++-- .../ForbiddenTypeAnalyzerTests.cs | 60 +++++ 4 files changed, 268 insertions(+), 18 deletions(-) diff --git a/docs/VirtualTags.md b/docs/VirtualTags.md index 55b791843..661528b3e 100644 --- a/docs/VirtualTags.md +++ b/docs/VirtualTags.md @@ -36,14 +36,16 @@ Until 2026-12 the analyzer was a **deny-list** over the whole BCL (namespaces `S A script may name only: - **The `ctx` API** — `ScriptContext` and its subclasses (`ctx.GetTag` / `SetVirtualTag` / `Now` / `Logger` / `CancellationToken`, `ScriptContext.Deadband`), `DataValueSnapshot`, `DriverDataType`, and `Serilog.ILogger` + `LogEventLevel` for `ctx.Logger`. Nothing else from the OtOpcUa assemblies (the host's `CredentialFilePaths`, `PollGroupEngine`, … used to be reachable). -- **Value types and helpers** — the primitives, `string`, `decimal`, `Guid`, `DateTime` / `DateTimeOffset` / `TimeSpan` / `DateOnly` / `TimeOnly` / `TimeZoneInfo`, `Math` / `MathF` / `Convert` / `BitConverter` / `BinaryPrimitives` / `BitOperations` / `Random`, `Enum`, `Nullable`, `Array`, `Span` / `Memory`, tuples, `Index` / `Range`, `HashCode`, `Lazy`, the delegate types `Func` / `Action` / `Predicate` / `Comparison` / `Converter`, and `System.Exception` plus every exception type in `System`. -- **Collections and LINQ-to-objects** — the whole of `System.Collections`, `System.Collections.Generic` and `System.Collections.ObjectModel`; `System.Linq.Enumerable` (not `ParallelEnumerable` / `Queryable`). +- **Value types and helpers** — the primitives, `string`, `decimal`, `Guid`, `DateTime` / `DateTimeOffset` / `TimeSpan` / `DateOnly` / `TimeOnly` / `TimeZoneInfo`, `Math` / `MathF` / `Convert` / `BitConverter` / `BinaryPrimitives` / `BitOperations` / `Random`, `Enum`, `Nullable`, `Array`, `Span` / `Memory`, tuples, `Index` / `Range`, `HashCode`, the delegate types `Func` / `Action` / `Predicate` / `Converter`, and `System.Exception` plus every exception type in `System` except `AggregateException`. +- **Collections and LINQ-to-objects** — `System.Collections`, `System.Collections.Generic` and `System.Collections.ObjectModel` (except `StructuralComparisons`, `IStructuralEquatable`, `IStructuralComparable` and `DictionaryEntry`); `System.Linq.Enumerable` (not `ParallelEnumerable` / `Queryable`). - **Text** — `StringBuilder`, `Encoding`, `Rune`, `System.Text.RegularExpressions` (`Regex` / `Match` / `Group` / …), and the formatting types of `System.Globalization` (`CultureInfo`, `NumberStyles`, `DateTimeStyles`, `NumberFormatInfo`, …). - `Interlocked` / `Volatile`, and `[MethodImpl]` on a local function. - **`System.Type` and `CancellationToken` as values, with a member allow-list** (`ForbiddenTypeAnalyzer.RestrictedTypeMembers`): `typeof(x)`, `o.GetType() == typeof(double)`, `t.Name` / `FullName` / `IsValueType` / `IsEnum` … work; `Assembly`, `Module`, `TypeHandle`, `GetMethod`, `MakeGenericType` do not. `ctx.CancellationToken` may be polled (`IsCancellationRequested`, `ThrowIfCancellationRequested`) but not `Register`ed against or waited on. The rules (`ForbiddenTypeAnalyzer`): every type a script names, and every type an expression evaluates or converts to, must be allowed (generic arguments and array elements included); every member used must be declared on an allowed type (or be in `AllowedMembers`), must not be in `ForbiddenMembers` (`CultureInfo.CurrentCulture` and the other ambient-culture setters, `TimeZoneInfo.ClearCachedData`, `Encoding.RegisterProvider`, `Regex.CacheSize`), and its return type must be allowed — which is what keeps reflection handles out of reach (`Exception.TargetSite` is a member of an allowed type but returns a `MethodBase`; `Delegate.Method` / `DynamicInvoke` are declared on the un-listed `System.Delegate`). `__makeref` / `__refvalue` / `__reftype` / `__arglist`, `lock`, and `extern` local functions are refused syntactically, and so — since the 2026-12-02 security review — are **`async` lambdas / anonymous methods / local functions** and **`stackalloc`**: each compiled through the allow-list *and* the deploy gate and then terminated the host (exit 134). An `async void` body's exception is rethrown on the thread pool by a compiler-synthesized builder no allow-list check sees, and one over-sized `stackalloc` overflows the stack inside a single frame, before any stack guard runs. `[MethodImpl]` on a local function may set only the JIT hints (`NoInlining` / `NoOptimization` / `AggressiveInlining` / `AggressiveOptimization`): `InternalCall` passed the gate and then failed to load, and `Synchronized` is a `lock`. Members the compiler calls without a name in the source — query operators, `foreach`'s enumerator pattern, `Deconstruct`, a collection initializer's `Add` — are checked like named ones. Pre-imported namespaces are unchanged (`System`, `System.Linq`, `ZB.MOM.WW.OtOpcUa.Core.Abstractions`, `ZB.MOM.WW.OtOpcUa.Core.Scripting`) — a collection still needs its full name (`System.Collections.Generic.List`). +**Deep or cyclic data (2026-12-02 review, lmxopcua#971).** Some BCL and compiler-synthesized members recurse over a value's contents with no script frame for the stack guard to check, so a structure a script nests a million deep in a loop — or makes cyclic — overflowed the stack inside `ToString` / `Equals` / `GetHashCode` / `CompareTo` / `Message` and terminated the host (in the script, or later in host code that logs or publishes the value). The analyzer refuses what builds one: a `Tuple` / `ValueTuple` / `KeyValuePair` / anonymous type with an *open* element (`object`, `ValueType`, an interface, a type parameter) — give it a concrete type, e.g. `Convert.ToDouble(v.Value)`; a tuple literal that is only deconstructed (`var (v, q) = (t.Value, t.StatusCode)`) is fine; `Lazy` (its `ToString` renders `Value`, which can be itself); `StructuralComparisons` / `IStructuralEquatable` / `IStructuralComparable` (an array that contains itself); `DictionaryEntry`; exception constructors taking an inner exception or an `object` (a million-deep chain), and `AggregateException`; an interpolated string held as a `FormattableString` / `IFormattable` (only `FormattableString.Invariant($"…")` is allowed, which formats at once); constructing or `with`-copying a host record with an `object` member (`DataValueSnapshot`); and an array whose element type can hold an array (`object[]`, `Array[]`, an interface) plus `Array.CreateInstance` — the *host* copies a returned array recursively (`OwnedDataSample.CopyLegacy`) and compares it structurally (`VirtualTagActor.SameValue`), so a nested or self-containing `object[]` overflowed the host's stack after the run (typed and jagged arrays are fine; an implicit `params object[]`, as in `ctx.Logger.Information("{A}", v)`, is not a script-held array). `System.Comparison` is off the list for a related reason: `Array` / `List` `Sort` and `BinarySearch` rethrow a comparer's exception from a catch block, so a comparer that recursed through `Sort` overflowed while unwinding — order with `OrderBy` / `ThenBy`. Iterators, `goto`, `checked`, exception filters, collection expressions, interpolation handlers, `params Span`, `using` and deconstruction were reviewed and are safe: their lowered code runs on the evaluating thread under the guard. A script that returns a lazy sequence (an iterator, an un-materialised LINQ query) hands the host an object whose code runs only if the host enumerates it, which the publish path does not. + `ScriptSandbox.Build` compiles against the pinned OtOpcUa assemblies (`Core.Abstractions`, `Core.Scripting.Abstractions`, `Serilog`, the context type's assembly) plus only the BCL assemblies in `ScriptSandbox.BclAssemblyNames` — `System.Private.CoreLib`, `System.Runtime`, `netstandard`, `System.Collections`, `System.Collections.NonGeneric`, `System.ObjectModel`, `System.Linq`, `System.Text.RegularExpressions` — so most refused APIs (XML, archives, networking, expression trees, crypto, the console, processes) do not even bind and are reported as compile errors. That is defence in depth, not the gate: `System.Private.CoreLib` carries `File`, `Thread`, `Assembly` and `Environment`, so the analyzer decides. `ForbiddenTypeAnalyzerTests` compiles every K-1 bypass against *every* assembly the test host can load and asserts the analyzer alone rejects it, and enumerates every public type of the reference set to pin that nothing from a flagged namespace is allowed. **Adding to the list.** Add a type only if it has no I/O, no process-wide state, no background work, no blocking wait, and no member that returns or accepts a reflection handle; prefer a new `ScriptContext` helper to opening BCL surface. The editor's completions, diagnostics and the publish gate all follow the list automatically (one authority). @@ -70,7 +72,7 @@ Absent, blank or unrecognised values mean `Error` — a typo never silently weak #### Known resource limits (accepted trade-offs) -The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen (the sandbox exposes no such API); a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". +The sandbox cannot pre-empt a script. **Memory:** each run's own-thread allocation is sampled (`GC.GetAllocatedBytesForCurrentThread`) and a run over `Scripting:MaxAllocBytesPerRun` (default 64 MB) quarantines the script — but the sample is taken after the run returns, so a script that allocates fast enough (`new byte[int.MaxValue]` in a loop) can still OOM the process first. **CPU:** a tight loop keeps its pool thread after the timeout fires; `ScriptRunGuard` bounds that to one orphan per script by refusing further runs while it spins (Bad `"previous evaluation still running"`) and quarantines after three consecutive timeouts (a refusal is not a strike) — or immediately on a refusal behind an orphan that has run longer than `Scripting:StuckOrphanQuarantineFactor` (default 10) × the timeout, which is what quarantines a never-returning `while(true)`. Both are mitigations; pre-emptive CPU/memory limits need the out-of-process runner (→ #750 design, #780; opt-in via `Scripting:Runner=OutOfProcess`, below). **Stack:** unbounded recursion used to terminate the whole server — a `StackOverflowException` cannot be caught, and lmxopcua#779 reproduced it out of process (local function, mutual recursion, self-referencing `Func<>`, anonymous self-application, recursion through LINQ: the child process died with "Stack overflow." / SIGABRT). `ScriptEvaluator.Compile` now rewrites the script so the body and every lambda, anonymous method and local function starts with `ScriptStackGuard.Check()` (`RuntimeHelpers.TryEnsureSufficientExecutionStack`), so the recursion fails the script with `ScriptStackExhaustedException` — Bad quality and a script-log entry like any throwing script — while there is still stack left. A runtime check rather than an analyzer rule because recursion is not decidable from syntax (anonymous self-application never names itself); bounded recursion keeps working. Limits: the depth reached depends on the evaluating thread's stack size; a recursion that never re-enters script code is not seen — the review found BCL members that do exactly that over script-built data (see "Deep or cyclic data" in the sandbox section), and the analyzer now refuses the constructs that build it; a script can catch the exception, which only unwinds it. **Exception handlers (2026-12-02 review, lmxopcua#971):** a `catch` / `finally` runs as a funclet *on top of* the frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level) — `catch { throw; }` on every frame overflowed while unwinding from the guard's own exception, and 300 frames that each rethrow overflowed with no guard involvement. The rewrite therefore also gives every script `catch` the filter `when (ScriptStackGuard.CanHandle() && …)` and wraps every `finally` body in `if (ScriptStackGuard.CanHandle())`: once the stack is low, script handlers are skipped and the exception in flight reaches the host in one dispatch (the run fails with it). On a healthy stack both are no-ops. Pinned by `ScriptRecursionContainmentTests` (one child process per shape) and `ScriptStackGuardInjectionTests`. Script authoring is gated by the AdminUI `ConfigEditor` policy — **`Administrator` or `Designer`**, not Administrator alone — and that same policy gates deploy, so a Designer can author a script and put it into production; that gate is the primary control (AdminUI-001 deliberately admitted Designers to the script pages and `/api/script-analysis/*`; lmxopcua#779 corrected this sentence, which used to say Admin-only). See `docs/ScriptEditor.md` §"Runtime safety". diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs index 9d887418a..1bb9e33e3 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Abstractions/ScriptStackGuard.cs @@ -20,8 +20,14 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting; /// /// /// Limits. The check runs on entry to script-declared code only. A recursion that never re-enters -/// script code (a BCL call that recurses on its own) is not seen — the sandbox gives scripts no such API -/// today. Frames of BCL code between two script frames (a LINQ operator invoking a script lambda) must fit +/// script code (a BCL call that recurses on its own) is not seen. The 2026-12-02 review (lmxopcua#971) +/// found such APIs did exist — Tuple / ValueTuple / KeyValuePair / anonymous-type +/// ToString / Equals / GetHashCode over a structure a script nested a million deep in a +/// loop, a self-referencing Lazy, StructuralComparisons over a self-containing array, an +/// inner-exception chain's ToString — so ForbiddenTypeAnalyzer now refuses the constructs that +/// build such structures (open-element holders, Lazy, the structural comparers, exception +/// constructors taking an inner exception, held FormattableStrings, host records with an +/// object member). Frames of BCL code between two script frames (a LINQ operator invoking a script lambda) must fit /// in the margin; they are a few hundred bytes. The check is per frame, so it bounds depth by the stack /// that remains, not by a fixed count: the same script may fail at a different depth on a thread with a /// different stack size (the platform's default thread stack size differs between Windows, Linux and macOS). diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs index fbaa17fb1..501b59490 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting/ForbiddenTypeAnalyzer.cs @@ -106,9 +106,13 @@ public static class ForbiddenTypeAnalyzer // Strings. "System.StringComparison", "System.StringComparer", "System.StringSplitOptions", // Delegates (members inherited from System.Delegate — Method, Target, DynamicInvoke — stay refused). - "System.Func", "System.Action", "System.Predicate", "System.Comparison", "System.Converter", - // Small helpers and interfaces. - "System.Lazy", "System.IComparable", "System.IEquatable", "System.IFormattable", "System.IFormatProvider", + // Not System.Comparison: it is the only way a script supplies comparer code, and Array / List Sort and + // BinarySearch rethrow a comparer's exception from a catch funclet, so a recursion through Sort overflowed + // the stack while unwinding (lmxopcua#971 review). Order with OrderBy / ThenBy. + "System.Func", "System.Action", "System.Predicate", "System.Converter", + // Small helpers and interfaces. Not System.Lazy: its ToString renders Value, so a Lazy whose value is itself + // recursed forever in BCL code with no script frame for the stack guard (lmxopcua#971 review). + "System.IComparable", "System.IEquatable", "System.IFormattable", "System.IFormatProvider", "System.IConvertible", "System.IDisposable", "System.ICloneable", // System.Linq — LINQ-to-objects only (not ParallelEnumerable / ParallelQuery / Queryable / IQueryable). "System.Linq.Enumerable", "System.Linq.IGrouping", "System.Linq.ILookup", "System.Linq.Lookup", @@ -137,6 +141,21 @@ public static class ForbiddenTypeAnalyzer "Serilog.ILogger", "Serilog.Events.LogEventLevel", ]; + /// + /// Types refused although their namespace is in (or, for exceptions, they are a + /// System.Exception subclass in System): each one recurses, in BCL code where the stack guard + /// cannot see it, over a structure a script can make cyclic or arbitrarily deep (lmxopcua#971 review). + /// StructuralComparisons / IStructuralEquatable / IStructuralComparable compare an array + /// that contains itself forever; DictionaryEntry.ToString renders an object key and value; + /// AggregateException.Message / ToString render every inner exception. + /// + public static readonly IReadOnlyList ExcludedTypes = + [ + "System.Collections.StructuralComparisons", "System.Collections.IStructuralEquatable", + "System.Collections.IStructuralComparable", "System.Collections.DictionaryEntry", + "System.AggregateException", + ]; + /// /// Types a script may hold and pass as values but whose members are limited to the listed names (anything /// else declared on the type is refused). System.Type is the reflection gateway — typeof(x), @@ -171,7 +190,7 @@ public static class ForbiddenTypeAnalyzer ("System.Reflection.MemberInfo", "Name"), ]; - /// Members refused on otherwise-allowed types: process-wide state. + /// Members refused on otherwise-allowed types: process-wide state, and the untyped array factory. public static readonly IReadOnlyList<(string Type, string Member)> ForbiddenMembers = [ // Ambient culture is process / pool-thread state (lmxopcua#792): name InvariantCulture or GetCultureInfo. @@ -186,6 +205,9 @@ public static class ForbiddenTypeAnalyzer // Process-wide regex cache size. ("System.Text.RegularExpressions.Regex", "CacheSize"), ("System.Text.RegularExpressions.Regex", "CompileToAssembly"), + // An object[] behind a System.Array-typed value: the array-element rule (see CheckType) cannot see it. + ("System.Array", "CreateInstance"), + ("System.Array", "CreateInstanceFromArrayType"), ]; private const string ScriptContextFullName = "ZB.MOM.WW.OtOpcUa.Core.Scripting.ScriptContext"; @@ -193,6 +215,22 @@ public static class ForbiddenTypeAnalyzer private static readonly HashSet AllowedNamespaceSet = new(AllowedNamespaces, StringComparer.Ordinal); private static readonly HashSet AllowedTypeSet = new(AllowedTypes, StringComparer.Ordinal); + private static readonly HashSet ExcludedTypeSet = new(ExcludedTypes, StringComparer.Ordinal); + + /// + /// Generic value holders whose ToString / Equals / GetHashCode / CompareTo recurse + /// into their elements (anonymous types' compiler-synthesized members do the same). With an open + /// element type () a script can nest one inside another in a loop — + /// o = Tuple.Create(o) a million times — and any of those members then recurses a million BCL frames + /// deep with no script frame for the stack guard to check: the host died with "Stack overflow." (lmxopcua#971 + /// review). With closed element types the nesting depth is fixed by the source. + /// + private static readonly HashSet RecursiveHolderTypes = new(StringComparer.Ordinal) + { + "System.Tuple", "System.ValueTuple", "System.Collections.Generic.KeyValuePair", + }; + + private const string FormattableStringFullName = "System.FormattableString"; private static readonly HashSet<(string, string)> AllowedMemberSet = new(AllowedMembers); private static readonly HashSet<(string, string)> ForbiddenMemberSet = new(ForbiddenMembers); @@ -362,12 +400,67 @@ public static class ForbiddenTypeAnalyzer if (node is not ExpressionSyntax expr) return; var symbol = semantic.GetSymbolInfo(expr).Symbol; - if (symbol is not null) CheckSymbol(symbol, expr.Span); + var deconstructionOnly = IsDeconstructionOnly(expr); + if (symbol is not null) CheckSymbol(symbol, expr.Span, deconstructionOnly); var typeInfo = semantic.GetTypeInfo(expr); - CheckType(typeInfo.Type, expr.Span); + CheckType(typeInfo.Type, expr.Span, deconstructionOnly); if (!SymbolEqualityComparer.Default.Equals(typeInfo.Type, typeInfo.ConvertedType)) - CheckType(typeInfo.ConvertedType, expr.Span); + CheckType(typeInfo.ConvertedType, expr.Span, deconstructionOnly); + + switch (expr) + { + // A FormattableString renders its holes with ToString, so one nested in another's hole in a loop is a + // deep structure like an open tuple. The only producer is an interpolated string converted to + // FormattableString / IFormattable; it may appear only as the argument FormattableString.Invariant / + // CurrentCulture format at once, so no FormattableString value is ever held. + case InterpolatedStringExpressionSyntax interpolated + when typeInfo.ConvertedType is INamedTypeSymbol converted + && TypeKey(converted.OriginalDefinition) is FormattableStringFullName or "System.IFormattable" + && !IsFormattableStringFormatArgument(interpolated): + Add(expr.Span, FormattableStringFullName, "System", + "An interpolated string may become a FormattableString only as the argument of " + + "FormattableString.Invariant(…) — a held FormattableString can be nested in another's hole " + + "without limit, and rendering it then recurses past the stack (see ForbiddenTypeAnalyzer)."); + break; + // `snapshot with { Value = … }` builds a record whose synthesized Equals / GetHashCode recurse into an + // open-typed member (DataValueSnapshot.Value is object). + case WithExpressionSyntax with + when semantic.GetTypeInfo(with.Expression).Type is INamedTypeSymbol { IsRecord: true } record + && !IsSourceSymbol(record) && OpenMember(record) is { } openMember: + Add(expr.Span, record.ToDisplayString(), record.ContainingNamespace?.ToDisplayString() ?? string.Empty, + $"A script may not build a '{record.ToDisplayString()}' (its member '{openMember}' holds any value, " + + "so one can be nested in another without limit; see ForbiddenTypeAnalyzer)."); + break; + } + } + + private bool IsFormattableStringFormatArgument(InterpolatedStringExpressionSyntax interpolated) + => interpolated.Parent is ArgumentSyntax { Parent: ArgumentListSyntax { Parent: InvocationExpressionSyntax invocation } } + && semantic.GetSymbolInfo(invocation).Symbol is IMethodSymbol { Name: "Invariant" or "CurrentCulture" } method + && TypeKey(method.ContainingType.OriginalDefinition) == FormattableStringFullName; + + /// + /// True when is a tuple that only exists to be deconstructed — var (a, b) = (x, y) + /// (either side, and the assignment statement itself) or a foreach (var (k, v) in …) target. No + /// tuple value is held, so an open element type there cannot nest. + /// + private static bool IsDeconstructionOnly(ExpressionSyntax expr) + { + SyntaxNode node = expr; + if (node.Parent is DeclarationExpressionSyntax declaration && declaration.Type == node) node = declaration; + if (node is AssignmentExpressionSyntax { Left: TupleExpressionSyntax or DeclarationExpressionSyntax, Parent: ExpressionStatementSyntax }) + return true; + // Only a tuple literal / declaration itself — never an element expression inside one, which is a value. + if (node is not (TupleExpressionSyntax or DeclarationExpressionSyntax)) return false; + while (node.Parent is ArgumentSyntax { Parent: TupleExpressionSyntax tuple }) node = tuple; + return node.Parent switch + { + AssignmentExpressionSyntax { Left: TupleExpressionSyntax or DeclarationExpressionSyntax, Parent: ExpressionStatementSyntax } assignment + => assignment.Left == node || assignment.Right == node, + ForEachVariableStatementSyntax forEach => forEach.Variable == node, + _ => false, + }; } /// Refuses [MethodImpl] flags outside , however spelled. @@ -401,12 +494,12 @@ public static class ForbiddenTypeAnalyzer foreach (var nested in info.Nested) CheckDeconstruction(nested, span); } - private void CheckSymbol(ISymbol symbol, TextSpan span) + private void CheckSymbol(ISymbol symbol, TextSpan span, bool deconstructionOnly = false) { switch (symbol) { case ITypeSymbol type: - CheckType(type, span); + CheckType(type, span, deconstructionOnly); break; case IMethodSymbol method: if (method.MethodKind is MethodKind.LocalFunction or MethodKind.AnonymousFunction) @@ -418,6 +511,7 @@ public static class ForbiddenTypeAnalyzer CheckMember(method.ReducedFrom ?? method, span); foreach (var arg in method.TypeArguments) CheckType(arg, span); if (!method.ReturnsVoid) CheckType(method.ReturnType, span); + if (method.MethodKind == MethodKind.Constructor) CheckConstructor(method, span); break; case IPropertySymbol property: CheckMember(property, span); @@ -436,6 +530,33 @@ public static class ForbiddenTypeAnalyzer } } + /// + /// Constructors that would let a script nest a value inside one of the same kind without limit: an + /// exception constructor taking an inner exception (or any object, e.g. + /// ArgumentOutOfRangeException's actualValue, which its Message renders) — a loop builds + /// a million-deep chain whose ToString / Message recurse past the stack, in the script or in + /// the host's log sink — and a host record with an open-typed member (new DataValueSnapshot(o, …)). + /// + private void CheckConstructor(IMethodSymbol constructor, TextSpan span) + { + var type = constructor.ContainingType; + if (type is null || IsSourceSymbol(type) || type.IsAnonymousType) return; + var ns = type.ContainingNamespace?.ToDisplayString() ?? string.Empty; + if (DerivesFrom(type, ExceptionFullName) + && constructor.Parameters.FirstOrDefault(p => IsExceptionChainSlot(p.Type)) is { } inner) + { + Add(span, $"{TypeKey(type.OriginalDefinition)}..ctor", ns, + $"This '{type.Name}' constructor takes '{inner.Name}' ({inner.Type.ToDisplayString()}): a script may not " + + "wrap one exception (or an arbitrary value) inside another — a chain built in a loop overflows the " + + "stack when it is rendered (see ForbiddenTypeAnalyzer). Use a constructor taking only a message."); + return; + } + if (type.IsRecord && OpenMember(type) is { } openMember) + Add(span, $"{TypeKey(type.OriginalDefinition)}..ctor", ns, + $"A script may not build a '{type.ToDisplayString()}' (its member '{openMember}' holds any value, so one " + + "can be nested in another without limit; see ForbiddenTypeAnalyzer)."); + } + private void CheckMember(ISymbol member, TextSpan span) { var declaring = member.ContainingType; @@ -450,7 +571,7 @@ public static class ForbiddenTypeAnalyzer if (ForbiddenMemberSet.Contains(pair)) { Add(span, display, ns, - $"Member '{display}' is on the sandbox forbidden-member list: it changes process-wide state " + + $"Member '{display}' is on the sandbox forbidden-member list: it changes process-wide state or escapes another rule " + "(see ForbiddenTypeAnalyzer.ForbiddenMembers)."); return; } @@ -472,7 +593,11 @@ public static class ForbiddenTypeAnalyzer "sandbox allow-list (see ForbiddenTypeAnalyzer.AllowedTypes)."); } - private void CheckType(ITypeSymbol? type, TextSpan span) + /// The type. + /// Where to report. + /// The expression is a tuple that is only deconstructed (never held), so a + /// tuple with an open element type is allowed there — see . + private void CheckType(ITypeSymbol? type, TextSpan span, bool deconstructionOnly = false) { switch (type) { @@ -481,7 +606,19 @@ public static class ForbiddenTypeAnalyzer case ITypeParameterSymbol: return; case IArrayTypeSymbol array: - CheckType(array.ElementType, span); + // An array whose element can be an array (object[], Array[], IList[] …) can nest or contain itself; + // the HOST copies a returned array recursively (OwnedDataSample.CopyLegacy) and compares it + // structurally (VirtualTagActor.SameValue), so such a value overflowed the host's stack after the + // run (lmxopcua#971 review). Typed and jagged arrays (int[][]) nest only as deep as the source. + if (IsOpenSlot(array.ElementType) || array.ElementType.SpecialType == SpecialType.System_Array) + { + Add(span, type.ToDisplayString(), string.Empty, + $"An array of '{array.ElementType.ToDisplayString()}' can contain itself or nest without limit, " + + "which the server's own copy / compare of a script value recurses over — use a typed array " + + "(double[], string[], …) — see ForbiddenTypeAnalyzer."); + return; + } + CheckType(array.ElementType, span, deconstructionOnly); return; case IPointerTypeSymbol or IFunctionPointerTypeSymbol: Add(span, type.ToDisplayString(), string.Empty, $"Pointer type '{type.ToDisplayString()}' is not allowed in a script."); @@ -495,7 +632,16 @@ public static class ForbiddenTypeAnalyzer "(see ForbiddenTypeAnalyzer.AllowedTypes / AllowedNamespaces)."); return; } - foreach (var arg in named.TypeArguments) CheckType(arg, span); + if (!deconstructionOnly && OpenHolderElement(named) is { } open) + { + Add(span, named.ToDisplayString(), named.ContainingNamespace?.ToDisplayString() ?? string.Empty, + $"'{named.ToDisplayString()}' holds a value of type '{open.ToDisplayString()}', which can be " + + "another one of itself: nested in a loop, its ToString / Equals / GetHashCode then recurse past " + + "the stack and terminate the server. Give the tuple / pair / anonymous type a concrete element " + + "type (e.g. Convert.ToDouble(v.Value)) — see ForbiddenTypeAnalyzer."); + return; + } + foreach (var arg in named.TypeArguments) CheckType(arg, span, deconstructionOnly); return; default: // dynamic and anything else unrecognised. @@ -512,6 +658,7 @@ public static class ForbiddenTypeAnalyzer var def = type.OriginalDefinition; if (def.ContainingType is { } outer) return IsTypeAllowedShallow(outer); var key = TypeKey(def); + if (ExcludedTypeSet.Contains(key)) return false; if (AllowedTypeSet.Contains(key) || RestrictedTypeMembers.ContainsKey(key)) return true; var ns = def.ContainingNamespace?.ToDisplayString() ?? string.Empty; if (AllowedNamespaceSet.Contains(ns)) return true; @@ -529,6 +676,41 @@ public static class ForbiddenTypeAnalyzer } } + /// + /// An element / member type that can hold an instance of the holder around it: object, + /// ValueType, an interface, a type parameter or dynamic (or a Nullable of one). + /// + private static bool IsOpenSlot(ITypeSymbol type) => type switch + { + { SpecialType: SpecialType.System_Object or SpecialType.System_ValueType } => true, + { TypeKind: TypeKind.Interface or TypeKind.TypeParameter or TypeKind.Dynamic } => true, + INamedTypeSymbol { OriginalDefinition.SpecialType: SpecialType.System_Nullable_T } nullable => IsOpenSlot(nullable.TypeArguments[0]), + _ => false, + }; + + /// The open element type of a instance or anonymous type, if any. + private static ITypeSymbol? OpenHolderElement(INamedTypeSymbol type) + { + if (type.IsAnonymousType) + return type.GetMembers().OfType().Select(p => p.Type).FirstOrDefault(IsOpenSlot); + return RecursiveHolderTypes.Contains(TypeKey(type.OriginalDefinition)) + ? type.TypeArguments.FirstOrDefault(IsOpenSlot) + : null; + } + + /// The name of a record's first instance property of an open type (its synthesized members recurse into it). + private static string? OpenMember(INamedTypeSymbol record) + => record.GetMembers().OfType().FirstOrDefault(p => !p.IsStatic && IsOpenSlot(p.Type))?.Name; + + /// A constructor parameter through which one exception can carry another (or any value). + private static bool IsExceptionChainSlot(ITypeSymbol type) => type switch + { + _ when IsOpenSlot(type) => true, + IArrayTypeSymbol array => IsExceptionChainSlot(array.ElementType), + INamedTypeSymbol named => DerivesFrom(named, ExceptionFullName) || named.TypeArguments.Any(IsExceptionChainSlot), + _ => false, + }; + private static bool DerivesFrom(INamedTypeSymbol type, string fullName) { for (var t = type; t is not null; t = t.BaseType) diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs index 693be8107..ab5bf74f8 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Core.Scripting.Tests/ForbiddenTypeAnalyzerTests.cs @@ -96,8 +96,68 @@ public sealed class ForbiddenTypeAnalyzerTests { "MethodImpl-Synchronized", """[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] static int F() => 1; return F();""" }, { "MethodImpl-numeric", """[System.Runtime.CompilerServices.MethodImpl((System.Runtime.CompilerServices.MethodImplOptions)4096)] static int F() => 1; return F();""" }, { "MethodImpl-short-ctor", """[System.Runtime.CompilerServices.MethodImpl((short)32)] static int F() => 1; return F();""" }, + + // Sibling class (lmxopcua#971 review): recursion with NO script frame for the #779 guard to check — a BCL + // (or compiler-synthesized) ToString / GetHashCode / Equals / CompareTo / Message that recurses over a deep + // or cyclic structure the script built in a loop. Each of these terminated the host with "Stack overflow." + // (and a returned / logged structure would do the same in host code, outside the run). + { "Tuple-chain-ToString", """object o = 0; for (var i = 0; i < 1_000_000; i++) o = Tuple.Create(o); return o.ToString();""" }, + { "ValueTuple-chain-GetHashCode", """object o = 0; for (var i = 0; i < 1_000_000; i++) o = ValueTuple.Create(o); return o.GetHashCode();""" }, + { "tuple-literal-chain-Compare", """object a = 0, b = 0; for (var i = 0; i < 1_000_000; i++) { a = (a, 1); b = (b, 1); } return System.Collections.Generic.Comparer.Default.Compare(a, b);""" }, + { "KeyValuePair-chain", """object o = 0; for (var i = 0; i < 1_000_000; i++) o = new System.Collections.Generic.KeyValuePair(o, 1); return o.ToString();""" }, + { "anonymous-type-chain", """object o = 0; for (var i = 0; i < 1_000_000; i++) o = new { o }; return o.ToString();""" }, + { "generic-local-function-tuple", """static object Wrap(T x) => Tuple.Create(x); object o = 0; for (var i = 0; i < 1_000_000; i++) o = Wrap(o); return o.ToString();""" }, + { "Lazy-self-cycle", """Lazy l = null!; l = new Lazy(() => l); _ = l.Value; return l.ToString();""" }, + { "StructuralComparisons-cycle", """object[] a = new object[1]; a[0] = a; return System.Collections.StructuralComparisons.StructuralEqualityComparer.GetHashCode(a);""" }, + { "IStructuralEquatable", """System.Collections.IStructuralEquatable a = new object[1]; return 0;""" }, + { "DictionaryEntry-chain", """object o = 0; for (var i = 0; i < 1_000_000; i++) o = new System.Collections.DictionaryEntry(o, 1); return o.ToString();""" }, + { "FormattableString-chain", """object o = 0; for (var i = 0; i < 1_000_000; i++) { FormattableString f = $"{o}"; o = f; } return o.ToString();""" }, + { "IFormattable-interpolation", """IFormattable f = $"{1}"; return f.ToString(null, null);""" }, + { "DataValueSnapshot-with-chain", """var s = ctx.GetTag("x"); object o = s; for (var i = 0; i < 1_000_000; i++) o = s with { Value = o }; return o.GetHashCode();""" }, + { "DataValueSnapshot-ctor", """return new DataValueSnapshot(1, 0u, null, DateTime.UtcNow);""" }, + { "Exception-inner-chain", """Exception e = new Exception("x"); for (var i = 0; i < 1_000_000; i++) e = new Exception("x", e); return e.ToString();""" }, + { "AggregateException-chain", """Exception e = new Exception("x"); for (var i = 0; i < 1_000_000; i++) e = new AggregateException(e); return e.Message;""" }, + { "ArgumentOutOfRange-actualValue-chain", """Exception e = new Exception("x"); for (var i = 0; i < 1_000_000; i++) e = new ArgumentOutOfRangeException("p", e, "m"); return e.Message;""" }, + // Array.Sort / List.Sort / BinarySearch catch a comparer's exception and rethrow it wrapped — from the catch + // funclet, on top of the frames being unwound — so a comparer that recurses through Sort overflowed while + // unwinding (a BCL handler the script's guarded catch/finally cannot reach). Comparison is the only way a + // script supplies comparer code (it declares no types), so it is off the list: use OrderBy / ThenBy. + { "Sort-Comparison-recursion", """int Rec(int d) { var a = new[] { 2, 1 }; Array.Sort(a, (x, y) => Rec(d + 1)); return 0; } return Rec(0);""" }, + { "List-Sort-Comparison", """var l = new System.Collections.Generic.List { 2, 1 }; l.Sort((x, y) => x - y); return l[0];""" }, + { "Comparer-Create", """var c = System.Collections.Generic.Comparer.Create((x, y) => x - y); return c.Compare(1, 2);""" }, + // A returned array is copied (OwnedDataSample.CopyLegacy, recursive over nested arrays) and compared + // structurally (VirtualTagActor.SameValue, ShadowScriptRunner) by HOST code: an object[] nested a million deep, + // or containing itself, overflowed the host's stack after the run. Arrays may not have an element type that + // can hold an array — and Array.CreateInstance (an object[] behind a System.Array) is refused with them. + { "object-array-chain", """object o = 0; for (var i = 0; i < 1_000_000; i++) o = new object[] { o }; return o;""" }, + { "object-array-cycle", """var a = new object[1]; a[0] = a; return a;""" }, + { "Array-element-array", """var a = new Array[1]; a[0] = a; return a;""" }, + { "Array-CreateInstance-cycle", """Array a = Array.CreateInstance(typeof(int), 1); return a.Length;""" }, + { "ToArray-object", """return new System.Collections.Generic.List { 1 }.ToArray();""" }, }; + /// + /// The legitimate neighbours of the deep-data rows above keep compiling: closed tuples / pairs / anonymous + /// types, a tuple literal that is only deconstructed, FormattableString.Invariant, default-comparer + /// sorting and key-based ordering, exceptions without an inner exception, and reading a snapshot. + /// + /// The script body. + [Theory] + [InlineData("""var t = (1, "a"); var p = Tuple.Create(1.5, "b"); return t.Item1 + p.Item1 + t.ToString().Length + p.GetHashCode() * 0;""")] + [InlineData("""var (v, q) = (ctx.GetTag("x").Value, ctx.GetTag("x").StatusCode); return v is null ? (int)q : 1;""")] + [InlineData("""ctx.Logger.Information("{@X}", new { A = 1, B = "s" }); return 0;""")] + [InlineData("""var d = new System.Collections.Generic.Dictionary { ["a"] = 1 }; var n = 0; foreach (var kv in d) n += kv.Value; foreach (var (k, val) in d) n += val + k.Length; return n;""")] + [InlineData("""var x = 1.5; return FormattableString.Invariant($"{x:F2}") + FormattableString.Invariant($"{x} {ctx.GetTag("x").Value}");""")] + [InlineData("""var a = new[] { 3, 1, 2 }; Array.Sort(a); var l = new System.Collections.Generic.List { 2, 1 }; l.Sort(); return a[0] + l[0] + l.OrderBy(i => -i).ThenBy(i => i).First() + Array.BinarySearch(a, 2);""")] + [InlineData("""try { throw new ArgumentOutOfRangeException("p", "m"); } catch (ArgumentException e) { return new InvalidOperationException(e.Message).Message.Length; }""")] + [InlineData("""var s = ctx.GetTag("x"); return s.Value is null && s == ctx.GetTag("x") ? s.GetHashCode() * 0 + s.ToString().Length : 0;""")] + [InlineData("""var j = new int[2][]; j[0] = new[] { 1 }; ctx.Logger.Information("{A} {B}", 1, ctx.GetTag("x").Value); return string.Format("{0}{1}", 1, ctx.GetTag("x").Value) + j[0][0] + new double[] { 1.5 }.Length + string.Join(",", new[] { "a" });""")] + public async Task Closed_neighbour_of_a_deep_data_refusal_still_compiles(string source) + { + using var evaluator = ScriptEvaluator.Compile(source); + _ = await evaluator.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken); + } + /// /// Siblings of the lmxopcua#971 review that are SAFE and must keep compiling: compiler-lowered constructs whose /// synthesized code runs on the evaluating thread, inside the run, under the stack guard. From 35d14936ac86418b864bf0975dc9840e300f5310 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:21:23 -0500 Subject: [PATCH 4/6] =?UTF-8?q?fix(sql):=20#974=20review=20=E2=80=94=20par?= =?UTF-8?q?se=20SqlServer/Odbc=20named=20queries=20as=20T-SQL;=20';'=20is?= =?UTF-8?q?=20not=20a=20statement=20boundary?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The named-query guard's only statement boundary was ';', but T-SQL runs ';'-less batches: 'SELECT 1 COMMIT KILL 55', '... COMMIT DISABLE TRIGGER ALL ON DATABASE', '... COMMIT SHUTDOWN WITH NOWAIT' and a TEXTPTR/WRITETEXT write were all accepted for SqlServer AND Odbc — a COMMIT ending the rolled-back transaction, then anything not on the keyword list. For SqlServer, and for Odbc / no provider (backend unknown: strictest reading), SqlReadOnlyStatement now also parses the statement with Microsoft.SqlServer.TransactSql.ScriptDom 180.154.0 (central package pin; both QUOTED_IDENTIFIER settings) and requires exactly one batch holding exactly one SelectStatement, no INTO, and no OPENQUERY/OPENROWSET/OPENDATASOURCE. Odbc '?' markers are read as variables for the parse. The lexical guard stays as a second layer. Tests: SqlReadOnlyStatementTransactSqlTests (11 batch strings x SqlServer/Odbc/ none, pass-through rowsets — all failed first; CTE/subquery/window/param/UNION/ FOR XML/OPTION and ODBC '?' positive controls). SqlNamedQueryTests' SQLite-backed Odbc stand-in used the T-SQL reserved word 'top' as an alias (renamed). Live (SQL Server 10.100.0.35,14330): SqlServerNamedQueryBatchLiveTests proves 'SELECT 1 AS v COMMIT UPDATE ...' commits the old way, the guard refuses it, and a CTE+window+subquery+@param query reads Good; SqlServerReadTests / write-mode / trigger suites unchanged (30/30). Class comment and docs/drivers/Sql.md corrected. Co-Authored-By: Claude --- .claude/rules/drivers.md | 2 +- Directory.Packages.props | 2 + docs/drivers/Sql.md | 22 ++- .../SqlReadOnlyStatement.cs | 111 ++++++++++++++- ...MOM.WW.OtOpcUa.Driver.Sql.Contracts.csproj | 3 + .../SqlServerNamedQueryBatchLiveTests.cs | 129 ++++++++++++++++++ .../SqlNamedQueryTests.cs | 16 +-- .../SqlReadOnlyStatementTransactSqlTests.cs | 81 +++++++++++ 8 files changed, 349 insertions(+), 17 deletions(-) create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests/SqlServerNamedQueryBatchLiveTests.cs create mode 100644 tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests/SqlReadOnlyStatementTransactSqlTests.cs diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index f43bfbd00..02726021e 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -228,7 +228,7 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa provider-less call site. Execution: `ISqlDialect.BeginNamedQueryAsync` (PG/Oracle `SET TRANSACTION READ ONLY`, MySQL read-only session + txn, restored by `EndNamedQueryAsync`) and `SealNamedQueryCommand` (PG rewrites `@name` to positional `$n` — Npgsql then sends unsplit and the server refuses a 2nd statement; a parameterless query gets - one unused typed `$1`). SQL Server / MySQL still execute batches: the lexer + a SELECT-only login are the line. + one unused typed `$1`). SQL Server / MySQL still execute batches: the guard + a SELECT-only login are the line — and since T-SQL needs no `;` between statements, SqlServer/Odbc/no-provider statements are also PARSED (`Microsoft.SqlServer.TransactSql.ScriptDom`): exactly one batch, one `SELECT`, no `INTO`, no `OPENQUERY`/`OPENROWSET`/`OPENDATASOURCE` (2026-12-02 review). Key-value rows attribute by `SqlKeyMatcher` (exact → typed/padding → collation; #987), and SQL Server table writes count the statement's own `@@ROWCOUNT` via an OUTPUT param (trigger DML no longer counts). - **FOCAS / AbLegacy:** background loops are joined (≤ 5 s) on shutdown. diff --git a/Directory.Packages.props b/Directory.Packages.props index da59c68d0..7dfa66fe3 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -97,6 +97,8 @@ + +