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:
Joseph Doherty
2026-12-03 09:59:08 -05:00
parent 835ed0bd04
commit 152a12cea9
9 changed files with 376 additions and 10 deletions
+1 -1
View File
@@ -178,7 +178,7 @@ Gateway gRPC clients authenticate with an API key in metadata: `authorization: B
Session RPCs are **owner-scoped**: the API key that opened a session is recorded on the session, and every `StreamEvents` attach/reattach, `Invoke` (every command kind, `DrainEvents` included) and `CloseSession` is rejected with `PermissionDenied` unless the caller's key id matches the owner (strict ordinal compare, **no `admin` override** — operators close or kill other keys' sessions from the dashboard, which calls `ISessionManager` directly). Possessing the matching scope and knowing a session id is not sufficient — this closes the reconnect/fan-out trust boundary (detach-grace and replay retention are on by default) so an `events:read`-scoped key cannot attach to, drain, write through or close another key's session.
Dashboard auth is LDAP-backed (separate from the gRPC API-key model). `/login` binds against `MxGateway:Ldap` and maps the user's LDAP groups to `Admin` or `Viewer` via `MxGateway:Dashboard:GroupToRole`, then issues an HTTP-only secure cookie named `__Host-MxGatewayDashboard` when `Dashboard:RequireHttpsCookie` is true (default) and no `Dashboard:CookieName` override is set, else the plain `MxGatewayDashboard` (the `__Host-` prefix requires a Secure cookie). SignalR hubs at `/hubs/{snapshot,alarms,events}` accept either the cookie or a 5-minute bearer minted at `/hubs/token`; `/hubs/alarms` and the `/alarms` page additionally require a **real authenticated dashboard role** (`MxGateway.Dashboard.Alarms`, a requirement type the environment-bypass handler does not handle), because the alarm feed is gateway-central with no per-session provenance and so cannot be tag-scoped — its metadata stays galaxy-wide for authenticated Viewers, but anonymous localhost and `Authentication:Mode=Disabled` do not receive it at all. Dashboard event visibility is **tag-scoped per session** (`IDashboardSessionAcl`, gating both the events hub and the session-details page's in-process subscribe): an Administrator sees every session, while any other caller sees a session only when its tags — inherited from the owning API key's `apikey --dashboard-tags`, never from the client's request — intersect the tags their LDAP groups grant via `Dashboard:GroupToTag`. That grant is **re-resolved from the caller's LDAP group claims against current options on every subscribe** (not read from the tag claims stamped at login, which would outlive a config-revoked grant for the cookie's 8-hour sliding life); login-stamped tag claims are the fallback only for a principal carrying no group claims — i.e. the hub-token principal, whose grant the mint already re-resolved. Untagged sessions follow `Dashboard:UntaggedSessionVisibility` (default `AdminOnly`), and a principal with neither claim kind (anonymous localhost included) is an empty-grant Viewer. `Dashboard:AllowAnonymousLocalhost` (default `true`) grants **read-only** loopback access — it satisfies the Viewer requirement but never the Admin-only requirement, so anonymous localhost can view the dashboard but not reach API-key CRUD, session Close/Kill, or the alarm feed (`Authentication:Mode=Disabled` is scoped the same way). `Dashboard:DisableLogin` (default `false`) auto-authenticates every dashboard request — including remote browsers — as `Dashboard:AutoLoginUser` (default `multi-role`) with both Admin and Viewer roles; dev/test only, never enable in production.
Dashboard auth is LDAP-backed (separate from the gRPC API-key model). `/login` binds against `MxGateway:Ldap` and maps the user's LDAP groups to `Admin` or `Viewer` via `MxGateway:Dashboard:GroupToRole`, then issues an HTTP-only secure cookie named `__Host-MxGatewayDashboard` when `Dashboard:RequireHttpsCookie` is true (default) and no `Dashboard:CookieName` override is set, else the plain `MxGatewayDashboard` (the `__Host-` prefix requires a Secure cookie). SignalR hubs at `/hubs/{snapshot,alarms,events}` accept either the cookie or a 5-minute bearer minted at `/hubs/token`, and close a connection when its ticket expires (`CloseOnAuthenticationExpiration`); Blazor circuits are re-validated every minute (`DashboardRevalidatingAuthenticationStateProvider`: signed out past the cookie's 8-hour idle life or when a held role is no longer granted by `GroupToRole`); `/hubs/alarms` and the `/alarms` page additionally require a **real authenticated dashboard role** (`MxGateway.Dashboard.Alarms`, a requirement type the environment-bypass handler does not handle), because the alarm feed is gateway-central with no per-session provenance and so cannot be tag-scoped — its metadata stays galaxy-wide for authenticated Viewers, but anonymous localhost and `Authentication:Mode=Disabled` do not receive it at all. Dashboard event visibility is **tag-scoped per session** (`IDashboardSessionAcl`, gating both the events hub and the session-details page's in-process subscribe): an Administrator sees every session, while any other caller sees a session only when its tags — inherited from the owning API key's `apikey --dashboard-tags`, never from the client's request — intersect the tags their LDAP groups grant via `Dashboard:GroupToTag`. That grant is **re-resolved from the caller's LDAP group claims against current options on every subscribe** (not read from the tag claims stamped at login, which would outlive a config-revoked grant for the cookie's 8-hour sliding life); login-stamped tag claims are the fallback only for a principal carrying no group claims — i.e. the hub-token principal, whose grant the mint already re-resolved. Untagged sessions follow `Dashboard:UntaggedSessionVisibility` (default `AdminOnly`), and a principal with neither claim kind (anonymous localhost included) is an empty-grant Viewer. `Dashboard:AllowAnonymousLocalhost` (default `true`) grants **read-only** loopback access — it satisfies the Viewer requirement but never the Admin-only requirement, so anonymous localhost can view the dashboard but not reach API-key CRUD, session Close/Kill, or the alarm feed (`Authentication:Mode=Disabled` is scoped the same way). `Dashboard:DisableLogin` (default `false`) auto-authenticates every dashboard request — including remote browsers — as `Dashboard:AutoLoginUser` (default `multi-role`) with both Admin and Viewer roles; dev/test only, never enable in production.
## Process / Platform Notes
+22 -1
View File
@@ -976,15 +976,36 @@ dashboard mints short-lived bearer tokens for the connection:
it must never be request-logged (see the remarks on
`HubTokenAuthenticationHandler`).
4. `HubTokenAuthenticationHandler` validates the protected payload and
rebuilds the `ClaimsPrincipal` with the carried roles.
rebuilds the `ClaimsPrincipal` with the carried roles, and stamps the
token's expiry on the authentication ticket (`ExpiresUtc`).
5. The hubs' `[Authorize(Policy = HubClientsPolicy)]` accepts the resulting
identity.
6. Every hub is mapped with `CloseOnAuthenticationExpiration`, so SignalR closes
the connection when that ticket expires (DSH-006). Before this, 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, and each later
`SubscribeSession` on it was decided from those frozen claims. A
cookie-authenticated hub connection closes at the cookie ticket's expiry the
same way. The client reconnects with a freshly minted token.
There is no in-repo hub client: the helper that once wrapped `HubConnectionBuilder`
for a circuit was deleted when the pages moved to the in-process seams. An external
client re-fetches `/hubs/token` on every (re)connect itself, which is what makes the
short 5-minute lifetime transparent.
Blazor circuits have the same capture-once problem — a circuit takes its principal
from the HTTP request that started it and an open tab sends no further requests — so
the dashboard replaces the default `ServerAuthenticationStateProvider` with
`DashboardRevalidatingAuthenticationStateProvider` (DSH-006). Every minute it signs
the circuit out (anonymous state) when the circuit is older than the cookie's 8-hour
idle lifetime, or when the principal holds a role that its LDAP group claims no
longer map to under the current `Dashboard:GroupToRole`. Pages under
`AuthorizeRouteView` then 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 there (no server-side
session, no password to re-bind with); they take effect at the age limit or on
reconnect. The `DisableLogin` dev bypass is never signed out.
Caveat — logout does not revoke outstanding tokens. Logout clears the dashboard
cookie, but hub bearer tokens are self-contained, data-protection-encrypted, and
carry no server-side revocation state (no jti denylist). A token captured before
@@ -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";
@@ -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,
@@ -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)
@@ -0,0 +1,189 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Time.Testing;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Dashboard;
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
/// <summary>
/// DSH-006: authentication lifetimes are enforced on live dashboard connections, not only at the
/// handshake — hub connections close when their ticket expires, and Blazor circuits are signed out
/// when their sign-in lapses or a role grant is withdrawn.
/// </summary>
public sealed class DashboardAuthLifetimeTests
{
private const string AdminGroup = "GwAdmin";
private const string ViewerGroup = "GwViewer";
/// <summary>
/// The hub-token ticket carries the token's expiry, which is what SignalR's
/// CloseOnAuthenticationExpiration closes the connection on.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task HubTokenTicket_CarriesTheTokenExpiry()
{
HubTokenService tokens = new(
new EphemeralDataProtectionProvider(),
Options.Create(new GatewayOptions()));
string token = tokens.Issue(Principal("alice", DashboardRoles.Viewer), TimeSpan.FromMinutes(5));
DefaultHttpContext httpContext = new();
httpContext.Request.Headers.Authorization = $"Bearer {token}";
HubTokenAuthenticationHandler handler = new(
new StaticOptionsMonitor<AuthenticationSchemeOptions>(new AuthenticationSchemeOptions()),
NullLoggerFactory.Instance,
UrlEncoder.Default,
tokens);
await handler.InitializeAsync(
new AuthenticationScheme(
DashboardAuthenticationDefaults.HubAuthenticationScheme,
displayName: null,
typeof(HubTokenAuthenticationHandler)),
httpContext);
AuthenticateResult result = await handler.AuthenticateAsync();
Assert.True(result.Succeeded);
DateTimeOffset? expires = result.Properties?.ExpiresUtc;
Assert.NotNull(expires);
Assert.InRange(
expires.Value,
DateTimeOffset.UtcNow.AddMinutes(4),
DateTimeOffset.UtcNow.AddMinutes(6));
}
/// <summary>
/// Every dashboard hub closes a connection whose authentication has expired. The dispatcher
/// options ride on each hub's negotiate endpoint.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EveryHub_ClosesOnAuthenticationExpiration()
{
await using WebApplication app = TestGatewayHost.Build([]);
List<RouteEndpoint> hubEndpoints = ((IEndpointRouteBuilder)app).DataSources
.SelectMany(source => source.Endpoints)
.OfType<RouteEndpoint>()
.Where(endpoint => endpoint.RoutePattern.RawText
is "/hubs/snapshot/negotiate" or "/hubs/alarms/negotiate" or "/hubs/events/negotiate")
.ToList();
Assert.Equal(3, hubEndpoints.Count);
Assert.All(
hubEndpoints,
endpoint => Assert.True(endpoint.Metadata.GetMetadata<HttpConnectionDispatcherOptions>()?.CloseOnAuthenticationExpiration));
}
/// <summary>Circuits get the revalidating provider, not the capture-once default.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Circuits_UseTheRevalidatingAuthenticationStateProvider()
{
await using WebApplication app = TestGatewayHost.Build([]);
await using AsyncServiceScope scope = app.Services.CreateAsyncScope();
Assert.IsType<DashboardRevalidatingAuthenticationStateProvider>(
scope.ServiceProvider.GetRequiredService<AuthenticationStateProvider>());
}
/// <summary>An Administrator whose admin group is withdrawn from GroupToRole is signed out.</summary>
[Fact]
public void Revalidation_WhenAdminGrantWithdrawn_SignsOut()
{
GatewayOptions options = OptionsWithRoles(includeAdmin: true);
StaticOptionsMonitor<GatewayOptions> monitor = new(options);
FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch);
using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock);
ClaimsPrincipal admin = Principal("alice", DashboardRoles.Admin, groups: [AdminGroup]);
Assert.True(provider.IsStillValid(admin));
monitor.CurrentValue = OptionsWithRoles(includeAdmin: false);
Assert.False(provider.IsStillValid(admin));
}
/// <summary>A circuit older than the cookie's idle lifetime is signed out.</summary>
[Fact]
public void Revalidation_PastCookieIdleTimeout_SignsOut()
{
StaticOptionsMonitor<GatewayOptions> monitor = new(OptionsWithRoles(includeAdmin: true));
FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch);
using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock);
ClaimsPrincipal viewer = Principal("bob", DashboardRoles.Viewer, groups: [ViewerGroup]);
clock.Advance(DashboardAuthenticationDefaults.CookieIdleTimeout - TimeSpan.FromMinutes(1));
Assert.True(provider.IsStillValid(viewer));
clock.Advance(TimeSpan.FromMinutes(1));
Assert.False(provider.IsStillValid(viewer));
}
/// <summary>
/// Principals with nothing to revoke stay as they are: anonymous localhost, and the
/// DisableLogin dev bypass however old the circuit.
/// </summary>
[Fact]
public void Revalidation_AnonymousAndDisableLogin_AreNeverSignedOut()
{
StaticOptionsMonitor<GatewayOptions> monitor = new(new GatewayOptions
{
Dashboard = new DashboardOptions { DisableLogin = true },
});
FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch);
using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock);
clock.Advance(DashboardAuthenticationDefaults.CookieIdleTimeout * 2);
Assert.True(provider.IsStillValid(new ClaimsPrincipal(new ClaimsIdentity())));
Assert.True(provider.IsStillValid(Principal("multi-role", DashboardRoles.Admin)));
}
private static GatewayOptions OptionsWithRoles(bool includeAdmin)
{
Dictionary<string, string> groupToRole = new(StringComparer.OrdinalIgnoreCase)
{
[ViewerGroup] = DashboardRoles.Viewer,
};
if (includeAdmin)
{
groupToRole[AdminGroup] = DashboardRoles.Admin;
}
return new GatewayOptions { Dashboard = new DashboardOptions { GroupToRole = groupToRole } };
}
private static ClaimsPrincipal Principal(string name, string role, string[]? groups = null)
{
List<Claim> claims =
[
new(ClaimTypes.Name, name),
new(ClaimTypes.NameIdentifier, name),
new(ClaimTypes.Role, role),
];
claims.AddRange((groups ?? []).Select(group => new Claim(DashboardAuthenticationDefaults.LdapGroupClaimType, group)));
return new ClaimsPrincipal(new ClaimsIdentity(claims, "Test", ClaimTypes.Name, ClaimTypes.Role));
}
private sealed class StaticOptionsMonitor<T>(T value) : IOptionsMonitor<T>
{
public T CurrentValue { get; set; } = value;
public T Get(string? name) => CurrentValue;
public IDisposable? OnChange(Action<T, string?> listener) => null;
}
}