From 152a12cea95bcd8663428100258ef2a690d2fb25 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:59:08 -0500 Subject: [PATCH] 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). --- CLAUDE.md | 2 +- docs/GatewayDashboardDesign.md | 23 ++- .../DashboardAuthenticationDefaults.cs | 7 + ...DashboardEndpointRouteBuilderExtensions.cs | 16 +- ...RevalidatingAuthenticationStateProvider.cs | 116 +++++++++++ .../DashboardServiceCollectionExtensions.cs | 7 +- .../HubTokenAuthenticationHandler.cs | 9 +- .../Dashboard/HubTokenService.cs | 17 +- .../Dashboard/DashboardAuthLifetimeTests.cs | 189 ++++++++++++++++++ 9 files changed, 376 insertions(+), 10 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRevalidatingAuthenticationStateProvider.cs create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAuthLifetimeTests.cs diff --git a/CLAUDE.md b/CLAUDE.md index d0996ee9..d5a7f45a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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 diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md index 2740c2e7..402a50be 100644 --- a/docs/GatewayDashboardDesign.md +++ b/docs/GatewayDashboardDesign.md @@ -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 diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs index 407a1876..6fd364fa 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs @@ -45,6 +45,13 @@ public static class DashboardAuthenticationDefaults /// public const string AlarmsPolicy = "MxGateway.Dashboard.Alarms"; + /// + /// 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 + /// signs it out at this age. + /// + public static readonly TimeSpan CookieIdleTimeout = TimeSpan.FromHours(8); + public const string LdapGroupClaimType = "mxgateway:ldap_group"; public const string KeyPrefixClaimType = "mxgateway:key_prefix"; diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs index 28f83581..93389986 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs @@ -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("/hubs/snapshot"); - endpoints.MapHub("/hubs/alarms"); - endpoints.MapHub("/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("/hubs/snapshot", CloseOnAuthenticationExpiration); + endpoints.MapHub("/hubs/alarms", CloseOnAuthenticationExpiration); + endpoints.MapHub("/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 PostLoginAsync( HttpContext httpContext, IAntiforgery antiforgery, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRevalidatingAuthenticationStateProvider.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRevalidatingAuthenticationStateProvider.cs new file mode 100644 index 00000000..afeac8e8 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRevalidatingAuthenticationStateProvider.cs @@ -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; + +/// +/// Re-checks a Blazor circuit's sign-in on a timer and signs the circuit out when it no longer +/// holds (DSH-006). +/// +/// +/// +/// 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 +/// this provider re-evaluates two things it can know without the +/// user's password: +/// +/// +/// +/// Age. A circuit older than the cookie's idle lifetime +/// () is signed out; the circuit +/// could not have renewed the cookie, so the sign-in it holds has lapsed. +/// +/// +/// Roles. The principal's LDAP group claims are re-mapped through the current +/// MxGateway:Dashboard:GroupToRole; 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. +/// +/// +/// +/// When either check fails the circuit's state becomes anonymous: pages under +/// AuthorizeRouteView 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 Dashboard:DisableLogin dev bypass and unauthenticated principals are +/// never signed out. +/// +/// +public sealed class DashboardRevalidatingAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider +{ + private readonly IOptionsMonitor _options; + private readonly TimeProvider _timeProvider; + private readonly DateTimeOffset _circuitStartedAt; + + /// Initializes a new instance of the class. + /// Logger factory for the revalidation loop. + /// Gateway options, read fresh on every revalidation. + /// Clock; the system clock when not registered. + public DashboardRevalidatingAuthenticationStateProvider( + ILoggerFactory loggerFactory, + IOptionsMonitor options, + TimeProvider? timeProvider = null) + : base(loggerFactory) + { + ArgumentNullException.ThrowIfNull(options); + _options = options; + _timeProvider = timeProvider ?? TimeProvider.System; + _circuitStartedAt = _timeProvider.GetUtcNow(); + } + + /// + protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1); + + /// Decides whether the circuit's principal is still signed in. Internal for tests. + /// The circuit's current principal. + /// to keep the sign-in; to sign out. + 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 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; + } + + /// + protected override Task ValidateAuthenticationStateAsync( + AuthenticationState authenticationState, + CancellationToken cancellationToken) => + Task.FromResult(IsStillValid(authenticationState.User)); +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs index 7a9e3ec1..7ac053fb 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs @@ -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(); 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 diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs index 0a5622e0..697e4a9d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs @@ -48,14 +48,19 @@ public sealed class HubTokenAuthenticationHandler : AuthenticationHandlerValidates a token and returns the equivalent claims principal; null when invalid or expired. /// The token string to validate. /// The reconstructed , or when the token is missing, invalid, or expired. - public ClaimsPrincipal? Validate(string? token) + public ClaimsPrincipal? Validate(string? token) => Validate(token, out _); + + /// + /// 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 + /// CloseOnAuthenticationExpiration ends the connection when the token lapses (DSH-006). + /// + /// The token string to validate. + /// The token's expiry when valid; otherwise . + /// The reconstructed , or . + 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(_protector.Unprotect(token)); + HubTokenPayload? payload = JsonSerializer.Deserialize( + _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) diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAuthLifetimeTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAuthLifetimeTests.cs new file mode 100644 index 00000000..15ff4f62 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAuthLifetimeTests.cs @@ -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; + +/// +/// 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. +/// +public sealed class DashboardAuthLifetimeTests +{ + private const string AdminGroup = "GwAdmin"; + private const string ViewerGroup = "GwViewer"; + + /// + /// The hub-token ticket carries the token's expiry, which is what SignalR's + /// CloseOnAuthenticationExpiration closes the connection on. + /// + /// A task that represents the asynchronous operation. + [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(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)); + } + + /// + /// Every dashboard hub closes a connection whose authentication has expired. The dispatcher + /// options ride on each hub's negotiate endpoint. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task EveryHub_ClosesOnAuthenticationExpiration() + { + await using WebApplication app = TestGatewayHost.Build([]); + List hubEndpoints = ((IEndpointRouteBuilder)app).DataSources + .SelectMany(source => source.Endpoints) + .OfType() + .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()?.CloseOnAuthenticationExpiration)); + } + + /// Circuits get the revalidating provider, not the capture-once default. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Circuits_UseTheRevalidatingAuthenticationStateProvider() + { + await using WebApplication app = TestGatewayHost.Build([]); + await using AsyncServiceScope scope = app.Services.CreateAsyncScope(); + + Assert.IsType( + scope.ServiceProvider.GetRequiredService()); + } + + /// An Administrator whose admin group is withdrawn from GroupToRole is signed out. + [Fact] + public void Revalidation_WhenAdminGrantWithdrawn_SignsOut() + { + GatewayOptions options = OptionsWithRoles(includeAdmin: true); + StaticOptionsMonitor 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)); + } + + /// A circuit older than the cookie's idle lifetime is signed out. + [Fact] + public void Revalidation_PastCookieIdleTimeout_SignsOut() + { + StaticOptionsMonitor 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)); + } + + /// + /// Principals with nothing to revoke stay as they are: anonymous localhost, and the + /// DisableLogin dev bypass however old the circuit. + /// + [Fact] + public void Revalidation_AnonymousAndDisableLogin_AreNeverSignedOut() + { + StaticOptionsMonitor 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 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 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 value) : IOptionsMonitor + { + public T CurrentValue { get; set; } = value; + + public T Get(string? name) => CurrentValue; + + public IDisposable? OnChange(Action listener) => null; + } +}