From 019ba963760a54ca2d506f824d7f99e30b354f01 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 10:12:54 -0500 Subject: [PATCH] fix(adminui-auth): #975 AdminUI roles are re-validated on a timer (cookie OnValidatePrincipal + revalidating circuit provider); demoted users lose elevated policies within the window --- docs/Configuration.md | 2 + docs/security.md | 12 + .../CookieOptions.cs | 15 + .../Endpoints/AuthEndpoints.cs | 5 + .../ServiceCollectionExtensions.cs | 41 ++ .../Session/AdminSessionClaims.cs | 57 +++ .../Session/AdminSessionRevalidator.cs | 164 ++++++ ...idatingAdminAuthenticationStateProvider.cs | 55 +++ .../AuthEndpointsIntegrationTests.cs | 10 +- .../SessionRevalidationTests.cs | 467 ++++++++++++++++++ 10 files changed, 827 insertions(+), 1 deletion(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionClaims.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/RevalidatingAdminAuthenticationStateProvider.cs create mode 100644 tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs diff --git a/docs/Configuration.md b/docs/Configuration.md index 599fcdd54..fede569cf 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -155,6 +155,8 @@ Security__Ldap__GroupToRole__=Viewer |---|---|---|---| | `Name` | string | `ZB.MOM.WW.OtOpcUa.Auth` | Auth cookie name. Changing it invalidates existing sessions on next deploy. | | `ExpiryMinutes` | int | `30` | Idle sliding-window length. | +| `RevalidateIntervalMinutes` | int | `5` | How often a session's roles are re-resolved from the current group→role grants (cookie: first request after the interval; open Blazor circuit: on a timer). ConfigDb read only, never LDAP. Values < 1 are treated as 1 (lmxopcua#975). | +| `MaxSessionMinutes` | int | `480` | Absolute session lifetime from interactive sign-in; the sliding cookie cannot extend it. `0` disables. Bounds how long a directory-group-membership change (invisible to the ConfigDb-only re-check) goes unnoticed. | | `RequireHttpsCookie` | bool | `true` | `SecurePolicy = Always`. Set `false` only for plain-HTTP local dev (emits a startup Warning). | > Authentication, data-plane authorization (`NodeAcl` / `PermissionTrie`), and control-plane Admin roles are all in [`security.md`](security.md). diff --git a/docs/security.md b/docs/security.md index 83cd4509a..09f97b5d4 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1778,6 +1778,18 @@ service account can read (another product's client certificate, a host certifica Admin reads `LdapGroupRoleMapping` rows from the Config DB (`src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/LdapGroupRoleMapping.cs`) — the same pattern as the data-plane `NodeAcl` but scoped to Admin roles + (optionally) one cluster for multi-site fleets (a system-wide row, `IsSystemWide = true`, stacks additively with cluster-scoped rows). The `RoleGrants.razor` page lets `Administrator`s edit these mappings without leaving the UI. +### AdminUI role freshness (#975 / review A-2) + +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**. +- **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). +- **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. + ### Headless deploy API (`POST /api/deployments`) For CI / scripts that need to trigger a deployment without driving the Blazor "Deploy current configuration" button, admin-role nodes expose `POST /api/deployments` (`DeployApiEndpoints`, `src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Api/DeployApiEndpoints.cs`). It forwards to the same `IAdminOperationsClient.StartDeploymentAsync` the button calls. diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/CookieOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/CookieOptions.cs index ee39de9bf..dca34464d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/CookieOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/CookieOptions.cs @@ -20,6 +20,21 @@ public sealed class OtOpcUaCookieOptions /// Idle sliding-window length in minutes (default 30). public int ExpiryMinutes { get; set; } = 30; + /// + /// How often (minutes) a session's roles are re-resolved from the current group→role grants + /// (GroupToRole + LdapGroupRoleMapping) — for the cookie, on the first request after the + /// interval; for an open Blazor circuit, on a timer (lmxopcua#975). Default 5; values below 1 are + /// treated as 1. The re-check reads ConfigDb only — it never contacts the LDAP directory. + /// + public int RevalidateIntervalMinutes { get; set; } = 5; + + /// + /// Absolute session lifetime (minutes) measured from the interactive sign-in; the sliding cookie + /// cannot extend it. This is the bound on how long a change to the user's directory group membership + /// (which the ConfigDb-only re-check cannot observe) stays unnoticed. Default 480 (8 h); 0 disables. + /// + public int MaxSessionMinutes { get; set; } = 480; + /// /// Require HTTPS for the auth cookie. Default true: cookie is marked /// SecurePolicy = Always. Set to false ONLY for local dev stacks running diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs index 2c1d833b9..3662deb08 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Endpoints/AuthEndpoints.cs @@ -13,6 +13,7 @@ using ZB.MOM.WW.Auth.AspNetCore; using ZB.MOM.WW.Auth.Abstractions.Roles; using ZB.MOM.WW.OtOpcUa.Security.Jwt; using ZB.MOM.WW.OtOpcUa.Security.Ldap; +using ZB.MOM.WW.OtOpcUa.Security.Session; namespace ZB.MOM.WW.OtOpcUa.Security.Endpoints; @@ -156,6 +157,10 @@ public static class AuthEndpoints foreach (var role in roles) // ZbClaimTypes.Role = ClaimTypes.Role — framework [Authorize(Roles=...)] + IsInRole work. claims.Add(new Claim(ZbClaimTypes.Role, role)); + // Session re-validation state (lmxopcua#975): the groups + sign-in-granted roles the re-check + // re-resolves against the current grants, and the sign-in / last-validated stamps. + var time = http.RequestServices.GetService() ?? TimeProvider.System; + AdminSessionClaims.Stamp(claims, result.Groups, result.Roles, time.GetUtcNow()); var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme); var principal = new ClaimsPrincipal(identity); diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs index 494145be8..4ecc67c50 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/ServiceCollectionExtensions.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; @@ -16,6 +17,7 @@ using ZB.MOM.WW.OtOpcUa.Security.Audit; using ZB.MOM.WW.OtOpcUa.Security.Auth; using ZB.MOM.WW.OtOpcUa.Security.Jwt; using ZB.MOM.WW.OtOpcUa.Security.Ldap; +using ZB.MOM.WW.OtOpcUa.Security.Session; namespace ZB.MOM.WW.OtOpcUa.Security; @@ -29,6 +31,33 @@ namespace ZB.MOM.WW.OtOpcUa.Security; /// public static class ServiceCollectionExtensions { + /// + /// Cookie OnValidatePrincipal (lmxopcua#975 / review A-2): re-resolves the session's roles on the + /// configured interval, replacing the principal when they changed and ending the session when the + /// account no longer maps to any role (or is stale / past its absolute lifetime). + /// + /// The cookie validation context. + internal static async Task ValidateSessionAsync(CookieValidatePrincipalContext context) + { + if (context.Principal is null) return; + var revalidator = context.HttpContext.RequestServices.GetRequiredService(); + var result = await revalidator + .RevalidateAsync(context.Principal, force: false, context.HttpContext.RequestAborted) + .ConfigureAwait(false); + switch (result.Outcome) + { + case SessionCheck.Rejected: + context.RejectPrincipal(); + await context.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme) + .ConfigureAwait(false); + break; + case SessionCheck.Renewed: + context.ReplacePrincipal(result.Principal!); + context.ShouldRenew = true; + break; + } + } + /// /// Wires cookie authentication, DataProtection key persistence to ConfigDb, /// LDAP services, and the LDAP-backed JwtTokenService. Browser flows redirect to @@ -84,6 +113,14 @@ public static class ServiceCollectionExtensions // would capture the scoped DB service. services.TryAddScoped, OtOpcUaGroupRoleMapper>(); + // Session role re-validation (lmxopcua#975 / review A-2): the cookie's OnValidatePrincipal and every + // Blazor circuit re-resolve the signed-in user's roles on Security:Cookie:RevalidateIntervalMinutes. + // The provider is registered with AddScoped (last wins) so it replaces the framework's plain + // ServerAuthenticationStateProvider regardless of whether AddRazorComponents ran before or after. + services.TryAddSingleton(TimeProvider.System); + services.TryAddSingleton(); + services.AddScoped(); + services.AddDataProtection() .PersistKeysToDbContext() .SetApplicationName("OtOpcUa"); @@ -154,6 +191,10 @@ public static class ServiceCollectionExtensions o.LogoutPath = "/auth/logout"; // No OnRedirectToLogin / OnRedirectToAccessDenied overrides — let the framework's // built-in IsAjaxRequest heuristic do its thing (302 for browsers, 401 for AJAX). + + // lmxopcua#975 / review A-2: roles were frozen at sign-in for as long as the cookie slid. + // Within the interval this is a claim-timestamp comparison; past it, one ConfigDb read. + o.Events.OnValidatePrincipal = ValidateSessionAsync; }); } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionClaims.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionClaims.cs new file mode 100644 index 000000000..c739d0069 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionClaims.cs @@ -0,0 +1,57 @@ +using System.Globalization; +using System.Security.Claims; + +namespace ZB.MOM.WW.OtOpcUa.Security.Session; + +/// +/// The claims /auth/login stamps onto the AdminUI cookie principal so the session can be +/// re-validated later (lmxopcua#975 / review A-2). They carry exactly what a re-check needs and +/// nothing the directory would have to be asked for: the LDAP groups the user held at sign-in (re-run +/// through IGroupRoleMapper<string> against the CURRENT appsettings + DB grants), the +/// roles the sign-in pre-resolved outside the mapper (the DevStub grant), and two timestamps. +/// +public static class AdminSessionClaims +{ + /// One claim per LDAP group the user held at sign-in. + public const string Group = "otopcua:group"; + + /// One claim per role the sign-in granted outside the group mapper (DevStub's Administrator). + public const string PreResolvedRole = "otopcua:preresolved-role"; + + /// Unix seconds of the interactive sign-in; the absolute session lifetime is measured from it. + public const string AuthTime = "otopcua:auth-time"; + + /// Unix seconds of the last successful role re-validation (or the sign-in). + public const string ValidatedAt = "otopcua:validated-at"; + + /// Formats a timestamp as the unix-seconds claim value. + /// The instant. + public static string Format(DateTimeOffset at) => + at.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture); + + /// Parses a unix-seconds claim value; when absent or malformed. + /// The claim value. + public static DateTimeOffset? Parse(string? value) => + long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var seconds) + ? DateTimeOffset.FromUnixTimeSeconds(seconds) + : null; + + /// Appends the session-state claims to a sign-in claim list. + /// The claim list being built for the new principal. + /// The LDAP groups the directory returned. + /// Roles granted by the sign-in itself, not by the mapper. + /// The sign-in instant. + public static void Stamp( + ICollection claims, + IEnumerable groups, + IEnumerable preResolvedRoles, + DateTimeOffset now) + { + foreach (var group in groups.Distinct(StringComparer.OrdinalIgnoreCase)) + claims.Add(new Claim(Group, group)); + foreach (var role in preResolvedRoles.Distinct(StringComparer.OrdinalIgnoreCase)) + claims.Add(new Claim(PreResolvedRole, role)); + claims.Add(new Claim(AuthTime, Format(now))); + claims.Add(new Claim(ValidatedAt, Format(now))); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs new file mode 100644 index 000000000..8640debea --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/AdminSessionRevalidator.cs @@ -0,0 +1,164 @@ +using System.Security.Claims; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.Auth.Abstractions.Roles; +using ZB.MOM.WW.Auth.AspNetCore; + +namespace ZB.MOM.WW.OtOpcUa.Security.Session; + +/// Outcome of . +public enum SessionCheck +{ + /// The session is current: nothing to do (inside the interval, or the check could not run). + Valid, + + /// The roles were re-resolved; carries the refreshed principal. + Renewed, + + /// The session must end: the account no longer maps to any role, or the session is stale/foreign. + Rejected, +} + +/// Result of a session re-validation. +/// What to do with the session. +/// The refreshed principal when is . +/// True when the re-resolved role SET differs from the one in the presented principal. +/// Why the session was rejected (for logs). +public sealed record SessionRevalidation( + SessionCheck Outcome, + ClaimsPrincipal? Principal = null, + bool RolesChanged = false, + string? Reason = null); + +/// +/// Re-validates an AdminUI cookie principal's roles on a timer (lmxopcua#975 / review A-2). Group→role +/// resolution used to run exactly once, in /auth/login, so a user removed from an admin group or +/// whose /role-grants row was deleted kept every role for as long as the cookie slid or a Blazor +/// circuit stayed open. +/// +/// +/// +/// 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. +/// +/// +/// Fail-soft on a mapper fault. A ConfigDb blip must not sign every operator out: the existing +/// session is kept (and re-tried on the next request); the absolute lifetime still caps it. +/// A session with NO session-state claims (a cookie minted before this change) is rejected, forcing +/// one re-login — it cannot be re-validated. +/// +/// +public sealed class AdminSessionRevalidator +{ + private readonly IServiceScopeFactory _scopes; + private readonly IOptionsMonitor _options; + private readonly TimeProvider _time; + private readonly ILogger _logger; + + /// Initializes a new instance of the class. + /// Creates the scope the (scoped, DbContext-backed) group mapper is resolved in. + /// The cookie / session options. + /// The clock. + /// The logger. + public AdminSessionRevalidator( + IServiceScopeFactory scopes, + IOptionsMonitor options, + TimeProvider time, + ILogger logger) + { + _scopes = scopes; + _options = options; + _time = time; + _logger = logger; + } + + /// The configured re-validation interval (never below one minute). + public TimeSpan Interval => TimeSpan.FromMinutes(Math.Max(1, _options.CurrentValue.RevalidateIntervalMinutes)); + + /// Re-validates . + /// The principal from the cookie (or a circuit's captured authentication state). + /// + /// True to re-check regardless of — a circuit holds one + /// principal for its whole life, so its stamp is always old and the circuit paces itself. + /// + /// Cancellation token. + public async Task RevalidateAsync( + ClaimsPrincipal principal, bool force, CancellationToken ct) + { + ArgumentNullException.ThrowIfNull(principal); + var user = principal.FindFirst(ZbClaimTypes.Username)?.Value ?? principal.Identity?.Name ?? ""; + var now = _time.GetUtcNow(); + + var authTime = AdminSessionClaims.Parse(principal.FindFirst(AdminSessionClaims.AuthTime)?.Value); + var validatedAt = AdminSessionClaims.Parse(principal.FindFirst(AdminSessionClaims.ValidatedAt)?.Value); + if (authTime is null || validatedAt is null) + return Reject(user, "the session carries no re-validation state (cookie predates session re-validation)"); + + var maxMinutes = _options.CurrentValue.MaxSessionMinutes; + if (maxMinutes > 0 && now - authTime.Value >= TimeSpan.FromMinutes(maxMinutes)) + return Reject(user, $"the session exceeded its absolute lifetime of {maxMinutes} min"); + + if (!force && now - validatedAt.Value < Interval) + return new SessionRevalidation(SessionCheck.Valid); + + var groups = principal.FindAll(AdminSessionClaims.Group).Select(c => c.Value).ToArray(); + var preResolved = principal.FindAll(AdminSessionClaims.PreResolvedRole).Select(c => c.Value).ToArray(); + + IReadOnlyList mapped; + try + { + await using var scope = _scopes.CreateAsyncScope(); + var mapper = scope.ServiceProvider.GetRequiredService>(); + mapped = (await mapper.MapAsync(groups, ct).ConfigureAwait(false)).Roles; + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + _logger.LogWarning(ex, + "Role re-validation for {User} could not reach the role map; keeping the current session and retrying next interval", + user); + return new SessionRevalidation(SessionCheck.Valid); + } + + var roles = new HashSet(preResolved, StringComparer.OrdinalIgnoreCase); + foreach (var role in mapped) roles.Add(role); + if (roles.Count == 0) + return Reject(user, "the account's groups no longer map to any role"); + + var current = principal.FindAll(ZbClaimTypes.Role).Select(c => c.Value) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + var changed = !current.SetEquals(roles); + if (changed) + _logger.LogInformation( + "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); + } + + private SessionRevalidation Reject(string user, string reason) + { + _logger.LogWarning("AdminUI session for {User} rejected: {Reason}", user, reason); + 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) + { + var original = source.Identities.First(); + var claims = original.Claims + .Where(c => c.Type != ZbClaimTypes.Role && c.Type != AdminSessionClaims.ValidatedAt) + .ToList(); + foreach (var role in roles.Order(StringComparer.OrdinalIgnoreCase)) + claims.Add(new Claim(ZbClaimTypes.Role, role)); + claims.Add(new Claim(AdminSessionClaims.ValidatedAt, AdminSessionClaims.Format(now))); + return new ClaimsPrincipal(new ClaimsIdentity( + claims, original.AuthenticationType, original.NameClaimType, original.RoleClaimType)); + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/RevalidatingAdminAuthenticationStateProvider.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/RevalidatingAdminAuthenticationStateProvider.cs new file mode 100644 index 000000000..51bf39e1f --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Security/Session/RevalidatingAdminAuthenticationStateProvider.cs @@ -0,0 +1,55 @@ +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Server; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.OtOpcUa.Security.Auth; + +namespace ZB.MOM.WW.OtOpcUa.Security.Session; + +/// +/// Authentication-state provider for AdminUI Blazor circuits that re-checks the circuit's principal on +/// (lmxopcua#975 / review A-2). A circuit +/// captures the principal once, when it connects, and cookie expiry does not end it — without this an +/// open tab keeps the roles it connected with indefinitely. +/// +/// +/// A circuit cannot re-issue the browser's cookie, so a changed role set is treated as an invalid +/// state exactly like a revoked one: the framework swaps in an anonymous principal and every +/// AuthorizeView / policy check fails closed. A page reload picks up the cookie the HTTP +/// pipeline refreshed (or sends the user to /login). With Security:Auth:DisableLogin=true +/// the principal is the dev auto-login user, which has no session-state claims, so the check is skipped. +/// +public class RevalidatingAdminAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider +{ + private readonly AdminSessionRevalidator _revalidator; + private readonly bool _disableLogin; + + /// Initializes a new instance of the class. + /// The logger factory. + /// The shared session re-validator. + /// The dev disable-login options. + public RevalidatingAdminAuthenticationStateProvider( + ILoggerFactory loggerFactory, + AdminSessionRevalidator revalidator, + IOptions disableLogin) + : base(loggerFactory) + { + _revalidator = revalidator; + _disableLogin = disableLogin.Value.DisableLogin; + } + + /// + protected override TimeSpan RevalidationInterval => _revalidator.Interval; + + /// + protected override async Task ValidateAuthenticationStateAsync( + AuthenticationState authenticationState, CancellationToken cancellationToken) + { + if (_disableLogin || authenticationState.User.Identity?.IsAuthenticated != true) + return true; + + var result = await _revalidator.RevalidateAsync(authenticationState.User, force: true, cancellationToken) + .ConfigureAwait(false); + return result.Outcome != SessionCheck.Rejected && !result.RolesChanged; + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs index 8cb521324..82c973c18 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/AuthEndpointsIntegrationTests.cs @@ -108,8 +108,16 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime // pre-fix /auth/login produced — so /auth/token's zero-role refusal is testable. e.MapPost("/test/signin-no-role", async (HttpContext ctx) => { + // Carries fresh session-revalidation stamps (lmxopcua#975) — an unstamped cookie is + // now refused outright — but NO role claim, the shape #913's refusal guards. + var legacyClaims = new List + { + new(ZbClaimTypes.Name, "legacy"), new(ZbClaimTypes.Username, "legacy"), + }; + ZB.MOM.WW.OtOpcUa.Security.Session.AdminSessionClaims.Stamp( + legacyClaims, [], [], DateTimeOffset.UtcNow); var identity = new ClaimsIdentity( - [new Claim(ZbClaimTypes.Name, "legacy"), new Claim(ZbClaimTypes.Username, "legacy")], + legacyClaims, Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme); await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync( ctx, diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs new file mode 100644 index 000000000..eae6872eb --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Security.Tests/SessionRevalidationTests.cs @@ -0,0 +1,467 @@ +using System.Net; +using System.Net.Http.Json; +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Shouldly; +using Xunit; +using ZB.MOM.WW.Auth.AspNetCore; +using ZB.MOM.WW.OtOpcUa.Configuration; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Enums; +using ZB.MOM.WW.OtOpcUa.Configuration.Services; +using ZB.MOM.WW.OtOpcUa.Security.Auth; +using ZB.MOM.WW.OtOpcUa.Security.Endpoints; +using ZB.MOM.WW.OtOpcUa.Security.Ldap; +using ZB.MOM.WW.OtOpcUa.Security.Session; + +namespace ZB.MOM.WW.OtOpcUa.Security.Tests; + +/// +/// lmxopcua#975 / review A-2 — AdminUI roles were frozen at sign-in: a sliding cookie and open Blazor circuits +/// never re-checked the group→role grants. A demoted user must lose the elevated policy within the +/// re-validation window; an unchanged user (positive control) must keep it. +/// +public sealed class SessionRevalidationTests : IAsyncLifetime +{ + private const int IntervalMinutes = 5; + private const int MaxSessionMinutes = 60; + + private readonly TestClock _clock = new(); + private readonly StubMappings _mappings = new(); + private IHost _host = null!; + private TestServer _server = null!; + + private static CancellationToken Ct => TestContext.Current.CancellationToken; + + public async ValueTask InitializeAsync() + { + var dbName = $"session-reval-{Guid.NewGuid():N}"; + _host = new HostBuilder() + .ConfigureWebHost(web => + { + web.UseTestServer(); + web.ConfigureServices(services => + { + services.AddDbContextFactory(o => o.UseInMemoryDatabase(dbName)); + services.AddDbContext(o => o.UseInMemoryDatabase(dbName)); + services.AddRouting(); + services.AddSingleton(_clock); + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Security:Cookie:RevalidateIntervalMinutes"] = IntervalMinutes.ToString(), + ["Security:Cookie:MaxSessionMinutes"] = MaxSessionMinutes.ToString(), + // Baseline: ReadOnly -> Viewer. Editors -> Designer comes from a DB grant the test deletes. + ["Security:Ldap:GroupToRole:ReadOnly"] = "Viewer", + }).Build(); + services.AddOtOpcUaAuth(configuration); + services.AddSingleton(); + services.AddSingleton(_mappings); + }); + web.Configure(app => + { + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(e => + { + e.MapOtOpcUaAuth(); + e.MapGet("/api/editor", () => Results.Ok("editor")) + .RequireAuthorization(AdminUiPolicies.ConfigEditor); + e.MapGet("/api/read", () => Results.Ok("read")) + .RequireAuthorization(AdminUiPolicies.AuthenticatedRead); + e.MapGet("/api/roles", (HttpContext c) => + Results.Ok(c.User.FindAll(ZbClaimTypes.Role).Select(x => x.Value).Order().ToArray())) + .RequireAuthorization(AdminUiPolicies.AuthenticatedRead); + // A cookie minted by a build without session re-validation: roles but NO stamps. + e.MapPost("/test/signin-unstamped", async (HttpContext ctx) => + { + var id = new ClaimsIdentity( + [new Claim(ZbClaimTypes.Name, "old"), new Claim(ZbClaimTypes.Role, "Administrator")], + "Cookies"); + await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync( + ctx, "Cookies", new ClaimsPrincipal(id)); + return Results.NoContent(); + }).AllowAnonymous().DisableAntiforgery(); + }); + }); + }) + .Build(); + await _host.StartAsync(Ct); + _server = _host.GetTestServer(); + } + + public async ValueTask DisposeAsync() + { + await _host.StopAsync(Ct); + _host.Dispose(); + } + + private async Task LoginAsync(string user) + { + var response = await _server.CreateClient().PostAsJsonAsync("/auth/login", + new AuthEndpoints.LoginRequest(user, "pw"), Ct); + response.StatusCode.ShouldBe(HttpStatusCode.NoContent); + return response; + } + + private async Task GetAsync(string path, HttpResponseMessage cookieSource) + { + var req = new HttpRequestMessage(HttpMethod.Get, path); + req.Headers.Add("X-Requested-With", "XMLHttpRequest"); // 401 instead of a login redirect + var pairs = cookieSource.Headers.GetValues("Set-Cookie").Select(c => c.Split(';', 2)[0]); + req.Headers.Add("Cookie", string.Join("; ", pairs)); + return await _server.CreateClient().SendAsync(req, Ct); + } + + private void GrantDesigner() => _mappings.Rows.Add(new LdapGroupRoleMapping + { + Id = Guid.NewGuid(), LdapGroup = "Editors", Role = AdminRole.Designer, IsSystemWide = true, + }); + + /// The reported defect: demote -> the elevated policy is gone once the window elapses. + [Fact] + public async Task Demoted_user_loses_the_elevated_policy_after_the_window_but_not_before() + { + GrantDesigner(); + var login = await LoginAsync("editor"); // groups: ReadOnly + Editors -> Viewer + Designer + (await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK); + + _mappings.Rows.Clear(); // FleetAdmin deletes the /role-grants row + + // Inside the window the session is (by design) still the sign-in snapshot. + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes - 1)); + (await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK); + + _clock.Advance(TimeSpan.FromMinutes(2)); // past the interval + (await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + + // The session is refreshed, not ended: the remaining baseline role still reads. + var read = await GetAsync("/api/roles", login); + read.StatusCode.ShouldBe(HttpStatusCode.OK); + (await read.Content.ReadFromJsonAsync(Ct)).ShouldBe(["Viewer"]); + } + + /// Positive control: nothing changed -> the elevated policy survives the re-check (and the check ran). + [Fact] + public async Task Unchanged_user_keeps_the_elevated_policy_across_the_window() + { + GrantDesigner(); + var login = await LoginAsync("editor"); + + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1)); + var response = await GetAsync("/api/editor", login); + + response.StatusCode.ShouldBe(HttpStatusCode.OK); + // The re-check ran: the cookie was re-issued carrying the advanced validated-at stamp. + response.Headers.TryGetValues("Set-Cookie", out var renewed).ShouldBeTrue(); + renewed!.ShouldContain(c => c.StartsWith("ZB.MOM.WW.OtOpcUa.Auth=")); + } + + /// A promotion is picked up too (the refreshed principal carries the CURRENT role set). + [Fact] + public async Task Newly_granted_role_is_picked_up_after_the_window() + { + var login = await LoginAsync("editor"); // no Designer grant yet + (await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + + GrantDesigner(); + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1)); + + (await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK); + } + + /// An account whose groups no longer map to ANY role is signed out, not left with a role-less session. + [Fact] + public async Task Account_with_no_remaining_role_is_signed_out_after_the_window() + { + GrantDesigner(); + var login = await LoginAsync("editor-only"); // group Editors only -> Designer via the DB grant + (await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.OK); + + _mappings.Rows.Clear(); + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1)); + + (await GetAsync("/api/read", login)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + /// + /// Directory-membership changes are invisible to the ConfigDb-only re-check, so the sliding cookie must + /// not outlive the absolute session lifetime however often it is used. + /// + [Fact] + public async Task Session_past_its_absolute_lifetime_is_rejected_even_when_in_constant_use() + { + GrantDesigner(); + var login = await LoginAsync("editor"); + + // Positive control: an active session still works just inside the cap, request after request. + var cookies = login; + for (var i = 0; i < MaxSessionMinutes / IntervalMinutes - 1; i++) + { + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes)); + var r = await GetAsync("/api/editor", cookies); + r.StatusCode.ShouldBe(HttpStatusCode.OK); + if (r.Headers.Contains("Set-Cookie")) cookies = r; // follow the sliding re-issue + } + + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1)); + (await GetAsync("/api/editor", cookies)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + /// A role-map fault is not a sign-out: the session survives (and is retried); the absolute cap still bounds it. + [Fact] + public async Task Role_map_outage_keeps_the_session_instead_of_signing_everyone_out() + { + GrantDesigner(); + var login = await LoginAsync("editor"); + + _mappings.Throws = true; + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1)); + (await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.OK); + + // Recovery: the next request re-checks and applies the change the outage deferred. + _mappings.Throws = false; + _mappings.Rows.Clear(); + (await GetAsync("/api/editor", login)).StatusCode.ShouldBe(HttpStatusCode.Forbidden); + } + + /// A cookie minted before this change cannot be re-validated, so it is refused (one re-login). + [Fact] + public async Task Cookie_without_session_state_is_rejected() + { + var signIn = await _server.CreateClient().PostAsync("/test/signin-unstamped", null, Ct); + signIn.StatusCode.ShouldBe(HttpStatusCode.NoContent); + + (await GetAsync("/api/read", signIn)).StatusCode.ShouldBe(HttpStatusCode.Unauthorized); + } + + /// The login stamps the re-validation state, including a sign-in-granted (DevStub) role. + [Fact] + public async Task Sign_in_granted_role_survives_revalidation_when_the_mapper_returns_nothing() + { + var login = await LoginAsync("dev"); // StubLdap: group "dev" (unmapped) + pre-resolved Administrator + _clock.Advance(TimeSpan.FromMinutes(IntervalMinutes + 1)); + + var roles = await GetAsync("/api/roles", login); + roles.StatusCode.ShouldBe(HttpStatusCode.OK); + (await roles.Content.ReadFromJsonAsync(Ct)).ShouldBe(["Administrator"]); + } + + // ---- circuit provider ---------------------------------------------------------------- + + private sealed class Probe( + AdminSessionRevalidator revalidator, bool disableLogin) + : RevalidatingAdminAuthenticationStateProvider( + NullLoggerFactory.Instance, revalidator, Options.Create(new AuthDisableLoginOptions { DisableLogin = disableLogin })) + { + public Task Validate(ClaimsPrincipal user) => + ValidateAuthenticationStateAsync(new AuthenticationState(user), CancellationToken.None); + } + + private ClaimsPrincipal SignedInPrincipal(params string[] groups) + { + var claims = new List { new(ZbClaimTypes.Name, "u"), new(ZbClaimTypes.Username, "u") }; + var roles = new StubMappingsMapper(_mappings, ["ReadOnly", .. groups]); + foreach (var r in roles.Roles) claims.Add(new Claim(ZbClaimTypes.Role, r)); + AdminSessionClaims.Stamp(claims, ["ReadOnly", .. groups], [], _clock.GetUtcNow()); + return new ClaimsPrincipal(new ClaimsIdentity(claims, "Cookies")); + } + + private Probe NewProbe(bool disableLogin = false) => + new(_host.Services.GetRequiredService(), disableLogin); + + /// An open circuit loses the elevated authority once the grant is gone; unchanged circuits stay valid. + [Fact] + public async Task Circuit_state_is_invalidated_when_roles_changed_and_stays_valid_otherwise() + { + GrantDesigner(); + var principal = SignedInPrincipal("Editors"); // Viewer + Designer + var probe = NewProbe(); + + (await probe.Validate(principal)).ShouldBeTrue(); // positive control: unchanged + + _mappings.Rows.Clear(); + (await probe.Validate(principal)).ShouldBeFalse(); // demoted -> the framework swaps in anonymous + } + + /// A circuit whose user vanished entirely is invalid; an anonymous circuit has nothing to revoke. + [Fact] + public async Task Circuit_state_is_invalid_for_a_vanished_account_and_trivially_valid_for_anonymous() + { + GrantDesigner(); + var principal = SignedInPrincipal(); // baseline Viewer only ... + var probe = NewProbe(); + (await probe.Validate(principal)).ShouldBeTrue(); + + _clock.Advance(TimeSpan.FromMinutes(MaxSessionMinutes + 1)); // ... past the absolute lifetime + (await probe.Validate(principal)).ShouldBeFalse(); + + (await probe.Validate(new ClaimsPrincipal(new ClaimsIdentity()))).ShouldBeTrue(); + } + + /// Dev rig (Security:Auth:DisableLogin=true): the auto-login principal carries no stamps and must stay valid. + [Fact] + public async Task Circuit_validation_is_a_noop_when_login_is_disabled() + { + var autoLogin = new ClaimsPrincipal(new ClaimsIdentity( + [new Claim(ZbClaimTypes.Name, "multi-role-test"), new Claim(ZbClaimTypes.Role, "Administrator")], "Cookies")); + + (await NewProbe(disableLogin: true).Validate(autoLogin)).ShouldBeTrue(); + // Positive control: the same stamp-less principal is refused when login is enabled. + (await NewProbe(disableLogin: false).Validate(autoLogin)).ShouldBeFalse(); + } + + /// The revalidating provider is the one the AdminUI circuit resolves (not the framework default). + [Fact] + public void Authentication_state_provider_resolves_to_the_revalidating_provider() + { + using var scope = _host.Services.CreateScope(); + scope.ServiceProvider.GetRequiredService() + .ShouldBeOfType(); + } + + /// + /// Registration order must not matter: the Host calls AddOtOpcUaAuth BEFORE AddAdminUI's + /// AddRazorComponents().AddInteractiveServerComponents(), whose framework default must not displace + /// the revalidating provider (and the circuit host-environment seam must resolve to the same instance). + /// + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Revalidating_provider_wins_regardless_of_razor_components_registration_order(bool authFirst) + { + var services = new ServiceCollection(); + services.AddLogging(); + services.AddDbContext(o => o.UseInMemoryDatabase($"order-{Guid.NewGuid():N}")); + var configuration = new ConfigurationBuilder().Build(); + if (authFirst) + { + services.AddOtOpcUaAuth(configuration); + services.AddRazorComponents().AddInteractiveServerComponents(); + } + else + { + services.AddRazorComponents().AddInteractiveServerComponents(); + services.AddOtOpcUaAuth(configuration); + } + using var provider = services.BuildServiceProvider(); + using var scope = provider.CreateScope(); + + var asp = scope.ServiceProvider.GetRequiredService(); + asp.ShouldBeOfType(); + // The circuit factory seeds the principal by casting the resolved provider to this seam. + asp.ShouldBeAssignableTo(); + } + + // ---- DisableLogin host ----------------------------------------------------------------- + + /// With DisableLogin the auto-login handler replaces the cookie handler: no stamps, no re-validation, still authenticated. + [Fact] + public async Task Disable_login_host_stays_authenticated_with_no_session_state() + { + var dbName = $"session-reval-dl-{Guid.NewGuid():N}"; + using var host = new HostBuilder() + .ConfigureWebHost(web => + { + web.UseTestServer(); + web.ConfigureServices(services => + { + services.AddDbContext(o => o.UseInMemoryDatabase(dbName)); + services.AddRouting(); + var configuration = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary + { + ["Security:Auth:DisableLogin"] = "true", + }).Build(); + services.AddOtOpcUaAuth(configuration); + services.AddSingleton(_mappings); + }); + web.Configure(app => + { + app.UseRouting(); + app.UseAuthentication(); + app.UseAuthorization(); + app.UseEndpoints(e => e.MapGet("/api/editor", () => Results.Ok("editor")) + .RequireAuthorization(AdminUiPolicies.ConfigEditor)); + }); + }).Build(); + await host.StartAsync(Ct); + var client = host.GetTestServer().CreateClient(); + + (await client.GetAsync("/api/editor", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK); + // Every request is auto-authenticated with the full dev role set; the cookie handler (and with it + // OnValidatePrincipal) is not in play, so there is no session state to expire. + (await client.GetAsync("/api/editor", Ct)).StatusCode.ShouldBe(HttpStatusCode.OK); + } + + // ---- stubs ----------------------------------------------------------------------------- + + private sealed class TestClock : TimeProvider + { + private DateTimeOffset _now = new(2026, 12, 3, 9, 0, 0, TimeSpan.Zero); + public override DateTimeOffset GetUtcNow() => _now; + public void Advance(TimeSpan by) => _now += by; + } + + private sealed class StubLdap : ILdapAuthService + { + public Task AuthenticateAsync(string username, string password, CancellationToken ct = default) => + Task.FromResult(username switch + { + "editor" => new LdapAuthResult(true, "Ed", username, ["ReadOnly", "Editors"], [], null), + "editor-only" => new LdapAuthResult(true, "Ed", username, ["Editors"], [], null), + "dev" => new LdapAuthResult(true, "Dev", username, ["dev"], ["Administrator"], null), + _ => new LdapAuthResult(false, null, username, [], [], "no"), + }); + } + + private sealed class StubMappings : ILdapGroupRoleMappingService + { + public List Rows { get; } = []; + public bool Throws { get; set; } + + public Task> GetByGroupsAsync( + IEnumerable ldapGroups, CancellationToken cancellationToken) + { + if (Throws) throw new InvalidOperationException("simulated DB outage"); + var groups = new HashSet(ldapGroups, StringComparer.OrdinalIgnoreCase); + IReadOnlyList matched = [.. Rows.Where(r => groups.Contains(r.LdapGroup))]; + return Task.FromResult(matched); + } + + public Task> ListAllAsync(CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task CreateAsync(LdapGroupRoleMapping row, CancellationToken cancellationToken) => + throw new NotSupportedException(); + + public Task DeleteAsync(Guid id, CancellationToken cancellationToken) => throw new NotSupportedException(); + } + + /// Resolves the roles a sign-in would have granted (baseline ReadOnly -> Viewer + the stub's DB rows). + private sealed class StubMappingsMapper + { + public IReadOnlyList Roles { get; } + + public StubMappingsMapper(StubMappings mappings, IEnumerable groups) + { + var list = groups.ToList(); + var roles = new HashSet(StringComparer.OrdinalIgnoreCase); + if (list.Contains("ReadOnly")) roles.Add("Viewer"); + foreach (var row in mappings.Rows.Where(r => list.Contains(r.LdapGroup))) + roles.Add(row.Role.ToString()); + Roles = [.. roles]; + } + } +}