fix(dashboard): enforce auth lifetimes on live hub connections and circuits (DSH-006)
Hub tokens and cookies bounded only the handshake: an open hub socket kept its connect-time roles and tag grants indefinitely, and a Blazor circuit never revisited its sign-in. The hub-token ticket now carries the token expiry and the hubs are mapped with CloseOnAuthenticationExpiration. Circuits use DashboardRevalidatingAuthenticationStateProvider, which signs a circuit out past the cookie's 8-hour idle lifetime or when a role it holds is no longer granted by GroupToRole. LDAP membership changes and sign-out in another tab are still only picked up at the age limit or on reconnect (documented).
This commit is contained in:
@@ -45,6 +45,13 @@ public static class DashboardAuthenticationDefaults
|
||||
/// </summary>
|
||||
public const string AlarmsPolicy = "MxGateway.Dashboard.Alarms";
|
||||
|
||||
/// <summary>
|
||||
/// Sliding idle lifetime of the dashboard login cookie. Also the longest a Blazor circuit keeps
|
||||
/// its sign-in: the circuit issues no HTTP requests, so it cannot renew the cookie, and
|
||||
/// <see cref="DashboardRevalidatingAuthenticationStateProvider"/> signs it out at this age.
|
||||
/// </summary>
|
||||
public static readonly TimeSpan CookieIdleTimeout = TimeSpan.FromHours(8);
|
||||
|
||||
public const string LdapGroupClaimType = "mxgateway:ldap_group";
|
||||
public const string KeyPrefixClaimType = "mxgateway:key_prefix";
|
||||
|
||||
|
||||
+13
-3
@@ -109,9 +109,14 @@ public static class DashboardEndpointRouteBuilderExtensions
|
||||
// events use HubClientsPolicy; AlarmsHub uses AlarmsPolicy, which additionally requires a
|
||||
// real authenticated dashboard role — see AlarmsHub for why the alarm feed is
|
||||
// gated harder than the session-scoped ones.
|
||||
endpoints.MapHub<DashboardSnapshotHub>("/hubs/snapshot");
|
||||
endpoints.MapHub<AlarmsHub>("/hubs/alarms");
|
||||
endpoints.MapHub<EventsHub>("/hubs/events");
|
||||
// CloseOnAuthenticationExpiration (DSH-006): a hub connection authenticates once, at the
|
||||
// handshake, and keeps that principal for as long as the socket stays up. Closing it when
|
||||
// the ticket expires — the hub token's 5 minutes, or the cookie ticket's expiry — makes a
|
||||
// long-lived connection re-authenticate, so a revoked role or tag grant cannot outlive it.
|
||||
// Remote clients already re-fetch /hubs/token on every (re)connect.
|
||||
endpoints.MapHub<DashboardSnapshotHub>("/hubs/snapshot", CloseOnAuthenticationExpiration);
|
||||
endpoints.MapHub<AlarmsHub>("/hubs/alarms", CloseOnAuthenticationExpiration);
|
||||
endpoints.MapHub<EventsHub>("/hubs/events", CloseOnAuthenticationExpiration);
|
||||
|
||||
// Bearer-token mint endpoint. The cookie-authenticated browser hits
|
||||
// this from JS before opening a hub connection; the hub then accepts
|
||||
@@ -140,6 +145,11 @@ public static class DashboardEndpointRouteBuilderExtensions
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
// Applied to every dashboard hub; internal so a test can assert the options each hub gets.
|
||||
internal static void CloseOnAuthenticationExpiration(
|
||||
Microsoft.AspNetCore.Http.Connections.HttpConnectionDispatcherOptions options) =>
|
||||
options.CloseOnAuthenticationExpiration = true;
|
||||
|
||||
private static async Task<IResult> PostLoginAsync(
|
||||
HttpContext httpContext,
|
||||
IAntiforgery antiforgery,
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// Re-checks a Blazor circuit's sign-in on a timer and signs the circuit out when it no longer
|
||||
/// holds (DSH-006).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A circuit captures its principal once, at circuit start, and an open tab issues no further HTTP
|
||||
/// requests, so neither cookie expiry nor a configuration change ever reached it: an Administrator
|
||||
/// tab left open could still close sessions, kill workers and manage API keys hours later. Every
|
||||
/// <see cref="RevalidationInterval"/> this provider re-evaluates two things it can know without the
|
||||
/// user's password:
|
||||
/// </para>
|
||||
/// <list type="bullet">
|
||||
/// <item><description>
|
||||
/// <b>Age.</b> A circuit older than the cookie's idle lifetime
|
||||
/// (<see cref="DashboardAuthenticationDefaults.CookieIdleTimeout"/>) is signed out; the circuit
|
||||
/// could not have renewed the cookie, so the sign-in it holds has lapsed.
|
||||
/// </description></item>
|
||||
/// <item><description>
|
||||
/// <b>Roles.</b> The principal's LDAP group claims are re-mapped through the current
|
||||
/// <c>MxGateway:Dashboard:GroupToRole</c>; if a role the principal carries is no longer granted, the
|
||||
/// circuit is signed out. This is the same re-resolution the session ACL applies to tag grants.
|
||||
/// </description></item>
|
||||
/// </list>
|
||||
/// <para>
|
||||
/// When either check fails the circuit's state becomes anonymous: pages under
|
||||
/// <c>AuthorizeRouteView</c> re-render as not authorized, and admin actions — which read the
|
||||
/// provider at action time — are refused. A change to the user's LDAP group membership, and a
|
||||
/// sign-out in another tab, are not observable here (the gateway keeps no server-side session and
|
||||
/// cannot re-bind without the password); they take effect when the circuit reaches the age limit or
|
||||
/// reconnects. The <c>Dashboard:DisableLogin</c> dev bypass and unauthenticated principals are
|
||||
/// never signed out.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class DashboardRevalidatingAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider
|
||||
{
|
||||
private readonly IOptionsMonitor<GatewayOptions> _options;
|
||||
private readonly TimeProvider _timeProvider;
|
||||
private readonly DateTimeOffset _circuitStartedAt;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="DashboardRevalidatingAuthenticationStateProvider"/> class.</summary>
|
||||
/// <param name="loggerFactory">Logger factory for the revalidation loop.</param>
|
||||
/// <param name="options">Gateway options, read fresh on every revalidation.</param>
|
||||
/// <param name="timeProvider">Clock; the system clock when not registered.</param>
|
||||
public DashboardRevalidatingAuthenticationStateProvider(
|
||||
ILoggerFactory loggerFactory,
|
||||
IOptionsMonitor<GatewayOptions> options,
|
||||
TimeProvider? timeProvider = null)
|
||||
: base(loggerFactory)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(options);
|
||||
_options = options;
|
||||
_timeProvider = timeProvider ?? TimeProvider.System;
|
||||
_circuitStartedAt = _timeProvider.GetUtcNow();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1);
|
||||
|
||||
/// <summary>Decides whether the circuit's principal is still signed in. Internal for tests.</summary>
|
||||
/// <param name="user">The circuit's current principal.</param>
|
||||
/// <returns><see langword="true"/> to keep the sign-in; <see langword="false"/> to sign out.</returns>
|
||||
internal bool IsStillValid(ClaimsPrincipal user)
|
||||
{
|
||||
if (user.Identity?.IsAuthenticated != true)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
GatewayOptions options = _options.CurrentValue;
|
||||
if (options.Dashboard.DisableLogin)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (_timeProvider.GetUtcNow() - _circuitStartedAt >= DashboardAuthenticationDefaults.CookieIdleTimeout)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
string[] groups = [.. user.FindAll(DashboardAuthenticationDefaults.LdapGroupClaimType).Select(claim => claim.Value)];
|
||||
if (groups.Length == 0)
|
||||
{
|
||||
// Nothing to re-resolve from (a principal minted without LDAP groups); the age check
|
||||
// above is the bound.
|
||||
return true;
|
||||
}
|
||||
|
||||
IReadOnlyList<string> grantedRoles = DashboardGroupRoleMapping.MapGroupsToRoles(
|
||||
groups,
|
||||
options.Dashboard.GroupToRole);
|
||||
foreach (Claim role in user.FindAll(ClaimTypes.Role))
|
||||
{
|
||||
if (!grantedRoles.Contains(role.Value, StringComparer.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<bool> ValidateAuthenticationStateAsync(
|
||||
AuthenticationState authenticationState,
|
||||
CancellationToken cancellationToken) =>
|
||||
Task.FromResult(IsStillValid(authenticationState.User));
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Server.Circuits;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection.Extensions;
|
||||
@@ -114,6 +115,10 @@ public static class DashboardServiceCollectionExtensions
|
||||
services.AddRazorComponents()
|
||||
.AddInteractiveServerComponents(circuit =>
|
||||
circuit.DisconnectedCircuitRetentionPeriod = DisconnectedCircuitRetention);
|
||||
// Registered after AddInteractiveServerComponents so it replaces the default
|
||||
// ServerAuthenticationStateProvider: a circuit's sign-in is otherwise captured once at
|
||||
// circuit start and never revisited (DSH-006).
|
||||
services.AddScoped<AuthenticationStateProvider, DashboardRevalidatingAuthenticationStateProvider>();
|
||||
services.AddSignalR();
|
||||
|
||||
// DEV/TEST ONLY. Read directly from configuration here because authentication scheme
|
||||
@@ -154,7 +159,7 @@ public static class DashboardServiceCollectionExtensions
|
||||
// ExpireTimeSpan) via the shared ZbCookieDefaults.Apply. requireHttps is set to
|
||||
// its default (true / Always) here and overridden per-environment by the
|
||||
// PostConfigure below; the 8-hour idle timeout is preserved (not the 30-min default).
|
||||
ZbCookieDefaults.Apply(cookieOptions, requireHttps: true, idleTimeout: TimeSpan.FromHours(8));
|
||||
ZbCookieDefaults.Apply(cookieOptions, requireHttps: true, idleTimeout: DashboardAuthenticationDefaults.CookieIdleTimeout);
|
||||
// Cookie name, path, and redirect paths are MxGateway-specific — set after Apply
|
||||
// so they are never overwritten by the shared helper (Apply intentionally skips name).
|
||||
// This is the canonical default; it is overridden per-environment from
|
||||
|
||||
@@ -48,14 +48,19 @@ public sealed class HubTokenAuthenticationHandler : AuthenticationHandler<Authen
|
||||
return Task.FromResult(AuthenticateResult.NoResult());
|
||||
}
|
||||
|
||||
System.Security.Claims.ClaimsPrincipal? principal = _tokens.Validate(token);
|
||||
System.Security.Claims.ClaimsPrincipal? principal = _tokens.Validate(token, out DateTimeOffset expiresUtc);
|
||||
if (principal is null)
|
||||
{
|
||||
return Task.FromResult(AuthenticateResult.Fail("Invalid or expired hub token."));
|
||||
}
|
||||
|
||||
// The ticket carries the token's expiry so the hubs, mapped with
|
||||
// CloseOnAuthenticationExpiration, close a token-authenticated connection when its token
|
||||
// lapses (DSH-006). Without it the 5-minute lifetime bounded only the handshake: an open
|
||||
// socket kept the roles and tag grants it connected with for as long as it stayed up.
|
||||
AuthenticationProperties properties = new() { ExpiresUtc = expiresUtc };
|
||||
return Task.FromResult(AuthenticateResult.Success(
|
||||
new AuthenticationTicket(principal, Scheme.Name)));
|
||||
new AuthenticationTicket(principal, properties, Scheme.Name)));
|
||||
}
|
||||
|
||||
private string? ExtractToken()
|
||||
|
||||
@@ -100,8 +100,19 @@ public sealed class HubTokenService
|
||||
/// <summary>Validates a token and returns the equivalent claims principal; null when invalid or expired.</summary>
|
||||
/// <param name="token">The token string to validate.</param>
|
||||
/// <returns>The reconstructed <see cref="ClaimsPrincipal"/>, or <see langword="null"/> when the token is missing, invalid, or expired.</returns>
|
||||
public ClaimsPrincipal? Validate(string? token)
|
||||
public ClaimsPrincipal? Validate(string? token) => Validate(token, out _);
|
||||
|
||||
/// <summary>
|
||||
/// Validates a token and returns the equivalent claims principal and the token's expiry; null
|
||||
/// when invalid or expired. The expiry is stamped on the hub authentication ticket so SignalR's
|
||||
/// <c>CloseOnAuthenticationExpiration</c> ends the connection when the token lapses (DSH-006).
|
||||
/// </summary>
|
||||
/// <param name="token">The token string to validate.</param>
|
||||
/// <param name="expiresUtc">The token's expiry when valid; otherwise <see langword="default"/>.</param>
|
||||
/// <returns>The reconstructed <see cref="ClaimsPrincipal"/>, or <see langword="null"/>.</returns>
|
||||
public ClaimsPrincipal? Validate(string? token, out DateTimeOffset expiresUtc)
|
||||
{
|
||||
expiresUtc = default;
|
||||
if (string.IsNullOrEmpty(token))
|
||||
{
|
||||
return null;
|
||||
@@ -109,7 +120,8 @@ public sealed class HubTokenService
|
||||
|
||||
try
|
||||
{
|
||||
HubTokenPayload? payload = JsonSerializer.Deserialize<HubTokenPayload>(_protector.Unprotect(token));
|
||||
HubTokenPayload? payload = JsonSerializer.Deserialize<HubTokenPayload>(
|
||||
_protector.Unprotect(token, out DateTimeOffset expiration));
|
||||
if (payload is null)
|
||||
{
|
||||
return null;
|
||||
@@ -149,6 +161,7 @@ public sealed class HubTokenService
|
||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||
ClaimTypes.Name,
|
||||
ClaimTypes.Role);
|
||||
expiresUtc = expiration;
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
catch (Exception ex) when (ex is CryptographicException or JsonException)
|
||||
|
||||
Reference in New Issue
Block a user