From 81cf44cb90628a99364555983828f269bf569a6c Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 12:25:41 -0500 Subject: [PATCH] =?UTF-8?q?fix(security):=20#975=20review=20=E2=80=94=20re?= =?UTF-8?q?-read=20directory=20groups=20at=20each=20AdminUI=20session=20re?= =?UTF-8?q?-validation=20(Auth=200.5.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- Directory.Packages.props | 6 +- docs/security.md | 7 +- .../Ldap/OtOpcUaLdapAuthService.cs | 25 ++- .../Ldap/UnsupportedLdapGroupLookup.cs | 21 +++ .../ServiceCollectionExtensions.cs | 9 ++ .../Session/AdminSessionRevalidator.cs | 102 ++++++++++-- .../OtOpcUaLdapGroupLookupTests.cs | 126 +++++++++++++++ .../SessionRevalidationTests.cs | 148 ++++++++++++++++++ 8 files changed, 424 insertions(+), 20 deletions(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/UnsupportedLdapGroupLookup.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/OtOpcUaLdapGroupLookupTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 7dfa66fe3..62d6f8e60 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -237,9 +237,9 @@ - - - + + + diff --git a/docs/security.md b/docs/security.md index 424d88847..5845bd3e5 100644 --- a/docs/security.md +++ b/docs/security.md @@ -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` (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` (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`) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs index 43affb873..bd8376c81 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/OtOpcUaLdapAuthService.cs @@ -32,7 +32,7 @@ namespace ZB.MOM.WW.OtOpcUa.Security.Ldap; /// "dev") so the dev session can navigate the full Admin UI (renamed from the prior /// "FleetAdmin" to the canonical "Administrator"). /// -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 }; } + /// + /// 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 — off ⇒ + /// ; ⇒ the stub's + /// dev group, no network; a plaintext transport without ⇒ + /// . Never throws except for cancellation. + /// + /// The signed-in (canonical) username. + /// Cancellation token. + /// The lookup result. + public async Task 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); + } + /// Folds a structured library failure code into the app's user-facing error text. /// The library failure code (null defensively treated as a generic error). private static string FailureToError(LdapAuthFailure? failure) => failure switch diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/UnsupportedLdapGroupLookup.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/UnsupportedLdapGroupLookup.cs new file mode 100644 index 000000000..22f8b8854 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Ldap/UnsupportedLdapGroupLookup.cs @@ -0,0 +1,21 @@ +using ZB.MOM.WW.Auth.Abstractions.Ldap; + +namespace ZB.MOM.WW.OtOpcUa.Security.Ldap; + +/// +/// The directory group lookup when the registered app LDAP service cannot do one (a test or dev stub): answers +/// every call , which AdminUI session re-validation treats as +/// "re-map the groups recorded at sign-in". +/// +internal sealed class UnsupportedLdapGroupLookup : ILdapGroupLookup +{ + /// The shared instance. + public static readonly UnsupportedLdapGroupLookup Instance = new(); + + /// + public Task GetUserGroupsAsync(string username, CancellationToken ct) + { + ct.ThrowIfCancellationRequested(); + return Task.FromResult(LdapGroupLookupResult.Of(LdapGroupLookupStatus.NotSupported)); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs index 4ecc67c50..5898fbdde 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs @@ -106,6 +106,15 @@ public static class ServiceCollectionExtensions // driver path) ends up with exactly one descriptor regardless of registration order. services.TryAddSingleton(); + // 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(sp => + sp.GetRequiredService() 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 diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs index 8640debea..29c6a76d4 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs @@ -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( /// /// /// -/// No LDAP traffic. The re-check re-runs the stored sign-in groups through -/// IGroupRoleMapper<string> (appsettings GroupToRole + DB -/// LdapGroupRoleMapping), so it costs one indexed ConfigDb read per -/// 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 ZB.MOM.WW.Auth.Ldap client offers no password-less group lookup. -/// That window is bounded instead by , an absolute -/// session lifetime the sliding cookie cannot extend. +/// Directory groups are re-read (lmxopcua#975 review 2026-12-02). Each re-check first asks the +/// directory for the user's CURRENT groups through the passwordless +/// (ZB.MOM.WW.Auth 0.5.0 — a service-account search, no user password), then maps them through +/// IGroupRoleMapper<string> (appsettings GroupToRole + DB LdapGroupRoleMapping). +/// Cost: one directory search + one indexed ConfigDb read per +/// 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. +/// +/// +/// Fail-soft on a directory outage. (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 , an absolute session +/// lifetime the sliding cookie cannot extend. Without a passwordless lookup (user-bind mode, no service +/// account, LDAP disabled, a stub service: / +/// ) the same applies. With +/// Security:Auth:DisableLogin the directory is never queried. /// /// /// Fail-soft on a mapper fault. A ConfigDb blip must not sign every operator out: the existing @@ -67,18 +79,30 @@ public sealed class AdminSessionRevalidator /// The cookie / session options. /// The clock. /// The logger. + /// + /// The passwordless directory group lookup (lmxopcua#975 review); null — or one answering + /// — re-maps the groups recorded at sign-in instead. + /// + /// The dev disable-login options: when set, the directory is never queried. public AdminSessionRevalidator( IServiceScopeFactory scopes, IOptionsMonitor options, TimeProvider time, - ILogger logger) + ILogger logger, + ILdapGroupLookup? groupLookup = null, + IOptions? 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; + /// The configured re-validation interval (never below one minute). 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 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); } - /// Copies with the role claims replaced and the validated-at stamp advanced. - private static ClaimsPrincipal Rebuild(ClaimsPrincipal source, IEnumerable roles, DateTimeOffset now) + /// + /// Copies 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. + /// + private static ClaimsPrincipal Rebuild( + ClaimsPrincipal source, IEnumerable roles, IReadOnlyList? 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))); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/OtOpcUaLdapGroupLookupTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/OtOpcUaLdapGroupLookupTests.cs new file mode 100644 index 000000000..b3f366960 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/OtOpcUaLdapGroupLookupTests.cs @@ -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; + +/// +/// lmxopcua#975 (review 2026-12-02): the app's LDAP wrapper exposes the shared library's 0.5.0 passwordless +/// 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: Enabled is the master switch, DevStubMode +/// answers the stub's group set without touching the network, and a plaintext transport without +/// AllowInsecure is refused. +/// +public sealed class OtOpcUaLdapGroupLookupTests +{ + private static ILdapGroupLookup Build(AppLdapOptions options, LibILdapAuthService inner) => + new AppLdapAuthService(options, inner, NullLogger.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); + } + + /// AddOtOpcUaAuth registers the lookup as the app's LDAP service — or NotSupported for a stub service. + [Fact] + public async Task AddOtOpcUaAuth_registers_the_group_lookup() + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(o => o.UseInMemoryDatabase($"lookup-{Guid.NewGuid():N}")); + services.AddOtOpcUaAuth(new ConfigurationBuilder().Build()); + using (var provider = services.BuildServiceProvider()) + provider.GetRequiredService().ShouldBeOfType(); + + services.AddSingleton(); + using (var provider = services.BuildServiceProvider()) + { + var lookup = provider.GetRequiredService(); + (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 AuthenticateAsync(string username, string password, CancellationToken ct) => + throw new NotSupportedException(); + + public Task GetUserGroupsAsync(string username, CancellationToken ct) + { + LookedUp = username; + return Task.FromResult(result); + } + } + + private sealed class AuthOnlyLib : LibILdapAuthService + { + public Task AuthenticateAsync(string username, string password, CancellationToken ct) => + throw new NotSupportedException(); + } + + private sealed class AuthOnlyAppService : ZB.MOM.WW.OtOpcUa.Security.Ldap.ILdapAuthService + { + public Task AuthenticateAsync( + string username, string password, CancellationToken ct = default) => throw new NotSupportedException(); + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs index eae6872eb..e76cd8c18 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs @@ -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(); services.AddSingleton(_mappings); + services.AddSingleton(_directory); }); web.Configure(app => { @@ -259,6 +264,128 @@ public sealed class SessionRevalidationTests : IAsyncLifetime (await roles.Content.ReadFromJsonAsync(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. + + /// The reported defect: removed from the directory group ⇒ the elevated policy is gone after the window. + [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(Ct)).ShouldBe(["Viewer"]); + _directory.Lookups.ShouldContain("editor"); + } + + /// Positive control: the directory still lists the same groups ⇒ the session keeps its roles. + [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"); + } + + /// A promotion in the directory is picked up too. + [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); + } + + /// The account is gone, disabled, ambiguous, or in no group at all ⇒ the session ends. + [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); + } + + /// + /// 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. + /// + [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); + } + + /// Login disabled (dev rig): the re-validator never queries the directory. Positive control: it does otherwise. + [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(), + _host.Services.GetRequiredService>(), + _clock, + NullLogger.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 }); } + /// The 0.5.0 passwordless lookup; a user with no answer set is NotSupported (the pre-0.5.0 behaviour). + private sealed class StubDirectory : ILdapGroupLookup + { + private readonly Dictionary _answers = new(StringComparer.OrdinalIgnoreCase); + + public List Lookups { get; } = []; + + public void Answer(string user, IReadOnlyList groups) => + _answers[user] = LdapGroupLookupResult.Found(user, user, groups); + + public void Answer(string user, LdapGroupLookupStatus status) => _answers[user] = LdapGroupLookupResult.Of(status); + + public Task 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 Rows { get; } = [];