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
@@ -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; } = [];