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:
@@ -231,7 +231,7 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa
|
||||
provider-less call site. Execution: `ISqlDialect.BeginNamedQueryAsync` (PG/Oracle `SET TRANSACTION READ ONLY`,
|
||||
MySQL read-only session + txn, restored by `EndNamedQueryAsync`) and `SealNamedQueryCommand` (PG rewrites `@name`
|
||||
to positional `$n` — Npgsql then sends unsplit and the server refuses a 2nd statement; a parameterless query gets
|
||||
one unused typed `$1`). SQL Server / MySQL still execute batches: the lexer + a SELECT-only login are the line.
|
||||
one unused typed `$1`). SQL Server / MySQL still execute batches: the guard + a SELECT-only login are the line — and since T-SQL needs no `;` between statements, SqlServer/Odbc/no-provider statements are also PARSED (`Microsoft.SqlServer.TransactSql.ScriptDom`): exactly one batch, one `SELECT`, no `INTO`, no `OPENQUERY`/`OPENROWSET`/`OPENDATASOURCE` (2026-12-02 review).
|
||||
Key-value rows attribute by `SqlKeyMatcher` (exact → typed/padding → collation; #987), and SQL Server table
|
||||
writes count the statement's own `@@ROWCOUNT` via an OUTPUT param (trigger DML no longer counts).
|
||||
- **FOCAS / AbLegacy:** background loops are joined (≤ 5 s) on shutdown.
|
||||
|
||||
@@ -97,6 +97,8 @@
|
||||
<PackageVersion Include="Microsoft.IdentityModel.Tokens" Version="8.11.0" />
|
||||
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
|
||||
<PackageVersion Include="Microsoft.Playwright" Version="1.51.0" />
|
||||
<!-- lmxopcua#974: the Sql named-query guard parses T-SQL (statements need no ';' between them). -->
|
||||
<PackageVersion Include="Microsoft.SqlServer.TransactSql.ScriptDom" Version="180.154.0" />
|
||||
<PackageVersion Include="Moq" Version="4.20.72" />
|
||||
<!--
|
||||
MQTT client for the Mqtt / Sparkplug B driver. MQTTnet v5 is the first line shipping a
|
||||
@@ -235,9 +237,9 @@
|
||||
<PackageVersion Include="ZB.MOM.WW.MxGateway.Client" Version="0.4.0" />
|
||||
<PackageVersion Include="ZB.MOM.WW.MxGateway.Contracts" Version="0.4.0" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Configuration" Version="0.1.0" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Auth.Abstractions" Version="0.4.1" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Auth.Ldap" Version="0.4.1" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Auth.AspNetCore" Version="0.4.1" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Auth.Abstractions" Version="0.5.0" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Auth.Ldap" Version="0.5.0" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Auth.AspNetCore" Version="0.5.0" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Secrets" Version="0.6.2" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Secrets.Abstractions" Version="0.6.6" />
|
||||
<PackageVersion Include="ZB.MOM.WW.Secrets.Ui" Version="1.0.1" />
|
||||
|
||||
@@ -242,8 +242,10 @@ scripted-alarm predicates) runs scripts through the shared `ScriptRunGuard`:
|
||||
`ScriptStackExhaustedException` (Bad, script log) instead of overflowing the
|
||||
stack, which would terminate the whole server. The runtime compile inserts a
|
||||
stack check at the entry of the script and of every lambda, anonymous method
|
||||
and local function (lmxopcua#779); the editor does not show it and does not
|
||||
flag recursion, and bounded recursion still works.
|
||||
and local function (lmxopcua#779), and guards every `catch` / `finally` so a
|
||||
handler that throws on every frame cannot overflow the stack while unwinding
|
||||
(lmxopcua#971 review); the editor does not show it and does not flag
|
||||
recursion, and bounded recursion still works.
|
||||
- **Configuration keys and their ranges.** All four knobs are node-wide (the
|
||||
`Scripting` appsettings section, shared by virtual tags, Calculation tags and
|
||||
scripted alarms) and are clamped when bound, with one startup Warning per
|
||||
|
||||
+6
-4
@@ -36,13 +36,15 @@ 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. 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<int>`).
|
||||
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<int>`).
|
||||
|
||||
**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.
|
||||
|
||||
@@ -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. 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".
|
||||
|
||||
|
||||
|
||||
|
||||
+18
-4
@@ -214,6 +214,18 @@ row:
|
||||
carriage return. T-SQL's `]]` inside `[ … ]` and MySQL's `#` comments are modelled. An **Odbc** driver's
|
||||
backend is unknown, so its statement must lex identically under every dialect (so must a statement checked
|
||||
without a provider). Changing the driver form's **Provider** re-validates the queries.
|
||||
- **On SQL Server the statement is also parsed (2026-12-02 review).** `;` is not a statement boundary in
|
||||
T-SQL — `SELECT 1 COMMIT KILL 55` is three statements to SQL Server and was one `SELECT` to the lexer, so
|
||||
a `COMMIT` ending the rolled-back transaction followed by `DISABLE TRIGGER ALL ON DATABASE`, `KILL`,
|
||||
`SHUTDOWN WITH NOWAIT` or `WRITETEXT` passed the guard. For **SqlServer** — and for **Odbc** and no
|
||||
provider, whose backend may be SQL Server, so the strictest reading applies — the statement is parsed
|
||||
with `Microsoft.SqlServer.TransactSql.ScriptDom` and must be exactly **one batch holding exactly one
|
||||
`SELECT`**, with no `INTO` and no `OPENQUERY` / `OPENROWSET` / `OPENDATASOURCE` (they run text on another
|
||||
server or read a file). CTEs, subqueries, window functions, `UNION`, `OPTION (…)` and `@name` parameters
|
||||
are ordinary `SELECT`s and pass. An Odbc statement's positional `?` markers are read as variables for the
|
||||
parse; anything else SQL Server's grammar does not accept — a PostgreSQL `::` cast, `LIMIT`, a T-SQL
|
||||
reserved word used as a bare alias (`AS top`) — is refused on Odbc, so quote or rename it. The lexical
|
||||
rules remain as a second, independent layer.
|
||||
- **It executes in a read-only transaction where the provider has one** — always rolled back regardless:
|
||||
PostgreSQL and Oracle `SET TRANSACTION READ ONLY`, MySQL a read-only **session** plus `START TRANSACTION
|
||||
READ ONLY` (a smuggled `COMMIT` ends a transaction, not a session; the session is restored afterwards). A
|
||||
@@ -223,8 +235,8 @@ row:
|
||||
positional `$n` parameters (rewritten from your `@name` markers), which makes Npgsql pass the text unsplit
|
||||
as one extended-protocol statement; the server rejects anything after a `;` itself. Oracle (ODP.NET)
|
||||
refuses a second statement anyway. SQL Server and MySQL execute a multi-statement batch — there the
|
||||
per-dialect guard is the line, and MySQL's read-only session is defence in depth that hidden text could
|
||||
undo.
|
||||
guard is the line (on SQL Server its T-SQL parse, above), and MySQL's read-only session is defence in depth
|
||||
that hidden text could undo.
|
||||
- None of this replaces the grant: a non-transactional side effect (an e-mail procedure, a call out to
|
||||
another system, an autonomous transaction) is outside every layer — which is why a read-only driver
|
||||
**must** connect with a `SELECT`-only login (see [Database login](#database-login-required)).
|
||||
@@ -484,7 +496,9 @@ value. Writes never change driver health. Discovery advertises `Operate` only fo
|
||||
two rows per changed row (#987). `NamedQueryBypassLiveTests` proves, per provider, that each smuggled-write
|
||||
string is a working bypass the old way, that the guard refuses it, and that with the guard bypassed the
|
||||
write still does not land (PostgreSQL, MySQL) — plus the MySQL session restore and an Oracle read under
|
||||
`SET TRANSACTION READ ONLY`.
|
||||
`SET TRANSACTION READ ONLY`. `SqlServerNamedQueryBatchLiveTests` does the same for SQL Server's `;`-less
|
||||
batch (`SELECT 1 AS v COMMIT UPDATE …` commits the old way; the guard refuses it for SqlServer and Odbc) and
|
||||
reads a CTE + window-function + subquery + parameter query Good through the driver.
|
||||
|
||||
## Database login (required)
|
||||
|
||||
@@ -494,7 +508,7 @@ The driver's own guards are not a substitute for the database's grants:
|
||||
the tables and views its tags and named queries read, and nothing else. The named-query guard is a
|
||||
per-dialect keyword check plus an always-rolled-back (read-only where the provider has one) transaction;
|
||||
none of that can stop a **non-transactional** side effect — a function that sends mail or calls out,
|
||||
autonomous transactions — and on SQL Server and MySQL a statement that got past the lexer would run as a
|
||||
autonomous transactions — and on SQL Server and MySQL a statement that got past the guard would run as a
|
||||
batch. Only the grant is a boundary.
|
||||
- **A writable driver must connect with a login limited to its write targets** — `SELECT` as above,
|
||||
plus exactly what its modes need on exactly the tables / procedures its writable tags name:
|
||||
|
||||
+4
-3
@@ -1792,12 +1792,13 @@ Admin reads `LdapGroupRoleMapping` rows from the Config DB (`src/Core/ZB.MOM.WW.
|
||||
Group→role resolution used to run once, in `/auth/login`, so a user removed from an admin group (or whose `/role-grants` row was deleted) kept every role while the sliding cookie renewed or a Blazor circuit stayed open. Roles are now re-validated on a timer:
|
||||
|
||||
- **Stamp.** `/auth/login` adds `otopcua:group` (the sign-in LDAP groups), `otopcua:preresolved-role` (roles granted outside the mapper — the DevStub Administrator), `otopcua:auth-time` and `otopcua:validated-at` (`Session/AdminSessionClaims.cs`).
|
||||
- **Cookie.** `CookieAuthenticationEvents.OnValidatePrincipal` → `AdminSessionRevalidator`. Inside `Security:Cookie:RevalidateIntervalMinutes` (default 5) it is a timestamp comparison; past it, the stored groups are re-run through `IGroupRoleMapper<string>` (appsettings `GroupToRole` + DB `LdapGroupRoleMapping`). A changed role set replaces the principal and re-issues the cookie (promotions are picked up too); **no remaining role signs the user out**.
|
||||
- **Cookie.** `CookieAuthenticationEvents.OnValidatePrincipal` → `AdminSessionRevalidator`. Inside `Security:Cookie:RevalidateIntervalMinutes` (default 5) it is a timestamp comparison; past it, the user's **current directory groups** are re-read (see below) and re-run through `IGroupRoleMapper<string>` (appsettings `GroupToRole` + DB `LdapGroupRoleMapping`). A changed role set replaces the principal and re-issues the cookie (promotions are picked up too); **no remaining role signs the user out**.
|
||||
- **Circuits.** `RevalidatingAdminAuthenticationStateProvider` (a `RevalidatingServerAuthenticationStateProvider`, registered by `AddOtOpcUaAuth`) forces the same check each interval. A circuit cannot re-issue the cookie, so a changed or revoked state yields an anonymous principal and every `AuthorizeView`/policy fails closed until the page is reloaded.
|
||||
- **No LDAP traffic.** The re-check reads ConfigDb only. ⚠️ Therefore a change to the user's **directory group membership** is NOT observed (the shared `ZB.MOM.WW.Auth.Ldap` client has no password-less group lookup); that window is bounded by `Security:Cookie:MaxSessionMinutes` (default 480, absolute from sign-in, `0` disables).
|
||||
- **Directory groups are re-read (2026-12-02 review).** Each re-check asks the directory for the user's current groups through `ZB.MOM.WW.Auth` 0.5.0's passwordless `ILdapGroupLookup` (a service-account search by `UserNameAttribute`, no user password; `OtOpcUaLdapAuthService` implements it with the same `Enabled` / `DevStubMode` / transport rules as sign-in), then maps them — so removing a user from a directory group takes effect at the next interval, not at `MaxSessionMinutes`. The refreshed groups replace the session's `otopcua:group` claims. The account **not found, disabled, ambiguous, or in no group** ⇒ the session ends. Cost: one directory search + one ConfigDb read per interval per session. With `Security:Ldap:BindMode=User` (no service account), LDAP disabled, or a non-library LDAP service the lookup answers `NotSupported` and the sign-in groups are re-mapped as before; `Security:Cookie:MaxSessionMinutes` (default 480, absolute from sign-in, `0` disables) bounds that case.
|
||||
- **Fail-soft on a directory outage.** `DirectoryUnavailable` (or a lookup fault) keeps the session on its last known groups — still re-mapped, so a `/role-grants` change applies — with a Warning; the absolute lifetime still caps it.
|
||||
- **Fail-soft.** A role-map fault (ConfigDb down) keeps the session and retries on the next request rather than signing everyone out; the absolute lifetime still caps it.
|
||||
- **Upgrade.** A cookie minted before this change carries no stamps and is refused once, forcing a re-login.
|
||||
- **`Security:Auth:DisableLogin=true`** replaces the cookie handler with the auto-login handler, so none of this runs (and the circuit provider skips validation) — the docker-dev rig is unchanged.
|
||||
- **`Security:Auth:DisableLogin=true`** replaces the cookie handler with the auto-login handler, so none of this runs (and the re-validator never queries the directory) (and the circuit provider skips validation) — the docker-dev rig is unchanged.
|
||||
|
||||
### Headless deploy API (`POST /api/deployments`)
|
||||
|
||||
|
||||
@@ -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() && …)</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<T></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() && (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() && (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";
|
||||
|
||||
+3
@@ -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<string></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<string></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)));
|
||||
|
||||
@@ -77,8 +77,123 @@ public sealed class ForbiddenTypeAnalyzerTests
|
||||
{ "AsQueryable", """return new[] { 1, 2 }.AsQueryable().Count();""" },
|
||||
// ... and the undocumented TypedReference keywords.
|
||||
{ "makeref", """int i = 1; var r = __makeref(i); return 0;""" },
|
||||
|
||||
// Review 2026-12-02 (lmxopcua#971): constructs that passed the allow-list AND the deploy gate and then
|
||||
// terminated the host process (exit 134). An async void body's exception is rethrown on the thread pool,
|
||||
// where nothing catches it; an over-sized stackalloc overflows the stack in one frame, before any guard.
|
||||
{ "async-void-local-function", """async void Boom() { throw new InvalidOperationException(); } Boom(); return 0;""" },
|
||||
{ "static-async-local-function", """static async void Boom() { throw new InvalidOperationException(); } Boom(); return 0;""" },
|
||||
{ "async-lambda", """Action a = async () => throw new InvalidOperationException(); a(); return 0;""" },
|
||||
{ "async-simple-lambda", """Action<int> a = async x => throw new InvalidOperationException(); a(1); return 0;""" },
|
||||
{ "async-anonymous-method", """Action a = async delegate { throw new InvalidOperationException(); }; a(); return 0;""" },
|
||||
{ "stackalloc", """Span<byte> s = stackalloc byte[1_500_000_000]; s[0] = 1; return s.Length;""" },
|
||||
{ "stackalloc-implicit", """Span<int> s = stackalloc[] { 1, 2, 3 }; return s.Length;""" },
|
||||
{ "stackalloc-nested", """return M(stackalloc int[4]); static int M(Span<int> s) => s.Length;""" },
|
||||
// Siblings: [MethodImpl] flags the runtime acts on. InternalCall passes the gate and then fails to LOAD
|
||||
// (TypeLoadException at run time — the gate and the runtime disagree); Synchronized takes a monitor (the
|
||||
// `lock` the analyzer already refuses); a numeric cast must not launder either.
|
||||
{ "MethodImpl-InternalCall", """[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.InternalCall)] static int F() => 1; return F();""" },
|
||||
{ "MethodImpl-Synchronized", """[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.Synchronized)] static int F() => 1; return F();""" },
|
||||
{ "MethodImpl-numeric", """[System.Runtime.CompilerServices.MethodImpl((System.Runtime.CompilerServices.MethodImplOptions)4096)] static int F() => 1; return F();""" },
|
||||
{ "MethodImpl-short-ctor", """[System.Runtime.CompilerServices.MethodImpl((short)32)] static int F() => 1; return F();""" },
|
||||
|
||||
// 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<object>.Default.Compare(a, b);""" },
|
||||
{ "KeyValuePair-chain", """object o = 0; for (var i = 0; i < 1_000_000; i++) o = new System.Collections.Generic.KeyValuePair<object, int>(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>(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<object> l = null!; l = new Lazy<object>(() => 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<T> 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<int> { 2, 1 }; l.Sort((x, y) => x - y); return l[0];""" },
|
||||
{ "Comparer-Create", """var c = System.Collections.Generic.Comparer<int>.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<object> { 1 }.ToArray();""" },
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The legitimate neighbours of the deep-data rows above keep compiling: closed tuples / pairs / anonymous
|
||||
/// types, a tuple literal that is only deconstructed, <c>FormattableString.Invariant</c>, default-comparer
|
||||
/// sorting and key-based ordering, exceptions without an inner exception, and reading a snapshot.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
[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<string, int> { ["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<int> { 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<FakeScriptContext, object?>.Compile(source);
|
||||
_ = await evaluator.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
[Theory]
|
||||
[InlineData("""System.Collections.Generic.IEnumerable<int> F() { for (var i = 0; ; i++) yield return i; } return F().Take(3).Sum();""")]
|
||||
[InlineData("""var i = 0; top: i++; if (i < 10) goto top; return i;""")]
|
||||
[InlineData("""int x = int.MaxValue; try { return checked(x + 1); } catch (OverflowException) { return -1; }""")]
|
||||
[InlineData("""try { throw new InvalidOperationException(); } catch (Exception e) when (e.Message.Length > 0) { return 1; }""")]
|
||||
[InlineData("""System.Collections.Generic.List<int> l = [1, 2, 3]; Span<int> s = [4, 5]; int[] a = [.. l, .. s]; return a.Length;""")]
|
||||
[InlineData("""var x = 1.5; return $"{x:F2} {x,8} {nameof(x)}";""")]
|
||||
[InlineData("""static int F(params ReadOnlySpan<int> xs) => xs.Length; return F(1, 2, 3);""")]
|
||||
[InlineData("""using var e = new System.Collections.Generic.List<int> { 1 }.GetEnumerator(); var (a, b) = (1, 2); return a + b;""")]
|
||||
[InlineData("""[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining | System.Runtime.CompilerServices.MethodImplOptions.NoOptimization)] static int F() => 1; return F();""")]
|
||||
public async Task Compiler_lowered_construct_still_compiles_and_runs(string source)
|
||||
{
|
||||
using var evaluator = ScriptEvaluator<FakeScriptContext, object?>.Compile(source);
|
||||
_ = await evaluator.RunAsync(new FakeScriptContext(), TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Constructs the C# grammar or the wrapper already refuses — no type, record, finalizer, static constructor or
|
||||
/// <c>unsafe</c> / <c>fixed</c> / pointer code can be declared in a script body — so no synthesized member
|
||||
/// of a script-declared type can run outside the walker's view.
|
||||
/// </summary>
|
||||
/// <param name="source">The script body.</param>
|
||||
[Theory]
|
||||
[InlineData("""record R(int A); return new R(1);""")]
|
||||
[InlineData("""class C { ~C() { } static C() { } } return 0;""")]
|
||||
[InlineData("""unsafe { int x = 1; int* p = &x; return *p; }""")]
|
||||
[InlineData("""var a = new int[1]; unsafe { fixed (int* p = a) { return *p; } }""")]
|
||||
[InlineData("""[System.Runtime.CompilerServices.SkipLocalsInit] static int F() => 1; return F();""")]
|
||||
[InlineData("""[ThreadStatic] static int F() => 1; return F();""")]
|
||||
public void Declaration_the_wrapper_cannot_hold_is_refused(string source) => SandboxRefusal.Refuses(source);
|
||||
|
||||
|
||||
/// <summary>Each bypass snippet is refused by the publish gate.</summary>
|
||||
/// <param name="name">Row label.</param>
|
||||
|
||||
+38
-3
@@ -43,6 +43,40 @@ public sealed class ScriptRecursionContainmentTests
|
||||
"System.Action<int> a = null!; System.Func<int, int> h = n => { a(n); return n; }; a = n => h(n + 1); a(0); return 0;",
|
||||
["anonymous-method"] =
|
||||
"System.Func<int, int> f = null!; f = delegate (int n) { return f(n + 1) + 1; }; return f(0);",
|
||||
|
||||
// lmxopcua#971 review: exception handlers on every frame. A catch / finally runs as a funclet ON TOP of the
|
||||
// frames being unwound, so a handler that throws starts a nested dispatch deeper still (~6 KB a level on
|
||||
// macOS). Before the fix each of these terminated the process — the unbounded ones after the guard fired
|
||||
// (its margin cannot hold a nested dispatch per frame), the bounded ones with no guard involvement at all:
|
||||
// 300 frames that each catch-and-rethrow are enough.
|
||||
["catch-rethrow-per-frame"] =
|
||||
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);",
|
||||
["catch-throw-new-per-frame"] =
|
||||
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { throw new System.InvalidOperationException(); } } return Rec(0);",
|
||||
["catch-recurse-again"] =
|
||||
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) { return Rec(d + 1); } } return Rec(0);",
|
||||
["finally-throw-per-frame"] =
|
||||
"int Rec(int d) { try { return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);",
|
||||
["bounded-catch-rethrow"] =
|
||||
"int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.Exception) { throw; } } return Rec(0);",
|
||||
["bounded-catch-wrap"] =
|
||||
"int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } catch (System.InvalidOperationException) { throw new System.ArgumentException(); } catch (System.ArgumentException) { throw new System.InvalidOperationException(); } } return Rec(0);",
|
||||
["bounded-finally-throw"] =
|
||||
"int Rec(int d) { try { if (d >= 300) throw new System.InvalidOperationException(); return Rec(d + 1); } finally { if (d >= 0) throw new System.InvalidOperationException(); } } return Rec(0);",
|
||||
["filter-recurses"] =
|
||||
"int Rec(int d) { try { return Rec(d + 1); } catch (System.Exception) when (Rec(d + 1) > 0) { return 0; } } return Rec(0);",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Scenarios whose surviving fault is not <see cref="ScriptStackExhaustedException"/>: the exception in flight
|
||||
/// when the stack ran low is the script's own, and the run fails with it (null = any exception type).
|
||||
/// </summary>
|
||||
private static readonly Dictionary<string, string?> ExpectedFaultOverrides = new(StringComparer.Ordinal)
|
||||
{
|
||||
["finally-throw-per-frame"] = null,
|
||||
["bounded-catch-rethrow"] = nameof(InvalidOperationException),
|
||||
["bounded-catch-wrap"] = null,
|
||||
["bounded-finally-throw"] = nameof(InvalidOperationException),
|
||||
};
|
||||
|
||||
public static TheoryData<string> ScenarioNames => new(Scenarios.Keys);
|
||||
@@ -58,9 +92,10 @@ public sealed class ScriptRecursionContainmentTests
|
||||
var outcome = File.Exists(resultFile) ? await File.ReadAllTextAsync(resultFile, TestContext.Current.CancellationToken) : "<no result file>";
|
||||
|
||||
// Assert the artifact first: what the child itself recorded about the run.
|
||||
outcome.ShouldBe(
|
||||
$"FAULTED:{nameof(ScriptStackExhaustedException)}",
|
||||
$"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}");
|
||||
var context = $"child exit {exitCode}; stderr head: {Head(stderr)}; stderr tail: {Tail(stderr)}; stdout tail: {Tail(stdout)}";
|
||||
var expected = ExpectedFaultOverrides.TryGetValue(scenario, out var over) ? over : nameof(ScriptStackExhaustedException);
|
||||
if (expected is null) outcome.ShouldStartWith("FAULTED:", Case.Sensitive, context);
|
||||
else outcome.ShouldBe($"FAULTED:{expected}", context);
|
||||
exitCode.ShouldBe(0, $"the process must survive the script; stderr tail: {Tail(stderr)}");
|
||||
}
|
||||
finally
|
||||
|
||||
@@ -38,6 +38,15 @@ public sealed class ScriptStackGuardInjectionTests
|
||||
// Static lambda and a lambda capturing ctx.
|
||||
[InlineData("System.Func<int, int> f = static x => x - 1; return f(9);", 8)]
|
||||
[InlineData("System.Func<string, bool> known = p => ctx.GetTag(p).StatusCode == 0u; return known(\"missing\") ? 1 : 0;", 0)]
|
||||
// lmxopcua#971 review: guarded handlers keep their meaning on a healthy stack — an existing filter still
|
||||
// decides, a declaration-less catch still catches, pattern variables from the filter stay in scope, and a
|
||||
// finally still runs on both the normal and the exceptional path.
|
||||
[InlineData("try { throw new InvalidOperationException(\"a\"); } catch (InvalidOperationException e) when (e.Message == \"b\") { return 1; } catch (Exception) { return 2; }", 2)]
|
||||
[InlineData("try { throw new InvalidOperationException(); } catch { return 4; }", 4)]
|
||||
[InlineData("try { throw new ArgumentException(\"x\"); } catch (Exception e) when (e is ArgumentException a && a.Message == \"x\") { return a.Message.Length + 2; }", 3)]
|
||||
[InlineData("var n = 0; try { n = 1; } finally { n += 10; } return n;", 11)]
|
||||
[InlineData("var n = 0; try { try { throw new Exception(); } finally { n = 5; } } catch { n += 1; } return n;", 6)]
|
||||
[InlineData("int Rec(int d) { try { if (d >= 50) throw new InvalidOperationException(); return Rec(d + 1); } catch (InvalidOperationException) { throw; } } try { return Rec(0); } catch (InvalidOperationException) { return 50; }", 50)]
|
||||
public void Rewritten_lambdas_and_local_functions_keep_their_meaning(string source, int expected) =>
|
||||
Run(source).ShouldBe(expected);
|
||||
|
||||
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
using System.Globalization;
|
||||
using System.Text.Json.Nodes;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#974 (security review 2026-12-02), against the real SQL Server: T-SQL needs no <c>;</c> between
|
||||
/// statements, so <c>SELECT 1 AS v COMMIT UPDATE …</c> is three statements to the server and was one
|
||||
/// <c>SELECT</c> to the lexical guard. SQL Server has no execution-layer seal (it runs batches, and the driver's
|
||||
/// transaction is merely rolled back), so the guard's T-SQL parse is the line in front of the
|
||||
/// <c>SELECT</c>-only login.
|
||||
/// <list type="number">
|
||||
/// <item><b>Positive control</b>: run the old way (an ordinary transaction, rolled back afterwards) the
|
||||
/// smuggled <c>COMMIT</c> ends the transaction and the UPDATE commits. The row is restored.</item>
|
||||
/// <item>The guard refuses it, for SqlServer and Odbc alike.</item>
|
||||
/// <item>A real read with a CTE, a window function, subqueries and a parameter is accepted by the guard and
|
||||
/// reads Good through the driver.</item>
|
||||
/// </list>
|
||||
/// </summary>
|
||||
[Collection(SqlPollServerCollection.Name)]
|
||||
public sealed class SqlServerNamedQueryBatchLiveTests(SqlPollServerFixture fixture)
|
||||
{
|
||||
private static readonly string Target = SqlPollServerFixture.Qualified("write_targets");
|
||||
|
||||
private static string Smuggled(int value)
|
||||
=> string.Create(CultureInfo.InvariantCulture,
|
||||
$"SELECT 1 AS v COMMIT UPDATE {Target} SET sp_value = {value} WHERE tag_name = 'Present'");
|
||||
|
||||
[Fact]
|
||||
public async Task SemicolonLessBatch_isAWorkingBypassOnThisServer_theOldWay()
|
||||
{
|
||||
SkipUnlessLive();
|
||||
var original = await ReadTargetAsync();
|
||||
var smuggled = Random.Shared.Next(1000, 900_000);
|
||||
try
|
||||
{
|
||||
await using var connection = await OpenAsync();
|
||||
await using var transaction = (SqlTransaction)await connection.BeginTransactionAsync(TestContext.Current.CancellationToken);
|
||||
await using (var command = new SqlCommand(Smuggled(smuggled), connection, transaction))
|
||||
{
|
||||
await using var reader = await command.ExecuteReaderAsync(TestContext.Current.CancellationToken);
|
||||
do { while (await reader.ReadAsync(TestContext.Current.CancellationToken)) { } }
|
||||
while (await reader.NextResultAsync(TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
try { await transaction.RollbackAsync(TestContext.Current.CancellationToken); }
|
||||
catch (InvalidOperationException) { /* the smuggled COMMIT already ended it — the point */ }
|
||||
|
||||
(await ReadTargetAsync()).ShouldBe(smuggled);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await ScalarAsync(string.Create(CultureInfo.InvariantCulture,
|
||||
$"UPDATE {Target} SET sp_value = {original} WHERE tag_name = 'Present'"));
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SemicolonLessBatch_isRefusedByTheGuard_forSqlServerAndOdbc()
|
||||
{
|
||||
SqlReadOnlyStatement.Check(Smuggled(1), SqlProvider.SqlServer, out _).ShouldNotBeNull();
|
||||
SqlReadOnlyStatement.Check(Smuggled(1), SqlProvider.Odbc, out _).ShouldNotBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task LegitimateRead_withCteWindowSubqueryAndParameter_passesTheGuard_andReadsGood()
|
||||
{
|
||||
SkipUnlessLive();
|
||||
var kv = SqlPollServerFixture.Qualified(SqlPollServerFixture.KeyValueTable);
|
||||
var sql =
|
||||
$"WITH ranked AS (SELECT tag_name, num_value, ROW_NUMBER() OVER (PARTITION BY tag_name ORDER BY sample_ts DESC) AS rn " +
|
||||
$"FROM {kv} WHERE num_value IS NOT NULL) " +
|
||||
$"SELECT r.num_value AS v, (SELECT COUNT(*) FROM {kv}) AS n FROM ranked AS r " +
|
||||
$"WHERE r.rn = 1 AND r.tag_name = @key AND r.num_value >= (SELECT MIN(num_value) FROM {kv})";
|
||||
SqlReadOnlyStatement.Check(sql, SqlProvider.SqlServer, out var normalised).ShouldBeNull();
|
||||
|
||||
var driver = new SqlDriver(
|
||||
new SqlDriverOptions
|
||||
{
|
||||
RawTags =
|
||||
[
|
||||
new RawTagEntry("Q/V", new JsonObject { ["driver"] = "Sql", ["model"] = "Query", ["query"] = "q", ["column"] = "v" }.ToJsonString(), WriteIdempotent: false),
|
||||
],
|
||||
Queries = new Dictionary<string, SqlNamedQuery>(StringComparer.Ordinal)
|
||||
{
|
||||
["q"] = new("q", normalised, ["key"], [SqlPollServerFixture.PresentKey], SqlNamedQueryRules.DefaultMaxRows),
|
||||
},
|
||||
CommandTimeout = TimeSpan.FromSeconds(30),
|
||||
OperationTimeout = TimeSpan.FromSeconds(45),
|
||||
},
|
||||
driverInstanceId: "sql-batch-guard-live",
|
||||
dialect: new SqlServerDialect(),
|
||||
connectionString: fixture.ConnectionString);
|
||||
await using (driver)
|
||||
{
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
var snapshot = (await driver.ReadAsync(["Q/V"], TestContext.Current.CancellationToken))[0];
|
||||
snapshot.StatusCode.ShouldBe(SqlStatusCodes.Good);
|
||||
Convert.ToDouble(snapshot.Value, CultureInfo.InvariantCulture).ShouldBe(SqlPollServerFixture.PresentValue);
|
||||
}
|
||||
}
|
||||
|
||||
private void SkipUnlessLive()
|
||||
{
|
||||
if (fixture.SkipReason is { } reason) Assert.Skip(reason);
|
||||
}
|
||||
|
||||
private async Task<double> ReadTargetAsync()
|
||||
=> Convert.ToDouble(await ScalarAsync($"SELECT sp_value FROM {Target} WHERE tag_name = 'Present'"), CultureInfo.InvariantCulture);
|
||||
|
||||
private async Task<object?> ScalarAsync(string sql)
|
||||
{
|
||||
await using var connection = await OpenAsync();
|
||||
await using var command = new SqlCommand(sql, connection);
|
||||
return await command.ExecuteScalarAsync(TestContext.Current.CancellationToken);
|
||||
}
|
||||
|
||||
private async Task<SqlConnection> OpenAsync()
|
||||
{
|
||||
var connection = new SqlConnection(fixture.ConnectionString);
|
||||
await connection.OpenAsync(TestContext.Current.CancellationToken);
|
||||
return connection;
|
||||
}
|
||||
}
|
||||
@@ -217,10 +217,10 @@ public sealed class SqlNamedQueryTests
|
||||
using var fixture = new SqlitePollFixture();
|
||||
await using var driver = await StartAsync(fixture,
|
||||
"""
|
||||
{"one":{"sql":"SELECT MAX(num_value) AS top FROM TagValues"},
|
||||
{"one":{"sql":"SELECT MAX(num_value) AS peak FROM TagValues"},
|
||||
"many":{"sql":"SELECT num_value FROM TagValues"}}
|
||||
""",
|
||||
Tag("Q/One", """{"model":"Query","query":"one","column":"top","type":"Float64"}"""),
|
||||
Tag("Q/One", """{"model":"Query","query":"one","column":"peak","type":"Float64"}"""),
|
||||
Tag("Q/Many", """{"model":"Query","query":"many","column":"num_value","type":"Float64"}"""));
|
||||
|
||||
var snapshots = await driver.ReadAsync(["Q/One", "Q/Many"], CancellationToken.None);
|
||||
@@ -238,7 +238,7 @@ public sealed class SqlNamedQueryTests
|
||||
{
|
||||
using var fixture = new SqlitePollFixture();
|
||||
await using var driver = await StartAsync(fixture,
|
||||
"""{"one":{"sql":"SELECT MAX(num_value) AS top FROM TagValues"}}""",
|
||||
"""{"one":{"sql":"SELECT MAX(num_value) AS peak FROM TagValues"}}""",
|
||||
Tag("Q/Wrong", """{"model":"Query","query":"one","column":"nope"}"""));
|
||||
|
||||
(await driver.ReadAsync(["Q/Wrong"], CancellationToken.None))[0].StatusCode
|
||||
@@ -287,8 +287,8 @@ public sealed class SqlNamedQueryTests
|
||||
fixture.Execute("CREATE TABLE SideEffects (n INTEGER)");
|
||||
var factory = new SideEffectFactory();
|
||||
await using var driver = await StartAsync(fixture, factory,
|
||||
"""{"one":{"sql":"SELECT MAX(num_value) AS top FROM TagValues"}}""",
|
||||
Tag("Q/One", """{"model":"Query","query":"one","column":"top"}"""));
|
||||
"""{"one":{"sql":"SELECT MAX(num_value) AS peak FROM TagValues"}}""",
|
||||
Tag("Q/One", """{"model":"Query","query":"one","column":"peak"}"""));
|
||||
|
||||
(await driver.ReadAsync(["Q/One"], CancellationToken.None))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
|
||||
(await driver.ReadAsync(["Q/One"], CancellationToken.None))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
|
||||
@@ -340,12 +340,12 @@ public sealed class SqlNamedQueryTests
|
||||
{
|
||||
using var fixture = new SqlitePollFixture();
|
||||
var dialect = new NamedQueryHookDialect();
|
||||
var dto = Dto("""{"one":{"sql":"SELECT MAX(num_value) AS top FROM TagValues WHERE num_value > @min","params":{"min":0}}}""");
|
||||
var dto = Dto("""{"one":{"sql":"SELECT MAX(num_value) AS peak FROM TagValues WHERE num_value > @min","params":{"min":0}}}""");
|
||||
var options = new SqlDriverOptions
|
||||
{
|
||||
RawTags =
|
||||
[
|
||||
Tag("Q/One", """{"model":"Query","query":"one","column":"top"}"""),
|
||||
Tag("Q/One", """{"model":"Query","query":"one","column":"peak"}"""),
|
||||
Tag("Kv", $$"""{"model":"KeyValue","table":"TagValues","keyColumn":"tag_name","keyValue":"{{SqlitePollFixture.PresentKey}}","valueColumn":"num_value"}"""),
|
||||
],
|
||||
OperationTimeout = TimeSpan.FromSeconds(15),
|
||||
@@ -362,7 +362,7 @@ public sealed class SqlNamedQueryTests
|
||||
|
||||
(await driver.ReadAsync(["Q/One"], CancellationToken.None))[0].StatusCode.ShouldBe(SqlStatusCodes.Good);
|
||||
dialect.Begun.ShouldBe(1);
|
||||
dialect.Sealed.ShouldHaveSingleItem().ShouldBe(("SELECT MAX(num_value) AS top FROM TagValues WHERE num_value > @min", 1));
|
||||
dialect.Sealed.ShouldHaveSingleItem().ShouldBe(("SELECT MAX(num_value) AS peak FROM TagValues WHERE num_value > @min", 1));
|
||||
dialect.Ended.ShouldBe(1);
|
||||
}
|
||||
|
||||
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Sql.Contracts;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Sql.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#974 (security review 2026-12-02): T-SQL does not need <c>;</c> between statements. The lexical guard's
|
||||
/// only statement boundary was <c>;</c>, so <c>SELECT 1 COMMIT KILL 55</c> was "one SELECT" to it and three
|
||||
/// statements to SQL Server — the <c>COMMIT</c> ending the driver's always-rolled-back transaction, then anything.
|
||||
/// For SQL Server (and for ODBC / no provider, whose backend is unknown and so must pass the strictest reading) the
|
||||
/// statement is now parsed 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 pass-through rowset.
|
||||
/// </summary>
|
||||
public sealed class SqlReadOnlyStatementTransactSqlTests
|
||||
{
|
||||
/// <summary>Accepted by the lexical guard for SqlServer AND Odbc before the fix.</summary>
|
||||
public static TheoryData<string> SemicolonLessBatches => new()
|
||||
{
|
||||
"SELECT 1 COMMIT DISABLE TRIGGER ALL ON DATABASE",
|
||||
"SELECT 1 COMMIT KILL 55",
|
||||
"SELECT 1 COMMIT SHUTDOWN WITH NOWAIT",
|
||||
"SELECT 1 COMMIT DECLARE @p varbinary(16) SELECT @p = TEXTPTR(Col) FROM dbo.T WRITETEXT dbo.T.Col @p 'pwned'",
|
||||
"SELECT 1 COMMIT BEGIN TRAN SELECT 2",
|
||||
"SELECT 1 WAITFOR DELAY '00:10:00'",
|
||||
"SELECT 1 SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED",
|
||||
"SELECT a FROM t\nGO\nSELECT 2",
|
||||
"WITH c AS (SELECT 1 AS a) SELECT a FROM c COMMIT RECONFIGURE",
|
||||
"SELECT 1 COMMIT DBCC SHRINKDATABASE (0)",
|
||||
"SELECT 1 COMMIT BACKUP LOG x TO DISK = 'nul'",
|
||||
};
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(SemicolonLessBatches))]
|
||||
public void A_semicolon_less_batch_is_refused_for_SqlServer(string sql)
|
||||
=> SqlReadOnlyStatement.Check(sql, SqlProvider.SqlServer, out _).ShouldNotBeNull();
|
||||
|
||||
[Theory]
|
||||
[MemberData(nameof(SemicolonLessBatches))]
|
||||
public void A_semicolon_less_batch_is_refused_for_Odbc_and_without_a_provider(string sql)
|
||||
{
|
||||
SqlReadOnlyStatement.Check(sql, SqlProvider.Odbc, out _).ShouldNotBeNull();
|
||||
SqlReadOnlyStatement.Check(sql, out _).ShouldNotBeNull();
|
||||
}
|
||||
|
||||
/// <summary>One statement, but not a plain read: pass-through rowsets run text on another server.</summary>
|
||||
[Theory]
|
||||
[InlineData("SELECT * FROM OPENQUERY(lnk, 'SELECT 1')")]
|
||||
[InlineData("SELECT * FROM OPENROWSET('SQLNCLI', 'Server=x;Trusted_Connection=yes;', 'SELECT 1')")]
|
||||
[InlineData("SELECT * FROM OPENDATASOURCE('SQLNCLI', 'Data Source=x;Integrated Security=SSPI').db.dbo.t")]
|
||||
[InlineData("SELECT * FROM OPENROWSET(BULK 'c:\\x.txt', SINGLE_CLOB) AS b")]
|
||||
public void A_pass_through_rowset_is_refused(string sql)
|
||||
=> SqlReadOnlyStatement.Check(sql, SqlProvider.SqlServer, out _).ShouldNotBeNull();
|
||||
|
||||
[Fact]
|
||||
public void The_refusal_names_the_statement_count()
|
||||
=> SqlReadOnlyStatement.Check("SELECT 1 COMMIT KILL 55", SqlProvider.SqlServer, out _)
|
||||
.ShouldNotBeNull().ShouldContain("statement");
|
||||
|
||||
/// <summary>Positive controls: ordinary T-SQL reads — CTEs, subqueries, window functions, parameters — still pass.</summary>
|
||||
[Theory]
|
||||
[InlineData("SELECT a FROM t WHERE x = @x")]
|
||||
[InlineData("SELECT a FROM t WHERE x = @x;")]
|
||||
[InlineData("WITH latest AS (SELECT tag, val, ROW_NUMBER() OVER (PARTITION BY tag ORDER BY ts DESC) AS rn FROM dbo.hist WHERE ts > @since) SELECT tag, val FROM latest WHERE rn = 1")]
|
||||
[InlineData("SELECT TOP (@n) a, (SELECT MAX(b) FROM u WHERE u.k = t.k) AS m, SUM(c) OVER () AS total FROM t WHERE k IN (SELECT k FROM v WHERE w = @w) ORDER BY a")]
|
||||
[InlineData("SELECT [it's], [a]]b], [update], \"quoted\" FROM t -- trailing comment")]
|
||||
[InlineData("SELECT a FROM #staging /* note */ WHERE b LIKE 'x%' OPTION (RECOMPILE)")]
|
||||
[InlineData("SELECT CAST(a AS varchar(10)) + N'x' AS s, CASE WHEN b > 0 THEN 1 ELSE 0 END AS f FROM t FOR XML PATH('r')")]
|
||||
[InlineData("SELECT a FROM t UNION ALL SELECT b FROM u EXCEPT SELECT c FROM v")]
|
||||
public void An_ordinary_T_SQL_read_passes(string sql)
|
||||
=> SqlReadOnlyStatement.Check(sql, SqlProvider.SqlServer, out _).ShouldBeNull();
|
||||
|
||||
[Theory]
|
||||
[InlineData("SELECT a FROM t WHERE x = ? AND y = ?")]
|
||||
[InlineData("SELECT a, '?' AS q FROM t WHERE x = ? ORDER BY a")]
|
||||
public void An_ODBC_read_with_positional_markers_passes(string sql)
|
||||
{
|
||||
SqlReadOnlyStatement.Check(sql, SqlProvider.Odbc, out var normalised).ShouldBeNull();
|
||||
normalised.ShouldBe(sql);
|
||||
}
|
||||
}
|
||||
@@ -47,9 +47,26 @@ public sealed class FleetDiagnosticsSsrfTests : BunitContext
|
||||
[InlineData("host-a:4053 ")]
|
||||
[InlineData("[::1]:4053")]
|
||||
[InlineData("host-a:4053?x=1")]
|
||||
// Review 2026-12-02: '$' also matches before a trailing '\n' (and int.Parse then ignores it), so a newline
|
||||
// rode into the akka.tcp address; '\d' matches non-ASCII digits, which int.Parse rejects with a FormatException
|
||||
// that took the page down instead of answering "not well-formed".
|
||||
[InlineData("host-a:4053\n")]
|
||||
[InlineData("host-a:4053\r\n")]
|
||||
[InlineData("host-a:\u0664\u0660\u0665\u0663")] // Arabic-Indic digits
|
||||
[InlineData("host-a:4053")] // full-width digits
|
||||
[InlineData("host-a:405\u0663")]
|
||||
public void Anything_that_could_retarget_the_actor_path_is_not_well_formed(string value) =>
|
||||
FleetDiagnosticsTargets.IsWellFormed(value).ShouldBeFalse();
|
||||
|
||||
/// <summary>A non-ASCII-digit request is refused by Resolve, not thrown (the page must render "not allowed").</summary>
|
||||
[Fact]
|
||||
public void Resolve_refuses_unicode_digits_and_a_trailing_newline_without_throwing()
|
||||
{
|
||||
FleetDiagnosticsTargets.Resolve("host-a:\u0664\u0660\u0665\u0663", ["host-a:4053"], []).ShouldBeNull();
|
||||
FleetDiagnosticsTargets.Resolve("host-a:4053", ["host-a:4053\n"], []).ShouldBeNull();
|
||||
FleetDiagnosticsTargets.Resolve("host-a:4053", ["host-a:4053"], []).ShouldBe("host-a:4053"); // positive control
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Resolve_accepts_a_member_and_returns_its_canonical_casing_and_rejects_a_stranger()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Ldap;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using AppLdapOptions = ZB.MOM.WW.OtOpcUa.Security.Ldap.LdapOptions;
|
||||
using AppLdapAuthService = ZB.MOM.WW.OtOpcUa.Security.Ldap.OtOpcUaLdapAuthService;
|
||||
using LibILdapAuthService = ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapAuthService;
|
||||
using LibLdapAuthResult = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapAuthResult;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#975 (review 2026-12-02): the app's LDAP wrapper exposes the shared library's 0.5.0 passwordless
|
||||
/// <see cref="ILdapGroupLookup"/> so a live AdminUI session can re-read its directory groups. The wrapper's own
|
||||
/// concerns apply to the lookup exactly as to sign-in: <c>Enabled</c> is the master switch, <c>DevStubMode</c>
|
||||
/// answers the stub's group set without touching the network, and a plaintext transport without
|
||||
/// <c>AllowInsecure</c> is refused.
|
||||
/// </summary>
|
||||
public sealed class OtOpcUaLdapGroupLookupTests
|
||||
{
|
||||
private static ILdapGroupLookup Build(AppLdapOptions options, LibILdapAuthService inner) =>
|
||||
new AppLdapAuthService(options, inner, NullLogger<AppLdapAuthService>.Instance);
|
||||
|
||||
[Fact]
|
||||
public async Task Real_path_delegates_to_the_library_lookup()
|
||||
{
|
||||
var inner = new LookupLib(LdapGroupLookupResult.Found("alice", "Alice", ["ReadOnly"]));
|
||||
var sut = Build(new AppLdapOptions { Enabled = true, Transport = LdapTransport.Ldaps }, inner);
|
||||
|
||||
var result = await sut.GetUserGroupsAsync("alice", CancellationToken.None);
|
||||
|
||||
result.Status.ShouldBe(LdapGroupLookupStatus.Found);
|
||||
result.Groups.ShouldBe(["ReadOnly"]);
|
||||
inner.LookedUp.ShouldBe("alice");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Disabled_provider_answers_ProviderDisabled_without_the_library()
|
||||
{
|
||||
var inner = new LookupLib(LdapGroupLookupResult.Found("alice", "Alice", ["ReadOnly"]));
|
||||
var sut = Build(new AppLdapOptions { Enabled = false, DevStubMode = true }, inner);
|
||||
|
||||
(await sut.GetUserGroupsAsync("alice", CancellationToken.None)).Status.ShouldBe(LdapGroupLookupStatus.ProviderDisabled);
|
||||
inner.LookedUp.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DevStub_answers_the_stub_group_without_the_library()
|
||||
{
|
||||
var inner = new LookupLib(LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound));
|
||||
var sut = Build(new AppLdapOptions { Enabled = true, DevStubMode = true }, inner);
|
||||
|
||||
var result = await sut.GetUserGroupsAsync("anyone", CancellationToken.None);
|
||||
|
||||
result.Status.ShouldBe(LdapGroupLookupStatus.Found);
|
||||
result.Groups.ShouldBe(["dev"]);
|
||||
inner.LookedUp.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Insecure_transport_without_opt_in_is_NotSupported()
|
||||
{
|
||||
var inner = new LookupLib(LdapGroupLookupResult.Found("alice", "Alice", ["ReadOnly"]));
|
||||
var sut = Build(new AppLdapOptions { Enabled = true, Transport = LdapTransport.None, AllowInsecure = false }, inner);
|
||||
|
||||
(await sut.GetUserGroupsAsync("alice", CancellationToken.None)).Status.ShouldBe(LdapGroupLookupStatus.NotSupported);
|
||||
inner.LookedUp.ShouldBeNull();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_library_without_lookup_answers_NotSupported()
|
||||
{
|
||||
var sut = Build(new AppLdapOptions { Enabled = true, Transport = LdapTransport.Ldaps }, new AuthOnlyLib());
|
||||
|
||||
(await sut.GetUserGroupsAsync("alice", CancellationToken.None)).Status.ShouldBe(LdapGroupLookupStatus.NotSupported);
|
||||
}
|
||||
|
||||
/// <summary>AddOtOpcUaAuth registers the lookup as the app's LDAP service — or NotSupported for a stub service.</summary>
|
||||
[Fact]
|
||||
public async Task AddOtOpcUaAuth_registers_the_group_lookup()
|
||||
{
|
||||
var services = new ServiceCollection();
|
||||
services.AddLogging();
|
||||
services.AddDbContext<OtOpcUaConfigDbContext>(o => o.UseInMemoryDatabase($"lookup-{Guid.NewGuid():N}"));
|
||||
services.AddOtOpcUaAuth(new ConfigurationBuilder().Build());
|
||||
using (var provider = services.BuildServiceProvider())
|
||||
provider.GetRequiredService<ILdapGroupLookup>().ShouldBeOfType<AppLdapAuthService>();
|
||||
|
||||
services.AddSingleton<ZB.MOM.WW.OtOpcUa.Security.Ldap.ILdapAuthService, AuthOnlyAppService>();
|
||||
using (var provider = services.BuildServiceProvider())
|
||||
{
|
||||
var lookup = provider.GetRequiredService<ILdapGroupLookup>();
|
||||
(await lookup.GetUserGroupsAsync("x", CancellationToken.None)).Status.ShouldBe(LdapGroupLookupStatus.NotSupported);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class LookupLib(LdapGroupLookupResult result) : LibILdapAuthService, ILdapGroupLookup
|
||||
{
|
||||
public string? LookedUp { get; private set; }
|
||||
|
||||
public Task<LibLdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
|
||||
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
|
||||
{
|
||||
LookedUp = username;
|
||||
return Task.FromResult(result);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class AuthOnlyLib : LibILdapAuthService
|
||||
{
|
||||
public Task<LibLdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct) =>
|
||||
throw new NotSupportedException();
|
||||
}
|
||||
|
||||
private sealed class AuthOnlyAppService : ZB.MOM.WW.OtOpcUa.Security.Ldap.ILdapAuthService
|
||||
{
|
||||
public Task<ZB.MOM.WW.OtOpcUa.Security.Ldap.LdapAuthResult> AuthenticateAsync(
|
||||
string username, string password, CancellationToken ct = default) => throw new NotSupportedException();
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,9 @@ using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ILdapGroupLookup = ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup;
|
||||
using LdapGroupLookupResult = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapGroupLookupResult;
|
||||
using LdapGroupLookupStatus = ZB.MOM.WW.Auth.Abstractions.Ldap.LdapGroupLookupStatus;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
@@ -40,6 +43,7 @@ public sealed class SessionRevalidationTests : IAsyncLifetime
|
||||
|
||||
private readonly TestClock _clock = new();
|
||||
private readonly StubMappings _mappings = new();
|
||||
private readonly StubDirectory _directory = new();
|
||||
private IHost _host = null!;
|
||||
private TestServer _server = null!;
|
||||
|
||||
@@ -68,6 +72,7 @@ public sealed class SessionRevalidationTests : IAsyncLifetime
|
||||
services.AddOtOpcUaAuth(configuration);
|
||||
services.AddSingleton<ILdapAuthService, StubLdap>();
|
||||
services.AddSingleton<ILdapGroupRoleMappingService>(_mappings);
|
||||
services.AddSingleton<ILdapGroupLookup>(_directory);
|
||||
});
|
||||
web.Configure(app =>
|
||||
{
|
||||
@@ -259,6 +264,128 @@ public sealed class SessionRevalidationTests : IAsyncLifetime
|
||||
(await roles.Content.ReadFromJsonAsync<string[]>(Ct)).ShouldBe(["Administrator"]);
|
||||
}
|
||||
|
||||
// ---- directory re-query (lmxopcua#975 review 2026-12-02) --------------------------------
|
||||
// The re-check used to re-map the groups frozen into the cookie at sign-in, so removing a user from a directory
|
||||
// group changed nothing until the absolute lifetime ended the session. With the 0.5.0 passwordless lookup the
|
||||
// groups are re-read from the directory at every interval.
|
||||
|
||||
/// <summary>The reported defect: removed from the directory group ⇒ the elevated policy is gone after the window.</summary>
|
||||
[Fact]
|
||||
public async Task Directory_group_removal_is_applied_after_the_window()
|
||||
{
|
||||
GrantDesigner();
|
||||
_directory.Answer("editor", ["ReadOnly", "Editors"]);
|
||||
var login = await LoginAsync("editor");
|
||||
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
_directory.Answer("editor", ["ReadOnly"]); // removed from Editors in the directory; the DB grant is untouched
|
||||
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes - 1));
|
||||
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK); // inside the window
|
||||
|
||||
_clock.Advance(TimeSpan.FromMinutes(2));
|
||||
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
||||
var roles = await GetAsync("/api/roles", login);
|
||||
(await roles.Content.ReadFromJsonAsync<string[]>(Ct)).ShouldBe(["Viewer"]);
|
||||
_directory.Lookups.ShouldContain("editor");
|
||||
}
|
||||
|
||||
/// <summary>Positive control: the directory still lists the same groups ⇒ the session keeps its roles.</summary>
|
||||
[Fact]
|
||||
public async Task Unchanged_directory_membership_keeps_the_roles()
|
||||
{
|
||||
GrantDesigner();
|
||||
_directory.Answer("editor", ["ReadOnly", "Editors"]);
|
||||
var login = await LoginAsync("editor");
|
||||
|
||||
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
|
||||
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
_directory.Lookups.ShouldContain("editor");
|
||||
}
|
||||
|
||||
/// <summary>A promotion in the directory is picked up too.</summary>
|
||||
[Fact]
|
||||
public async Task Directory_group_addition_is_applied_after_the_window()
|
||||
{
|
||||
GrantDesigner();
|
||||
_directory.Answer("editor", ["ReadOnly"]);
|
||||
var login = await LoginAsync("editor"); // the sign-in result still says ReadOnly + Editors; directory now differs
|
||||
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
|
||||
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
||||
|
||||
_directory.Answer("editor", ["ReadOnly", "Editors"]);
|
||||
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
|
||||
(await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
}
|
||||
|
||||
/// <summary>The account is gone, disabled, ambiguous, or in no group at all ⇒ the session ends.</summary>
|
||||
[Theory]
|
||||
[InlineData(LdapGroupLookupStatus.UserNotFound)]
|
||||
[InlineData(LdapGroupLookupStatus.UserDisabled)]
|
||||
[InlineData(LdapGroupLookupStatus.AmbiguousUser)]
|
||||
[InlineData(LdapGroupLookupStatus.Found)] // with zero groups
|
||||
public async Task Directory_says_the_account_is_gone_or_groupless_and_the_session_ends(LdapGroupLookupStatus status)
|
||||
{
|
||||
GrantDesigner();
|
||||
_directory.Answer("editor", ["ReadOnly", "Editors"]);
|
||||
var login = await LoginAsync("editor");
|
||||
(await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
if (status == LdapGroupLookupStatus.Found) _directory.Answer("editor", []);
|
||||
else _directory.Answer("editor", status);
|
||||
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
|
||||
|
||||
(await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A directory outage is not a sign-out: the session keeps its sign-in groups (still re-mapped, so a DB grant
|
||||
/// change applies), and the absolute lifetime still caps it.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Directory_outage_keeps_the_session_bounded_by_the_absolute_lifetime()
|
||||
{
|
||||
GrantDesigner();
|
||||
_directory.Answer("editor", ["ReadOnly", "Editors"]);
|
||||
var login = await LoginAsync("editor");
|
||||
|
||||
_directory.Answer("editor", LdapGroupLookupStatus.DirectoryUnavailable);
|
||||
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
|
||||
var kept = await GetAsync("/api/editor", login);
|
||||
kept.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
_directory.Lookups.ShouldContain("editor"); // the directory WAS asked
|
||||
|
||||
_mappings.Rows.Clear(); // the stored groups are still re-mapped during the outage
|
||||
var cookies = kept.Headers.Contains("Set-Cookie") ? kept : login;
|
||||
_clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1));
|
||||
var demoted = await GetAsync("/api/editor", cookies);
|
||||
demoted.StatusCode.ShouldBe(HttpStatusCode.Forbidden);
|
||||
if (demoted.Headers.Contains("Set-Cookie")) cookies = demoted;
|
||||
|
||||
_clock.Advance(TimeSpan.FromMinutes(MaxSessionMinutes));
|
||||
(await GetAsync("/api/read", cookies)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
}
|
||||
|
||||
/// <summary>Login disabled (dev rig): the re-validator never queries the directory. Positive control: it does otherwise.</summary>
|
||||
[Theory]
|
||||
[InlineData(true, 0)]
|
||||
[InlineData(false, 1)]
|
||||
public async Task Directory_is_not_queried_when_login_is_disabled(bool disableLogin, int expectedLookups)
|
||||
{
|
||||
_directory.Answer("u", ["ReadOnly"]);
|
||||
var revalidator = new AdminSessionRevalidator(
|
||||
_host.Services.GetRequiredService<IServiceScopeFactory>(),
|
||||
_host.Services.GetRequiredService<IOptionsMonitor<OtOpcUaCookieOptions>>(),
|
||||
_clock,
|
||||
NullLogger<AdminSessionRevalidator>.Instance,
|
||||
_directory,
|
||||
Options.Create(new AuthDisableLoginOptions { DisableLogin = disableLogin }));
|
||||
|
||||
var result = await revalidator.RevalidateAsync(SignedInPrincipal(), force: true, Ct);
|
||||
|
||||
result.Outcome.ShouldBe(SessionCheck.Renewed);
|
||||
_directory.Lookups.Count.ShouldBe(expectedLookups);
|
||||
}
|
||||
|
||||
// ---- circuit provider ----------------------------------------------------------------
|
||||
|
||||
private sealed class Probe(
|
||||
@@ -426,6 +553,27 @@ public sealed class SessionRevalidationTests : IAsyncLifetime
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The 0.5.0 passwordless lookup; a user with no answer set is NotSupported (the pre-0.5.0 behaviour).</summary>
|
||||
private sealed class StubDirectory : ILdapGroupLookup
|
||||
{
|
||||
private readonly Dictionary<string, LdapGroupLookupResult> _answers = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public List<string> Lookups { get; } = [];
|
||||
|
||||
public void Answer(string user, IReadOnlyList<string> groups) =>
|
||||
_answers[user] = LdapGroupLookupResult.Found(user, user, groups);
|
||||
|
||||
public void Answer(string user, LdapGroupLookupStatus status) => _answers[user] = LdapGroupLookupResult.Of(status);
|
||||
|
||||
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
|
||||
{
|
||||
Lookups.Add(username);
|
||||
return Task.FromResult(_answers.TryGetValue(username, out var answer)
|
||||
? answer
|
||||
: LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class StubMappings : ILdapGroupRoleMappingService
|
||||
{
|
||||
public List<LdapGroupRoleMapping> Rows { get; } = [];
|
||||
|
||||
Reference in New Issue
Block a user