Merge security review fixes: sandbox refuses async/stackalloc/MethodImpl, unwinding-overflow guard, deep-data types (#971); T-SQL ScriptDom single-SELECT guard (#974); Auth 0.5.0 directory re-query on revalidation (#975); fleet-diagnostics target check (#973)

This commit is contained in:
Joseph Doherty
2026-12-03 12:27:35 -05:00
25 changed files with 1299 additions and 71 deletions
@@ -20,12 +20,31 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// </para>
/// <para>
/// <b>Limits.</b> 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 — <c>Tuple</c> / <c>ValueTuple</c> / <c>KeyValuePair</c> / anonymous-type
/// <c>ToString</c> / <c>Equals</c> / <c>GetHashCode</c> over a structure a script nested a million deep in a
/// loop, a self-referencing <c>Lazy</c>, <c>StructuralComparisons</c> over a self-containing array, an
/// inner-exception chain's <c>ToString</c> — so <c>ForbiddenTypeAnalyzer</c> now refuses the constructs that
/// build such structures (open-element holders, <c>Lazy</c>, the structural comparers, exception
/// constructors taking an inner exception, held <c>FormattableString</c>s, host records with an
/// <c>object</c> 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).
/// </para>
/// <para>
/// <b>Exception handlers (lmxopcua#971 review 2026-12-02).</b> Checking frames is not enough on its own: a
/// <c>catch</c> or <c>finally</c> block runs as a funclet <em>on top of</em> the frames being unwound, so a
/// handler that throws (<c>throw;</c>, <c>throw new …</c>, 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
/// <see cref="CanHandle"/>: a <c>catch</c> gains the filter <c>when (CanHandle() &amp;&amp; …)</c> and a
/// <c>finally</c> body runs only <c>if (CanHandle())</c>. 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 <c>finally</c> is only possible on a run that is already
/// failing on an exhausted stack.
/// </para>
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class ScriptStackGuard
@@ -38,6 +57,14 @@ public static class ScriptStackGuard
if (!RuntimeHelpers.TryEnsureSufficientExecutionStack())
throw new ScriptStackExhaustedException();
}
/// <summary>
/// True while the current thread has stack to spare for a script exception handler (see the remarks). Called
/// by compiled scripts from every <c>catch</c> filter and <c>finally</c> block; not part of the script
/// authoring surface.
/// </summary>
/// <returns>False when the remaining stack is below the runtime's safety margin.</returns>
public static bool CanHandle() => RuntimeHelpers.TryEnsureSufficientExecutionStack();
}
/// <summary>
@@ -49,7 +49,11 @@ namespace ZB.MOM.WW.OtOpcUa.Core.Scripting;
/// return-type check is what keeps reflection handles out of reach: <c>Exception.TargetSite</c> is a member
/// of an allowed type but returns a <c>MethodBase</c>. (3) A few syntactic forms are refused outright
/// (<see cref="IsForbiddenSyntax"/>): <c>__makeref</c>/<c>__refvalue</c>/<c>__reftype</c>/<c>__arglist</c>,
/// <c>lock</c> (a blocking primitive on a possibly-shared object) and <c>extern</c> local functions.
/// <c>lock</c> (a blocking primitive on a possibly-shared object), <c>extern</c> local functions,
/// <c>async</c> lambdas / local functions and <c>stackalloc</c> (each terminated the host —
/// lmxopcua#971 review 2026-12-02); <c>[MethodImpl]</c> is limited to the JIT hint bits. (4) Members the
/// compiler calls without a name in the source — query operators, <c>foreach</c>'s enumerator pattern,
/// <c>Deconstruct</c>, a collection initializer's <c>Add</c> — are checked like named ones.
/// </para>
/// <para>
/// <b>Defence in depth.</b> <see cref="ScriptSandbox"/> also references only the handful of BCL assemblies
@@ -102,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",
@@ -133,6 +141,21 @@ public static class ForbiddenTypeAnalyzer
"Serilog.ILogger", "Serilog.Events.LogEventLevel",
];
/// <summary>
/// Types refused although their namespace is in <see cref="AllowedNamespaces"/> (or, for exceptions, they are a
/// <c>System.Exception</c> subclass in <c>System</c>): 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).
/// <c>StructuralComparisons</c> / <c>IStructuralEquatable</c> / <c>IStructuralComparable</c> compare an array
/// that contains itself forever; <c>DictionaryEntry.ToString</c> renders an <c>object</c> key and value;
/// <c>AggregateException.Message</c> / <c>ToString</c> render every inner exception.
/// </summary>
public static readonly IReadOnlyList<string> ExcludedTypes =
[
"System.Collections.StructuralComparisons", "System.Collections.IStructuralEquatable",
"System.Collections.IStructuralComparable", "System.Collections.DictionaryEntry",
"System.AggregateException",
];
/// <summary>
/// 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). <c>System.Type</c> is the reflection gateway — <c>typeof(x)</c>,
@@ -167,7 +190,7 @@ public static class ForbiddenTypeAnalyzer
("System.Reflection.MemberInfo", "Name"),
];
/// <summary>Members refused on otherwise-allowed types: process-wide state.</summary>
/// <summary>Members refused on otherwise-allowed types: process-wide state, and the untyped array factory.</summary>
public static readonly IReadOnlyList<(string Type, string Member)> ForbiddenMembers =
[
// Ambient culture is process / pool-thread state (lmxopcua#792): name InvariantCulture or GetCultureInfo.
@@ -182,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";
@@ -189,6 +215,22 @@ public static class ForbiddenTypeAnalyzer
private static readonly HashSet<string> AllowedNamespaceSet = new(AllowedNamespaces, StringComparer.Ordinal);
private static readonly HashSet<string> AllowedTypeSet = new(AllowedTypes, StringComparer.Ordinal);
private static readonly HashSet<string> ExcludedTypeSet = new(ExcludedTypes, StringComparer.Ordinal);
/// <summary>
/// Generic value holders whose <c>ToString</c> / <c>Equals</c> / <c>GetHashCode</c> / <c>CompareTo</c> recurse
/// into their elements (anonymous types' compiler-synthesized members do the same). With an <em>open</em>
/// element type (<see cref="IsOpenSlot"/>) a script can nest one inside another in a loop —
/// <c>o = Tuple.Create(o)</c> 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.
/// </summary>
private static readonly HashSet<string> 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);
@@ -255,9 +297,28 @@ public static class ForbiddenTypeAnalyzer
/// <summary>
/// Syntax refused regardless of binding: the undocumented <c>TypedReference</c> keywords, <c>lock</c> (a
/// blocking monitor on an object that may be shared with the host, e.g. <c>lock (typeof(string))</c>), and
/// <c>extern</c> local functions (a native entry point).
/// blocking monitor on an object that may be shared with the host, e.g. <c>lock (typeof(string))</c>),
/// <c>extern</c> local functions (a native entry point), <c>async</c> lambdas / anonymous methods / local
/// functions, and <c>stackalloc</c>.
/// </summary>
/// <remarks>
/// <para>
/// <b><c>async</c> (lmxopcua#971 review 2026-12-02).</b> 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
/// <c>async void</c> body's exception is not returned to the caller: <c>AsyncVoidMethodBuilder</c>
/// rethrows it on the thread pool, where nothing catches it and the runtime terminates the host
/// (<c>async void Boom() { throw … } Boom();</c> — and an <c>async</c> lambda converted to
/// <c>Action</c> is the same thing). A script is synchronous by contract
/// (<see cref="ScriptEvaluator{TContext, TResult}.RunAsync"/>) and <c>System.Threading.Tasks</c> is not
/// on the allow-list, so there is no legitimate <c>async</c> script code: every form is refused, which
/// also covers <c>await</c>, <c>await foreach</c> and <c>await using</c> (legal only inside one).
/// </para>
/// <para>
/// <b><c>stackalloc</c>.</b> One <c>stackalloc byte[1_500_000_000]</c> overflows the thread's stack inside
/// a single frame — before the next <c>ScriptStackGuard.Check()</c> can run — and a stack overflow is
/// uncatchable. Scripts have heap arrays and <c>Span</c> over them; there is no need for stack buffers.
/// </para>
/// </remarks>
/// <param name="node">The node.</param>
/// <returns>A description of the construct, or null when the node is allowed.</returns>
internal static string? IsForbiddenSyntax(SyntaxNode node) => node switch
@@ -268,9 +329,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,
};
/// <summary>
/// The <see cref="System.Runtime.CompilerServices.MethodImplOptions"/> bits a script's <c>[MethodImpl]</c> may
/// set: JIT inlining / optimization hints only. <c>InternalCall</c> / <c>ForwardRef</c> / <c>Unmanaged</c> /
/// <c>PreserveSig</c> change how the runtime binds the method (an <c>InternalCall</c> local function passes the
/// compiler and fails to load — the publish gate accepted what the runtime refuses), and <c>Synchronized</c>
/// takes a monitor (the <c>lock</c> the analyzer refuses).
/// </summary>
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<ForbiddenTypeRejection> rejections)
{
public void Visit(SyntaxNode node)
@@ -283,9 +363,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);
@@ -310,12 +400,87 @@ 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;
/// <summary>
/// True when <paramref name="expr"/> is a tuple that only exists to be deconstructed — <c>var (a, b) = (x, y)</c>
/// (either side, and the assignment statement itself) or a <c>foreach (var (k, v) in …)</c> target. No
/// tuple value is held, so an open element type there cannot nest.
/// </summary>
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,
};
}
/// <summary>Refuses <c>[MethodImpl]</c> flags outside <see cref="AllowedMethodImplBits"/>, however spelled.</summary>
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)
@@ -329,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)
@@ -346,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);
@@ -364,6 +530,33 @@ public static class ForbiddenTypeAnalyzer
}
}
/// <summary>
/// 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 <c>object</c>, e.g.
/// <c>ArgumentOutOfRangeException</c>'s <c>actualValue</c>, which its <c>Message</c> renders) — a loop builds
/// a million-deep chain whose <c>ToString</c> / <c>Message</c> recurse past the stack, in the script or in
/// the host's log sink — and a host record with an open-typed member (<c>new DataValueSnapshot(o, …)</c>).
/// </summary>
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;
@@ -378,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;
}
@@ -400,7 +593,11 @@ public static class ForbiddenTypeAnalyzer
"sandbox allow-list (see ForbiddenTypeAnalyzer.AllowedTypes).");
}
private void CheckType(ITypeSymbol? type, TextSpan span)
/// <param name="type">The type.</param>
/// <param name="span">Where to report.</param>
/// <param name="deconstructionOnly">The expression is a tuple that is only deconstructed (never held), so a
/// tuple with an open element type is allowed there — see <see cref="IsDeconstructionOnly"/>.</param>
private void CheckType(ITypeSymbol? type, TextSpan span, bool deconstructionOnly = false)
{
switch (type)
{
@@ -409,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.");
@@ -423,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.
@@ -440,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;
@@ -457,6 +676,41 @@ public static class ForbiddenTypeAnalyzer
}
}
/// <summary>
/// An element / member type that can hold an instance of the holder around it: <c>object</c>,
/// <c>ValueType</c>, an interface, a type parameter or <c>dynamic</c> (or a <c>Nullable</c> of one).
/// </summary>
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,
};
/// <summary>The open element type of a <see cref="RecursiveHolderTypes"/> instance or anonymous type, if any.</summary>
private static ITypeSymbol? OpenHolderElement(INamedTypeSymbol type)
{
if (type.IsAnonymousType)
return type.GetMembers().OfType<IPropertySymbol>().Select(p => p.Type).FirstOrDefault(IsOpenSlot);
return RecursiveHolderTypes.Contains(TypeKey(type.OriginalDefinition))
? type.TypeArguments.FirstOrDefault(IsOpenSlot)
: null;
}
/// <summary>The name of a record's first instance property of an open type (its synthesized members recurse into it).</summary>
private static string? OpenMember(INamedTypeSymbol record)
=> record.GetMembers().OfType<IPropertySymbol>().FirstOrDefault(p => !p.IsStatic && IsOpenSlot(p.Type))?.Name;
/// <summary>A constructor parameter through which one exception can carry another (or any value).</summary>
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)
@@ -28,8 +28,16 @@ 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 (<c>Expression&lt;T&gt;</c>) 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 <c>System.Threading.Tasks</c>, so a script cannot
/// produce one that compiles).
/// local functions are left alone: <see cref="ForbiddenTypeAnalyzer"/> refuses every <c>async</c> form
/// (lmxopcua#971 review — an <c>async void</c> one compiled without naming <c>System.Threading.Tasks</c> and
/// its exception terminated the host), so none reaches this rewrite.
/// </para>
/// <para>
/// <b>Exception handlers (lmxopcua#971 review).</b> Every script <c>catch</c> also gets the filter
/// <c>when (ScriptStackGuard.CanHandle() &amp;&amp; (original filter))</c>, and every <c>finally</c> body is
/// wrapped in <c>if (ScriptStackGuard.CanHandle()) { … }</c>: a handler runs on top of the frames being
/// unwound, so one that throws on every frame overflowed the stack while unwinding (see
/// <see cref="ScriptStackGuard"/>). On a healthy stack both are no-ops.
/// </para>
/// <para>
/// Runs after <see cref="ForbiddenTypeAnalyzer"/>, so the analyzer only ever sees the user's code; the
@@ -39,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()";
/// <summary>Returns <paramref name="tree"/> with a stack check at the entry of every script-declared body.</summary>
/// <param name="compilation">The compiled (error-free, analyzer-clean) wrapper compilation.</param>
@@ -64,6 +73,25 @@ internal static class ScriptStackGuardInjector
private sealed class Rewriter(SemanticModel model) : CSharpSyntaxRewriter
{
/// <summary><c>catch … when (f)</c> becomes <c>catch … when (CanHandle() &amp;&amp; (f))</c> — see
/// <see cref="ScriptStackGuard"/>'s "Exception handlers" remarks.</summary>
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));
}
/// <summary><c>finally { b }</c> becomes <c>finally { if (CanHandle()) { b } }</c>.</summary>
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).
@@ -1,4 +1,5 @@
using System.Text;
using Microsoft.SqlServer.TransactSql.ScriptDom;
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
@@ -8,10 +9,20 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
/// and single-statement, where the provider can enforce that (see <c>ISqlDialect.BeginNamedQueryAsync</c>) —
/// and the connecting principal should hold <c>SELECT</c> only. The guard exists so an operator learns at
/// construction — not from a database audit — that a statement is not a plain read.
/// <para>Rules, applied to the text <em>outside</em> string literals, quoted identifiers and comments:
/// the statement begins with <c>SELECT</c> or <c>WITH</c>; it is a single statement (one trailing
/// <c>;</c> is tolerated and removed); and none of the data- or schema-changing keywords appears anywhere
/// — which also refuses <c>SELECT … INTO</c>, <c>FOR UPDATE</c> and a data-modifying CTE.</para>
/// <para>Lexical rules, applied to the text <em>outside</em> string literals, quoted identifiers and comments:
/// the statement begins with <c>SELECT</c> or <c>WITH</c>; it carries no second <c>;</c>-separated statement
/// (one trailing <c>;</c> is tolerated and removed); and none of the data- or schema-changing keywords
/// appears anywhere — which also refuses <c>SELECT … INTO</c>, <c>FOR UPDATE</c> and a data-modifying CTE.</para>
/// <para><b><c>;</c> is NOT a statement boundary in T-SQL (lmxopcua#974, review 2026-12-02).</b> SQL Server
/// runs <c>SELECT 1 COMMIT KILL 55</c> as three statements — no separator needed — so the lexical rules alone
/// accepted, for SqlServer and Odbc, a <c>COMMIT</c> that ends the driver's rolled-back transaction followed by
/// any non-listed statement (<c>DISABLE TRIGGER</c>, <c>KILL</c>, <c>SHUTDOWN</c>, <c>WRITETEXT</c> …). For
/// SqlServer, and for Odbc and no provider (the backend may be SQL Server, so the strictest reading applies),
/// the statement is also <b>parsed</b> with <c>Microsoft.SqlServer.TransactSql.ScriptDom</c> and must be exactly
/// one batch holding exactly one <c>SELECT</c>, with no <c>INTO</c> and no <c>OPENQUERY</c> /
/// <c>OPENROWSET</c> / <c>OPENDATASOURCE</c>. An Odbc statement's positional <c>?</c> markers are read as
/// variables for that parse; anything else SQL Server's grammar does not accept (PostgreSQL <c>::</c> casts,
/// <c>LIMIT</c>) is refused for Odbc. The lexical rules stay as a second, independent layer.</para>
/// <para><b>The lexer is dialect-aware, and refuses what it cannot read exactly as the server does
/// (lmxopcua#974, review finding S-7).</b> Everything above depends on knowing where a literal or comment ends.
/// One lexer for five dialects got that wrong in the direction that matters — it took live SQL for literal
@@ -145,10 +156,102 @@ public static class SqlReadOnlyStatement
"must read the same under every one";
}
// T-SQL needs no ';' between statements (review 2026-12-02): the lexical rules above see one SELECT in
// `SELECT 1 COMMIT KILL 55`, SQL Server runs three. SQL Server — and ODBC / no provider, whose backend may be
// SQL Server, so the strictest reading applies — must also PARSE as exactly one SELECT.
if (provider is null or SqlProvider.SqlServer or SqlProvider.Odbc
&& TransactSqlProblem(agreed!, positional: provider != SqlProvider.SqlServer) is { } tsqlProblem)
{
return provider == SqlProvider.SqlServer
? tsqlProblem
: $"{tsqlProblem} ({DescribeUnknownBackend(provider)} must also be a single SELECT as SQL Server parses it)";
}
normalised = agreed!;
return null;
}
/// <summary>
/// Parses <paramref name="statement"/> with the SQL Server parser (under both <c>QUOTED_IDENTIFIER</c>
/// settings) and returns the problem unless it is exactly one batch holding exactly one <c>SELECT</c> with no
/// <c>INTO</c> and no pass-through rowset (<c>OPENQUERY</c> / <c>OPENROWSET</c> / <c>OPENDATASOURCE</c>, which
/// run text on another server or read a file).
/// </summary>
/// <param name="statement">The lexically-accepted, normalised statement.</param>
/// <param name="positional">The statement may carry positional <c>?</c> markers (ODBC), which T-SQL spells
/// <c>@name</c>: each one outside a literal / comment is read as a variable for the parse.</param>
private static string? TransactSqlProblem(string statement, bool positional)
{
var text = positional ? PositionalMarkersAsVariables(statement) : statement;
foreach (var quotedIdentifiers in (ReadOnlySpan<bool>)[true, false])
{
var parser = new TSql170Parser(quotedIdentifiers);
TSqlFragment fragment;
IList<ParseError> errors;
using (var reader = new StringReader(text)) fragment = parser.Parse(reader, out errors);
if (errors.Count > 0)
{
var first = errors[0];
return $"the statement does not parse as T-SQL ({first.Message} at line {first.Line}, column {first.Column})";
}
if (fragment is not TSqlScript script || script.Batches.Count != 1 || script.Batches[0].Statements.Count != 1)
{
var count = (fragment as TSqlScript)?.Batches.Sum(b => b.Statements.Count) ?? 0;
return $"the statement carries more than one statement ({count} as SQL Server parses it — T-SQL runs " +
"statements one after another without ';' between them, and GO separates batches); a named " +
"query must be one SELECT";
}
if (script.Batches[0].Statements[0] is not SelectStatement select)
return "a named query must be a single SELECT (or WITH … SELECT) statement";
if (select.Into is not null)
return "a named query must be read-only, and SELECT … INTO creates a table";
var passThrough = new PassThroughRowsetFinder();
select.Accept(passThrough);
if (passThrough.Found is { } rowset)
return $"a named query may not read through {rowset}: it runs text on another server (or reads a " +
"file), outside the driver's read-only transaction";
}
return null;
}
/// <summary>Replaces every positional <c>?</c> outside literals and comments (SQL Server lexicon) with <c>@pN</c>.</summary>
private static string PositionalMarkersAsVariables(string statement)
{
if (Mask(statement, SqlServer, out var code) is not null) return statement;
var builder = new StringBuilder(statement.Length + 8);
var n = 0;
for (var i = 0; i < statement.Length; i++)
{
if (code[i] == '?') builder.Append("@p").Append(n++.ToString(System.Globalization.CultureInfo.InvariantCulture)).Append(' ');
else builder.Append(statement[i]);
}
return builder.ToString();
}
/// <summary>Finds a rowset source that executes on another server or reads a file.</summary>
private sealed class PassThroughRowsetFinder : TSqlFragmentVisitor
{
public string? Found { get; private set; }
public override void ExplicitVisit(OpenQueryTableReference node) { Found ??= "OPENQUERY"; base.ExplicitVisit(node); }
public override void ExplicitVisit(OpenRowsetTableReference node) { Found ??= "OPENROWSET"; base.ExplicitVisit(node); }
public override void ExplicitVisit(BulkOpenRowset node) { Found ??= "OPENROWSET(BULK …)"; base.ExplicitVisit(node); }
public override void ExplicitVisit(InternalOpenRowset node) { Found ??= "OPENROWSET"; base.ExplicitVisit(node); }
public override void ExplicitVisit(OpenRowsetCosmos node) { Found ??= "OPENROWSET"; base.ExplicitVisit(node); }
public override void ExplicitVisit(AdHocTableReference node) { Found ??= "OPENDATASOURCE"; base.ExplicitVisit(node); }
}
private static string DescribeUnknownBackend(SqlProvider? provider) => provider == SqlProvider.Odbc
? "an Odbc driver's backend is unknown, so its statement"
: "a statement checked without a provider";
@@ -7,6 +7,9 @@
<NoWarn>$(NoWarn);CS1591</NoWarn>
<RootNamespace>ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.SqlServer.TransactSql.ScriptDom" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Core\ZB.MOM.WW.OtOpcUa.Core.Abstractions\ZB.MOM.WW.OtOpcUa.Core.Abstractions.csproj" />
</ItemGroup>
@@ -23,9 +23,11 @@ public static class FleetDiagnosticsTargets
{
// host:port where host is a DNS name / IPv4 literal. No '/', '@', whitespace, '[' or '?' — anything that
// could re-target the actor path or smuggle a second address into the akka.tcp URI. (IPv6 literals are
// not representable in the NodeId host:port form the fleet uses.)
// not representable in the NodeId host:port form the fleet uses.) ASCII digits only and \z, not $
// (review 2026-12-02): \d matches any Unicode decimal digit (int.Parse then threw and took the page down),
// and $ also matches before a trailing '\n' (which int.Parse ignored, so a newline reached the akka address).
private static readonly Regex WellFormed = new(
@"^[A-Za-z0-9._-]{1,253}:\d{1,5}$",
@"^[A-Za-z0-9._-]{1,253}:[0-9]{1,5}\z",
RegexOptions.Compiled | RegexOptions.CultureInvariant,
TimeSpan.FromMilliseconds(100));
@@ -36,8 +38,9 @@ public static class FleetDiagnosticsTargets
{
if (string.IsNullOrEmpty(value) || value.Length > 260) return false;
if (!WellFormed.IsMatch(value)) return false;
var port = int.Parse(value[(value.LastIndexOf(':') + 1)..], System.Globalization.CultureInfo.InvariantCulture);
return port is >= 1 and <= 65535;
return int.TryParse(value.AsSpan(value.LastIndexOf(':') + 1), System.Globalization.NumberStyles.None,
System.Globalization.CultureInfo.InvariantCulture, out var port)
&& port is >= 1 and <= 65535;
}
/// <summary>The <c>Host:AkkaPort</c> dial target of every enabled <c>ClusterNode</c> row.</summary>
@@ -32,7 +32,7 @@ namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;
/// <c>"dev"</c>) so the dev session can navigate the full Admin UI (renamed from the prior
/// <c>"FleetAdmin"</c> to the canonical <c>"Administrator"</c>).
/// </remarks>
public sealed class OtOpcUaLdapAuthService : ILdapAuthService
public sealed class OtOpcUaLdapAuthService : ILdapAuthService, ILdapGroupLookup
{
private readonly LdapOptions _options;
private readonly LibILdapAuthService _inner;
@@ -130,6 +130,29 @@ public sealed class OtOpcUaLdapAuthService : ILdapAuthService
};
}
/// <summary>
/// Passwordless directory group lookup (shared library 0.5.0) for AdminUI session re-validation
/// (lmxopcua#975 review): re-reads a signed-in user's groups without their password, applying the same
/// app-only concerns as <see cref="AuthenticateAsync"/> — <see cref="LdapOptions.Enabled"/> off ⇒
/// <see cref="LdapGroupLookupStatus.ProviderDisabled"/>; <see cref="LdapOptions.DevStubMode"/> ⇒ the stub's
/// <c>dev</c> group, no network; a plaintext transport without <see cref="LdapOptions.AllowInsecure"/> ⇒
/// <see cref="LdapGroupLookupStatus.NotSupported"/>. Never throws except for cancellation.
/// </summary>
/// <param name="username">The signed-in (canonical) username.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The lookup result.</returns>
public async Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (!_options.Enabled) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.ProviderDisabled);
if (string.IsNullOrWhiteSpace(username)) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
if (_options.DevStubMode) return LdapGroupLookupResult.Found(username, username, ["dev"]);
if (_options.Transport == LdapTransport.None && !_options.AllowInsecure)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
if (_inner is not ILdapGroupLookup lookup) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
return await lookup.GetUserGroupsAsync(username, ct).ConfigureAwait(false);
}
/// <summary>Folds a structured library failure code into the app's user-facing error text.</summary>
/// <param name="failure">The library failure code (null defensively treated as a generic error).</param>
private static string FailureToError(LdapAuthFailure? failure) => failure switch
@@ -0,0 +1,21 @@
using ZB.MOM.WW.Auth.Abstractions.Ldap;
namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;
/// <summary>
/// The directory group lookup when the registered app LDAP service cannot do one (a test or dev stub): answers
/// every call <see cref="LdapGroupLookupStatus.NotSupported"/>, which AdminUI session re-validation treats as
/// "re-map the groups recorded at sign-in".
/// </summary>
internal sealed class UnsupportedLdapGroupLookup : ILdapGroupLookup
{
/// <summary>The shared instance.</summary>
public static readonly UnsupportedLdapGroupLookup Instance = new();
/// <inheritdoc />
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
return Task.FromResult(LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported));
}
}
@@ -106,6 +106,15 @@ public static class ServiceCollectionExtensions
// driver path) ends up with exactly one descriptor regardless of registration order.
services.TryAddSingleton<ILdapAuthService, OtOpcUaLdapAuthService>();
// lmxopcua#975 (review 2026-12-02): the passwordless directory group lookup (ZB.MOM.WW.Auth 0.5.0) that
// session re-validation uses to re-read a signed-in user's groups. It is the SAME instance as the app's
// LDAP service (so it shares the Enabled / DevStubMode / transport rules and the library's sticky endpoint
// preference); a host that registers its own ILdapAuthService (a test stub) gets a NotSupported lookup,
// which re-validation treats as "re-map the sign-in groups" — the pre-0.5.0 behaviour.
services.TryAddSingleton<ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup>(sp =>
sp.GetRequiredService<ILdapAuthService>() as ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup
?? UnsupportedLdapGroupLookup.Instance);
// Shared ZB.MOM.WW.Auth group→role mapper seam. Wraps the existing RoleMapper.Map +
// RoleMapper.Merge logic; consumed by AuthEndpoints.cs (/auth/login) and by
// AdminUI login (the OPC UA data plane uses API keys). Scoped to match
@@ -2,8 +2,10 @@ using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.Auth.Abstractions.Roles;
using ZB.MOM.WW.Auth.AspNetCore;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.Security.Session;
@@ -39,14 +41,24 @@ public sealed record SessionRevalidation(
/// </summary>
/// <remarks>
/// <para>
/// <b>No LDAP traffic.</b> The re-check re-runs the stored sign-in groups through
/// <c>IGroupRoleMapper&lt;string&gt;</c> (appsettings <c>GroupToRole</c> + DB
/// <c>LdapGroupRoleMapping</c>), so it costs one indexed ConfigDb read per
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> per session and never hammers the
/// directory. What it therefore CANNOT see is a change to the user's directory group membership
/// itself — the shared <c>ZB.MOM.WW.Auth.Ldap</c> client offers no password-less group lookup.
/// That window is bounded instead by <see cref="OtOpcUaCookieOptions.MaxSessionMinutes"/>, an absolute
/// session lifetime the sliding cookie cannot extend.
/// <b>Directory groups are re-read (lmxopcua#975 review 2026-12-02).</b> Each re-check first asks the
/// directory for the user's CURRENT groups through the passwordless <see cref="ILdapGroupLookup"/>
/// (<c>ZB.MOM.WW.Auth</c> 0.5.0 — a service-account search, no user password), then maps them through
/// <c>IGroupRoleMapper&lt;string&gt;</c> (appsettings <c>GroupToRole</c> + DB <c>LdapGroupRoleMapping</c>).
/// Cost: one directory search + one indexed ConfigDb read per
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> per session. The account gone, disabled,
/// ambiguous or in no group ⇒ the session ends. Before 0.5.0 the cookie's sign-in groups were re-mapped,
/// so removing a user from a directory group changed nothing until the absolute lifetime ended the
/// session.
/// </para>
/// <para>
/// <b>Fail-soft on a directory outage.</b> <see cref="LdapGroupLookupStatus.DirectoryUnavailable"/> (or a
/// lookup that throws) keeps the sign-in groups — still re-mapped, so a DB grant change applies — and the
/// session survives, bounded by <see cref="OtOpcUaCookieOptions.MaxSessionMinutes"/>, an absolute session
/// lifetime the sliding cookie cannot extend. Without a passwordless lookup (user-bind mode, no service
/// account, LDAP disabled, a stub service: <see cref="LdapGroupLookupStatus.NotSupported"/> /
/// <see cref="LdapGroupLookupStatus.ProviderDisabled"/>) the same applies. With
/// <c>Security:Auth:DisableLogin</c> the directory is never queried.
/// </para>
/// <para>
/// <b>Fail-soft on a mapper fault.</b> A ConfigDb blip must not sign every operator out: the existing
@@ -67,18 +79,30 @@ public sealed class AdminSessionRevalidator
/// <param name="options">The cookie / session options.</param>
/// <param name="time">The clock.</param>
/// <param name="logger">The logger.</param>
/// <param name="groupLookup">
/// The passwordless directory group lookup (lmxopcua#975 review); null — or one answering
/// <see cref="LdapGroupLookupStatus.NotSupported"/> — re-maps the groups recorded at sign-in instead.
/// </param>
/// <param name="disableLogin">The dev disable-login options: when set, the directory is never queried.</param>
public AdminSessionRevalidator(
IServiceScopeFactory scopes,
IOptionsMonitor<OtOpcUaCookieOptions> options,
TimeProvider time,
ILogger<AdminSessionRevalidator> logger)
ILogger<AdminSessionRevalidator> logger,
ILdapGroupLookup? groupLookup = null,
IOptions<AuthDisableLoginOptions>? disableLogin = null)
{
_scopes = scopes;
_options = options;
_time = time;
_logger = logger;
_groupLookup = groupLookup;
_disableLogin = disableLogin?.Value.DisableLogin ?? false;
}
private readonly ILdapGroupLookup? _groupLookup;
private readonly bool _disableLogin;
/// <summary>The configured re-validation interval (never below one minute).</summary>
public TimeSpan Interval => TimeSpan.FromMinutes(Math.Max(1, _options.CurrentValue.RevalidateIntervalMinutes));
@@ -111,6 +135,51 @@ public sealed class AdminSessionRevalidator
var groups = principal.FindAll(AdminSessionClaims.Group).Select(c => c.Value).ToArray();
var preResolved = principal.FindAll(AdminSessionClaims.PreResolvedRole).Select(c => c.Value).ToArray();
// Re-read the user's groups from the directory (lmxopcua#975 review). Found ⇒ the fresh groups replace the
// sign-in snapshot; the account is gone / disabled / ambiguous, or in no group ⇒ the session ends; an outage,
// NotSupported (user-bind mode, no service account, a stub service) or a disabled provider ⇒ fail-soft: keep
// the sign-in groups (still re-mapped below), bounded by MaxSessionMinutes. Never under DisableLogin.
string[]? directoryGroups = null;
var username = principal.FindFirst(ZbClaimTypes.Username)?.Value;
if (!_disableLogin && _groupLookup is not null && !string.IsNullOrWhiteSpace(username))
{
LdapGroupLookupResult lookup;
try
{
lookup = await _groupLookup.GetUserGroupsAsync(username, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Directory group re-check for {User} failed; treating it as a directory outage", user);
lookup = LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
}
switch (lookup.Status)
{
case LdapGroupLookupStatus.Found when lookup.Groups.Count == 0:
return Reject(user, "the directory lists the account in no group");
case LdapGroupLookupStatus.Found:
directoryGroups = [.. lookup.Groups];
break;
case LdapGroupLookupStatus.UserNotFound:
return Reject(user, "the account no longer exists in the directory");
case LdapGroupLookupStatus.UserDisabled:
return Reject(user, "the account is disabled in the directory");
case LdapGroupLookupStatus.AmbiguousUser:
return Reject(user, "the directory no longer resolves the account to a single entry");
case LdapGroupLookupStatus.DirectoryUnavailable:
_logger.LogWarning(
"Directory group re-check for {User}: the directory is unavailable; keeping the sign-in groups " +
"(the session's absolute lifetime still caps it)", user);
break;
default:
// NotSupported / ProviderDisabled: no passwordless lookup in this configuration.
break;
}
}
if (directoryGroups is not null) groups = directoryGroups;
IReadOnlyList<string> mapped;
try
{
@@ -139,7 +208,7 @@ public sealed class AdminSessionRevalidator
"Role re-validation for {User}: roles changed [{Before}] -> [{After}]",
user, string.Join(",", current.Order()), string.Join(",", roles.Order()));
return new SessionRevalidation(SessionCheck.Renewed, Rebuild(principal, roles, now), changed);
return new SessionRevalidation(SessionCheck.Renewed, Rebuild(principal, roles, directoryGroups, now), changed);
}
private SessionRevalidation Reject(string user, string reason)
@@ -148,13 +217,20 @@ public sealed class AdminSessionRevalidator
return new SessionRevalidation(SessionCheck.Rejected, Reason: reason);
}
/// <summary>Copies <paramref name="source"/> with the role claims replaced and the validated-at stamp advanced.</summary>
private static ClaimsPrincipal Rebuild(ClaimsPrincipal source, IEnumerable<string> roles, DateTimeOffset now)
/// <summary>
/// Copies <paramref name="source"/> with the role claims replaced, the validated-at stamp advanced and — when
/// the directory answered — the recorded groups replaced, so a later fail-soft re-map uses the latest groups.
/// </summary>
private static ClaimsPrincipal Rebuild(
ClaimsPrincipal source, IEnumerable<string> roles, IReadOnlyList<string>? directoryGroups, DateTimeOffset now)
{
var original = source.Identities.First();
var claims = original.Claims
.Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt)
.Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt
&& (directoryGroups is null || c.Type != AdminSessionClaims.Group))
.ToList();
if (directoryGroups is not null)
foreach (var group in directoryGroups) claims.Add(new Claim(AdminSessionClaims.Group, group));
foreach (var role in roles.Order(StringComparer.OrdinalIgnoreCase))
claims.Add(new Claim(ZbClaimTypes.Role, role));
claims.Add(new Claim(AdminSessionClaims.ValidatedAt, AdminSessionClaims.Format(now)));