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.