fix(security): #975 review — re-read directory groups at each AdminUI session re-validation (Auth 0.5.0)

AdminSessionRevalidator re-mapped the groups frozen into the cookie at sign-in,
so removing a user from a directory group changed nothing until
MaxSessionMinutes ended the session.

Bump ZB.MOM.WW.Auth.{Abstractions,Ldap,AspNetCore} 0.4.1 -> 0.5.0 (additive
ILdapGroupLookup; 0.4.2-0.4.4 changes only affect BindMode=User / API-key SQL
stores, unused here; solution builds clean). OtOpcUaLdapAuthService now
implements ILdapGroupLookup with the same Enabled / DevStubMode / insecure-
transport rules as sign-in, registered as the same singleton (a stub
ILdapAuthService gets a NotSupported lookup).

At each re-validation interval the revalidator looks the user up: Found ->
fresh groups replace the session's otopcua:group claims and are mapped;
UserNotFound / UserDisabled / AmbiguousUser / Found-with-no-groups -> reject;
DirectoryUnavailable (or a lookup fault) -> fail-soft on the last known groups
(still re-mapped), bounded by MaxSessionMinutes; NotSupported / ProviderDisabled
-> previous behaviour. Never queried under DisableLogin.

Tests (directory rows failed first): group removal / addition picked up after
the window, unchanged membership kept (positive control), four end-the-session
statuses, outage keeps the session until the absolute cap, DisableLogin issues
no lookup (control: one lookup otherwise); wrapper lookup rules + DI
registration. docs/security.md drops the 'no password-less lookup' claim.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Joseph Doherty
2026-12-03 12:25:41 -05:00
parent 35d14936ac
commit 81cf44cb90
8 changed files with 424 additions and 20 deletions
+3 -3
View File
@@ -237,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" />
+4 -3
View File
@@ -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`)
@@ -32,7 +32,7 @@ namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;
/// <c>"dev"</c>) so the dev session can navigate the full Admin UI (renamed from the prior
/// <c>"FleetAdmin"</c> to the canonical <c>"Administrator"</c>).
/// </remarks>
public sealed class OtOpcUaLdapAuthService : ILdapAuthService
public sealed class OtOpcUaLdapAuthService : ILdapAuthService, ILdapGroupLookup
{
private readonly LdapOptions _options;
private readonly LibILdapAuthService _inner;
@@ -130,6 +130,29 @@ public sealed class OtOpcUaLdapAuthService : ILdapAuthService
};
}
/// <summary>
/// Passwordless directory group lookup (shared library 0.5.0) for AdminUI session re-validation
/// (lmxopcua#975 review): re-reads a signed-in user's groups without their password, applying the same
/// app-only concerns as <see cref="AuthenticateAsync"/> — <see cref="LdapOptions.Enabled"/> off ⇒
/// <see cref="LdapGroupLookupStatus.ProviderDisabled"/>; <see cref="LdapOptions.DevStubMode"/> ⇒ the stub's
/// <c>dev</c> group, no network; a plaintext transport without <see cref="LdapOptions.AllowInsecure"/> ⇒
/// <see cref="LdapGroupLookupStatus.NotSupported"/>. Never throws except for cancellation.
/// </summary>
/// <param name="username">The signed-in (canonical) username.</param>
/// <param name="ct">Cancellation token.</param>
/// <returns>The lookup result.</returns>
public async Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
if (!_options.Enabled) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.ProviderDisabled);
if (string.IsNullOrWhiteSpace(username)) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.UserNotFound);
if (_options.DevStubMode) return LdapGroupLookupResult.Found(username, username, ["dev"]);
if (_options.Transport == LdapTransport.None && !_options.AllowInsecure)
return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
if (_inner is not ILdapGroupLookup lookup) return LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported);
return await lookup.GetUserGroupsAsync(username, ct).ConfigureAwait(false);
}
/// <summary>Folds a structured library failure code into the app's user-facing error text.</summary>
/// <param name="failure">The library failure code (null defensively treated as a generic error).</param>
private static string FailureToError(LdapAuthFailure? failure) => failure switch
@@ -0,0 +1,21 @@
using ZB.MOM.WW.Auth.Abstractions.Ldap;
namespace ZB.MOM.WW.OtOpcUa.Security.Ldap;
/// <summary>
/// The directory group lookup when the registered app LDAP service cannot do one (a test or dev stub): answers
/// every call <see cref="LdapGroupLookupStatus.NotSupported"/>, which AdminUI session re-validation treats as
/// "re-map the groups recorded at sign-in".
/// </summary>
internal sealed class UnsupportedLdapGroupLookup : ILdapGroupLookup
{
/// <summary>The shared instance.</summary>
public static readonly UnsupportedLdapGroupLookup Instance = new();
/// <inheritdoc />
public Task<LdapGroupLookupResult> GetUserGroupsAsync(string username, CancellationToken ct)
{
ct.ThrowIfCancellationRequested();
return Task.FromResult(LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported));
}
}
@@ -106,6 +106,15 @@ public static class ServiceCollectionExtensions
// driver path) ends up with exactly one descriptor regardless of registration order.
services.TryAddSingleton<ILdapAuthService, OtOpcUaLdapAuthService>();
// lmxopcua#975 (review 2026-12-02): the passwordless directory group lookup (ZB.MOM.WW.Auth 0.5.0) that
// session re-validation uses to re-read a signed-in user's groups. It is the SAME instance as the app's
// LDAP service (so it shares the Enabled / DevStubMode / transport rules and the library's sticky endpoint
// preference); a host that registers its own ILdapAuthService (a test stub) gets a NotSupported lookup,
// which re-validation treats as "re-map the sign-in groups" — the pre-0.5.0 behaviour.
services.TryAddSingleton<ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup>(sp =>
sp.GetRequiredService<ILdapAuthService>() as ZB.MOM.WW.Auth.Abstractions.Ldap.ILdapGroupLookup
?? UnsupportedLdapGroupLookup.Instance);
// Shared ZB.MOM.WW.Auth group→role mapper seam. Wraps the existing RoleMapper.Map +
// RoleMapper.Merge logic; consumed by AuthEndpoints.cs (/auth/login) and by
// AdminUI login (the OPC UA data plane uses API keys). Scoped to match
@@ -2,8 +2,10 @@ using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.Auth.Abstractions.Roles;
using ZB.MOM.WW.Auth.AspNetCore;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.Security.Session;
@@ -39,14 +41,24 @@ public sealed record SessionRevalidation(
/// </summary>
/// <remarks>
/// <para>
/// <b>No LDAP traffic.</b> The re-check re-runs the stored sign-in groups through
/// <c>IGroupRoleMapper&lt;string&gt;</c> (appsettings <c>GroupToRole</c> + DB
/// <c>LdapGroupRoleMapping</c>), so it costs one indexed ConfigDb read per
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> per session and never hammers the
/// directory. What it therefore CANNOT see is a change to the user's directory group membership
/// itself — the shared <c>ZB.MOM.WW.Auth.Ldap</c> client offers no password-less group lookup.
/// That window is bounded instead by <see cref="OtOpcUaCookieOptions.MaxSessionMinutes"/>, an absolute
/// session lifetime the sliding cookie cannot extend.
/// <b>Directory groups are re-read (lmxopcua#975 review 2026-12-02).</b> Each re-check first asks the
/// directory for the user's CURRENT groups through the passwordless <see cref="ILdapGroupLookup"/>
/// (<c>ZB.MOM.WW.Auth</c> 0.5.0 — a service-account search, no user password), then maps them through
/// <c>IGroupRoleMapper&lt;string&gt;</c> (appsettings <c>GroupToRole</c> + DB <c>LdapGroupRoleMapping</c>).
/// Cost: one directory search + one indexed ConfigDb read per
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> per session. The account gone, disabled,
/// ambiguous or in no group ⇒ the session ends. Before 0.5.0 the cookie's sign-in groups were re-mapped,
/// so removing a user from a directory group changed nothing until the absolute lifetime ended the
/// session.
/// </para>
/// <para>
/// <b>Fail-soft on a directory outage.</b> <see cref="LdapGroupLookupStatus.DirectoryUnavailable"/> (or a
/// lookup that throws) keeps the sign-in groups — still re-mapped, so a DB grant change applies — and the
/// session survives, bounded by <see cref="OtOpcUaCookieOptions.MaxSessionMinutes"/>, an absolute session
/// lifetime the sliding cookie cannot extend. Without a passwordless lookup (user-bind mode, no service
/// account, LDAP disabled, a stub service: <see cref="LdapGroupLookupStatus.NotSupported"/> /
/// <see cref="LdapGroupLookupStatus.ProviderDisabled"/>) the same applies. With
/// <c>Security:Auth:DisableLogin</c> the directory is never queried.
/// </para>
/// <para>
/// <b>Fail-soft on a mapper fault.</b> A ConfigDb blip must not sign every operator out: the existing
@@ -67,18 +79,30 @@ public sealed class AdminSessionRevalidator
/// <param name="options">The cookie / session options.</param>
/// <param name="time">The clock.</param>
/// <param name="logger">The logger.</param>
/// <param name="groupLookup">
/// The passwordless directory group lookup (lmxopcua#975 review); null — or one answering
/// <see cref="LdapGroupLookupStatus.NotSupported"/> — re-maps the groups recorded at sign-in instead.
/// </param>
/// <param name="disableLogin">The dev disable-login options: when set, the directory is never queried.</param>
public AdminSessionRevalidator(
IServiceScopeFactory scopes,
IOptionsMonitor<OtOpcUaCookieOptions> options,
TimeProvider time,
ILogger<AdminSessionRevalidator> logger)
ILogger<AdminSessionRevalidator> logger,
ILdapGroupLookup? groupLookup = null,
IOptions<AuthDisableLoginOptions>? disableLogin = null)
{
_scopes = scopes;
_options = options;
_time = time;
_logger = logger;
_groupLookup = groupLookup;
_disableLogin = disableLogin?.Value.DisableLogin ?? false;
}
private readonly ILdapGroupLookup? _groupLookup;
private readonly bool _disableLogin;
/// <summary>The configured re-validation interval (never below one minute).</summary>
public TimeSpan Interval => TimeSpan.FromMinutes(Math.Max(1, _options.CurrentValue.RevalidateIntervalMinutes));
@@ -111,6 +135,51 @@ public sealed class AdminSessionRevalidator
var groups = principal.FindAll(AdminSessionClaims.Group).Select(c => c.Value).ToArray();
var preResolved = principal.FindAll(AdminSessionClaims.PreResolvedRole).Select(c => c.Value).ToArray();
// Re-read the user's groups from the directory (lmxopcua#975 review). Found ⇒ the fresh groups replace the
// sign-in snapshot; the account is gone / disabled / ambiguous, or in no group ⇒ the session ends; an outage,
// NotSupported (user-bind mode, no service account, a stub service) or a disabled provider ⇒ fail-soft: keep
// the sign-in groups (still re-mapped below), bounded by MaxSessionMinutes. Never under DisableLogin.
string[]? directoryGroups = null;
var username = principal.FindFirst(ZbClaimTypes.Username)?.Value;
if (!_disableLogin && _groupLookup is not null && !string.IsNullOrWhiteSpace(username))
{
LdapGroupLookupResult lookup;
try
{
lookup = await _groupLookup.GetUserGroupsAsync(username, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger.LogWarning(ex, "Directory group re-check for {User} failed; treating it as a directory outage", user);
lookup = LdapGroupLookupResult.Of(LdapGroupLookupStatus.DirectoryUnavailable);
}
switch (lookup.Status)
{
case LdapGroupLookupStatus.Found when lookup.Groups.Count == 0:
return Reject(user, "the directory lists the account in no group");
case LdapGroupLookupStatus.Found:
directoryGroups = [.. lookup.Groups];
break;
case LdapGroupLookupStatus.UserNotFound:
return Reject(user, "the account no longer exists in the directory");
case LdapGroupLookupStatus.UserDisabled:
return Reject(user, "the account is disabled in the directory");
case LdapGroupLookupStatus.AmbiguousUser:
return Reject(user, "the directory no longer resolves the account to a single entry");
case LdapGroupLookupStatus.DirectoryUnavailable:
_logger.LogWarning(
"Directory group re-check for {User}: the directory is unavailable; keeping the sign-in groups " +
"(the session's absolute lifetime still caps it)", user);
break;
default:
// NotSupported / ProviderDisabled: no passwordless lookup in this configuration.
break;
}
}
if (directoryGroups is not null) groups = directoryGroups;
IReadOnlyList<string> mapped;
try
{
@@ -139,7 +208,7 @@ public sealed class AdminSessionRevalidator
"Role re-validation for {User}: roles changed [{Before}] -> [{After}]",
user, string.Join(",", current.Order()), string.Join(",", roles.Order()));
return new SessionRevalidation(SessionCheck.Renewed, Rebuild(principal, roles, now), changed);
return new SessionRevalidation(SessionCheck.Renewed, Rebuild(principal, roles, directoryGroups, now), changed);
}
private SessionRevalidation Reject(string user, string reason)
@@ -148,13 +217,20 @@ public sealed class AdminSessionRevalidator
return new SessionRevalidation(SessionCheck.Rejected, Reason: reason);
}
/// <summary>Copies <paramref name="source"/> with the role claims replaced and the validated-at stamp advanced.</summary>
private static ClaimsPrincipal Rebuild(ClaimsPrincipal source, IEnumerable<string> roles, DateTimeOffset now)
/// <summary>
/// Copies <paramref name="source"/> with the role claims replaced, the validated-at stamp advanced and — when
/// the directory answered — the recorded groups replaced, so a later fail-soft re-map uses the latest groups.
/// </summary>
private static ClaimsPrincipal Rebuild(
ClaimsPrincipal source, IEnumerable<string> roles, IReadOnlyList<string>? directoryGroups, DateTimeOffset now)
{
var original = source.Identities.First();
var claims = original.Claims
.Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt)
.Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt
&& (directoryGroups is null || c.Type != AdminSessionClaims.Group))
.ToList();
if (directoryGroups is not null)
foreach (var group in directoryGroups) claims.Add(new Claim(AdminSessionClaims.Group, group));
foreach (var role in roles.Order(StringComparer.OrdinalIgnoreCase))
claims.Add(new Claim(ZbClaimTypes.Role, role));
claims.Add(new Claim(AdminSessionClaims.ValidatedAt, AdminSessionClaims.Format(now)));
@@ -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; } = [];