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
This commit is contained in:
@@ -20,6 +20,21 @@ public sealed class OtOpcUaCookieOptions
|
||||
/// <summary>Idle sliding-window length in minutes (default 30).</summary>
|
||||
public int ExpiryMinutes { get; set; } = 30;
|
||||
|
||||
/// <summary>
|
||||
/// How often (minutes) a session's roles are re-resolved from the current group→role grants
|
||||
/// (<c>GroupToRole</c> + <c>LdapGroupRoleMapping</c>) — 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.
|
||||
/// </summary>
|
||||
public int RevalidateIntervalMinutes { get; set; } = 5;
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public int MaxSessionMinutes { get; set; } = 480;
|
||||
|
||||
/// <summary>
|
||||
/// Require HTTPS for the auth cookie. Default <c>true</c>: cookie is marked
|
||||
/// <c>SecurePolicy = Always</c>. Set to <c>false</c> ONLY for local dev stacks running
|
||||
|
||||
@@ -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>() ?? TimeProvider.System;
|
||||
AdminSessionClaims.Stamp(claims, result.Groups, result.Roles, time.GetUtcNow());
|
||||
|
||||
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
var principal = new ClaimsPrincipal(identity);
|
||||
|
||||
@@ -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;
|
||||
/// </summary>
|
||||
public static class ServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Cookie <c>OnValidatePrincipal</c> (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).
|
||||
/// </summary>
|
||||
/// <param name="context">The cookie validation context.</param>
|
||||
internal static async Task ValidateSessionAsync(CookieValidatePrincipalContext context)
|
||||
{
|
||||
if (context.Principal is null) return;
|
||||
var revalidator = context.HttpContext.RequestServices.GetRequiredService<AdminSessionRevalidator>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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<IGroupRoleMapper<string>, 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<AdminSessionRevalidator>();
|
||||
services.AddScoped<AuthenticationStateProvider, RevalidatingAdminAuthenticationStateProvider>();
|
||||
|
||||
services.AddDataProtection()
|
||||
.PersistKeysToDbContext<OtOpcUaConfigDbContext>()
|
||||
.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;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
using System.Globalization;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Security.Session;
|
||||
|
||||
/// <summary>
|
||||
/// The claims <c>/auth/login</c> 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 <c>IGroupRoleMapper<string></c> against the CURRENT appsettings + DB grants), the
|
||||
/// roles the sign-in pre-resolved outside the mapper (the DevStub grant), and two timestamps.
|
||||
/// </summary>
|
||||
public static class AdminSessionClaims
|
||||
{
|
||||
/// <summary>One claim per LDAP group the user held at sign-in.</summary>
|
||||
public const string Group = "otopcua:group";
|
||||
|
||||
/// <summary>One claim per role the sign-in granted outside the group mapper (DevStub's Administrator).</summary>
|
||||
public const string PreResolvedRole = "otopcua:preresolved-role";
|
||||
|
||||
/// <summary>Unix seconds of the interactive sign-in; the absolute session lifetime is measured from it.</summary>
|
||||
public const string AuthTime = "otopcua:auth-time";
|
||||
|
||||
/// <summary>Unix seconds of the last successful role re-validation (or the sign-in).</summary>
|
||||
public const string ValidatedAt = "otopcua:validated-at";
|
||||
|
||||
/// <summary>Formats a timestamp as the unix-seconds claim value.</summary>
|
||||
/// <param name="at">The instant.</param>
|
||||
public static string Format(DateTimeOffset at) =>
|
||||
at.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
/// <summary>Parses a unix-seconds claim value; <see langword="null"/> when absent or malformed.</summary>
|
||||
/// <param name="value">The claim value.</param>
|
||||
public static DateTimeOffset? Parse(string? value) =>
|
||||
long.TryParse(value, NumberStyles.None, CultureInfo.InvariantCulture, out var seconds)
|
||||
? DateTimeOffset.FromUnixTimeSeconds(seconds)
|
||||
: null;
|
||||
|
||||
/// <summary>Appends the session-state claims to a sign-in claim list.</summary>
|
||||
/// <param name="claims">The claim list being built for the new principal.</param>
|
||||
/// <param name="groups">The LDAP groups the directory returned.</param>
|
||||
/// <param name="preResolvedRoles">Roles granted by the sign-in itself, not by the mapper.</param>
|
||||
/// <param name="now">The sign-in instant.</param>
|
||||
public static void Stamp(
|
||||
ICollection<Claim> claims,
|
||||
IEnumerable<string> groups,
|
||||
IEnumerable<string> 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)));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Outcome of <see cref="AdminSessionRevalidator.RevalidateAsync"/>.</summary>
|
||||
public enum SessionCheck
|
||||
{
|
||||
/// <summary>The session is current: nothing to do (inside the interval, or the check could not run).</summary>
|
||||
Valid,
|
||||
|
||||
/// <summary>The roles were re-resolved; <see cref="SessionRevalidation.Principal"/> carries the refreshed principal.</summary>
|
||||
Renewed,
|
||||
|
||||
/// <summary>The session must end: the account no longer maps to any role, or the session is stale/foreign.</summary>
|
||||
Rejected,
|
||||
}
|
||||
|
||||
/// <summary>Result of a session re-validation.</summary>
|
||||
/// <param name="Outcome">What to do with the session.</param>
|
||||
/// <param name="Principal">The refreshed principal when <paramref name="Outcome"/> is <see cref="SessionCheck.Renewed"/>.</param>
|
||||
/// <param name="RolesChanged">True when the re-resolved role SET differs from the one in the presented principal.</param>
|
||||
/// <param name="Reason">Why the session was rejected (for logs).</param>
|
||||
public sealed record SessionRevalidation(
|
||||
SessionCheck Outcome,
|
||||
ClaimsPrincipal? Principal = null,
|
||||
bool RolesChanged = false,
|
||||
string? Reason = null);
|
||||
|
||||
/// <summary>
|
||||
/// 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 <c>/auth/login</c>, so a user removed from an admin group or
|
||||
/// whose <c>/role-grants</c> row was deleted kept every role for as long as the cookie slid or a Blazor
|
||||
/// circuit stayed open.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>No LDAP traffic.</b> The re-check re-runs the stored sign-in groups through
|
||||
/// <c>IGroupRoleMapper<string></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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Fail-soft on a mapper fault.</b> 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.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class AdminSessionRevalidator
|
||||
{
|
||||
private readonly IServiceScopeFactory _scopes;
|
||||
private readonly IOptionsMonitor<OtOpcUaCookieOptions> _options;
|
||||
private readonly TimeProvider _time;
|
||||
private readonly ILogger<AdminSessionRevalidator> _logger;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="AdminSessionRevalidator"/> class.</summary>
|
||||
/// <param name="scopes">Creates the scope the (scoped, DbContext-backed) group mapper is resolved in.</param>
|
||||
/// <param name="options">The cookie / session options.</param>
|
||||
/// <param name="time">The clock.</param>
|
||||
/// <param name="logger">The logger.</param>
|
||||
public AdminSessionRevalidator(
|
||||
IServiceScopeFactory scopes,
|
||||
IOptionsMonitor<OtOpcUaCookieOptions> options,
|
||||
TimeProvider time,
|
||||
ILogger<AdminSessionRevalidator> logger)
|
||||
{
|
||||
_scopes = scopes;
|
||||
_options = options;
|
||||
_time = time;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>The configured re-validation interval (never below one minute).</summary>
|
||||
public TimeSpan Interval => TimeSpan.FromMinutes(Math.Max(1, _options.CurrentValue.RevalidateIntervalMinutes));
|
||||
|
||||
/// <summary>Re-validates <paramref name="principal"/>.</summary>
|
||||
/// <param name="principal">The principal from the cookie (or a circuit's captured authentication state).</param>
|
||||
/// <param name="force">
|
||||
/// True to re-check regardless of <see cref="AdminSessionClaims.ValidatedAt"/> — a circuit holds one
|
||||
/// principal for its whole life, so its stamp is always old and the circuit paces itself.
|
||||
/// </param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
public async Task<SessionRevalidation> RevalidateAsync(
|
||||
ClaimsPrincipal principal, bool force, CancellationToken ct)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(principal);
|
||||
var user = principal.FindFirst(ZbClaimTypes.Username)?.Value ?? principal.Identity?.Name ?? "<unknown>";
|
||||
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<string> mapped;
|
||||
try
|
||||
{
|
||||
await using var scope = _scopes.CreateAsyncScope();
|
||||
var mapper = scope.ServiceProvider.GetRequiredService<IGroupRoleMapper<string>>();
|
||||
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<string>(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);
|
||||
}
|
||||
|
||||
/// <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)
|
||||
{
|
||||
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));
|
||||
}
|
||||
}
|
||||
+55
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Authentication-state provider for AdminUI Blazor circuits that re-checks the circuit's principal on
|
||||
/// <see cref="OtOpcUaCookieOptions.RevalidateIntervalMinutes"/> (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.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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
|
||||
/// <c>AuthorizeView</c> / policy check fails closed. A page reload picks up the cookie the HTTP
|
||||
/// pipeline refreshed (or sends the user to <c>/login</c>). With <c>Security:Auth:DisableLogin=true</c>
|
||||
/// the principal is the dev auto-login user, which has no session-state claims, so the check is skipped.
|
||||
/// </remarks>
|
||||
public class RevalidatingAdminAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider
|
||||
{
|
||||
private readonly AdminSessionRevalidator _revalidator;
|
||||
private readonly bool _disableLogin;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="RevalidatingAdminAuthenticationStateProvider"/> class.</summary>
|
||||
/// <param name="loggerFactory">The logger factory.</param>
|
||||
/// <param name="revalidator">The shared session re-validator.</param>
|
||||
/// <param name="disableLogin">The dev disable-login options.</param>
|
||||
public RevalidatingAdminAuthenticationStateProvider(
|
||||
ILoggerFactory loggerFactory,
|
||||
AdminSessionRevalidator revalidator,
|
||||
IOptions<AuthDisableLoginOptions> disableLogin)
|
||||
: base(loggerFactory)
|
||||
{
|
||||
_revalidator = revalidator;
|
||||
_disableLogin = disableLogin.Value.DisableLogin;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override TimeSpan RevalidationInterval => _revalidator.Interval;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task<bool> 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user