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

This commit is contained in:
Joseph Doherty
2026-12-03 12:27:35 -05:00
25 changed files with 1299 additions and 71 deletions
@@ -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>
@@ -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);
@@ -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);
}
@@ -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; } = [];