7ec0b3594c
Follow-up to the per-session event ACL. Part of that change rode into 693a78d
via a concurrent agent's pathspec-less commit; this commit carries the review
fixes and uses pathspecs on the commit itself so it cannot recur in either
direction.
Gating the page's subscribe seam made AttachEvents asynchronous — it awaits the
authentication state — and that await is a suspension point the synchronous
version did not have. On a rapid A -> B navigation the suspended A continuation
resumes after B's parameter set has run to completion, re-reads the live
SessionId (now B's), and attaches B a SECOND time. The ACL is not bypassed —
the newer attach already cleared that same session — but the fields holding B's
first subscription are overwritten in place, so nothing ever disposes it: its
EventsHubViewerRegistry entry is never released, which keeps the mirror cloning
events for a session the page is no longer watching through that handle, and
its pump is never cancelled. A resource leak the ACL work introduced.
OnParametersSetAsync now claims a monotonic _attachGeneration synchronously,
before its first await, and AttachEventsAsync re-checks it after the await and
before any field write or Subscribe call. A stale attach returns rather than
detaching: it owns nothing, and tearing down there would destroy the newer
attach's subscription. DetachEventsAsync needs no such guard — it captures and
nulls the live fields synchronously before it awaits, so a resumed detach only
unwinds what it already took ownership of. Same dispatcher-owned identity idea
as the existing ReferenceEquals guards in PumpEventsAsync and
MarkDisconnectedAsync, one level up.
The interleaving is not expressible with the static HtmlRenderer idiom the other
page tests use: it renders a root component once and exposes no parameter-update
seam. The new test therefore adds a minimal Renderer subclass whose only job is
to mount a component and drive a second SetParametersAsync into it while the
first is parked on a gated AuthenticationStateProvider. That subclass is the
lone reason for a narrowly scoped BL0006 suppression, justified in place: it is
test-only scaffolding that never ships, and the cost of the warning coming true
is a compile break in one test file on an SDK bump. Confirmed non-vacuous by
mutation — with the generation check disabled the test goes red on the doubled
subscription and the two passing ACL tests stay green.
Two decision-table corners are now pinned rather than implied. Admin x
nonexistent session id resolves to ALLOW, because the admin bypass is evaluated
before the registry lookup; a plausible "look the session up first, it reads
better" refactor would flip it, so a test documents the ordering. EventsHub's
remarks said "an unknown session id is denied" without qualification, which read
as universal; they now state that the bypass is checked first and every rule
below it is a non-Admin rule.
HubTokenServiceTests gains the truly-absent-field case: a hand-built payload
JSON with no Tags key at all, protected through the same purpose, which is the
shape every in-flight token has across the deploy that introduces the field. The
existing test covered present-but-empty, which does not exercise the null
coalesce that stands between a legacy token and a crash on the hub auth path.
ProtectorPurpose became internal so the test cannot drift from the real purpose
string.
Tag-count cardinality cap considered and recorded as a deliberate non-goal.
Build 0 warnings / 0 errors; 48 filtered (ACL/hub/token/page) and 257 dashboard
tests pass.
157 lines
8.0 KiB
C#
157 lines
8.0 KiB
C#
using System.Security.Claims;
|
|
using System.Security.Cryptography;
|
|
using System.Text.Json;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.Extensions.Options;
|
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
|
|
|
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
|
|
|
/// <summary>
|
|
/// Mints and validates short-lived bearer tokens for SignalR hub connections.
|
|
/// The token is a data-protected JSON payload containing the user's name, role
|
|
/// claims, and granted dashboard visibility tags. Validity is enforced by the
|
|
/// data-protection time-limited protector; no separate signing keys are configured.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// This service is registered as a singleton in
|
|
/// <see cref="DashboardServiceCollectionExtensions.AddGatewayDashboard"/> and
|
|
/// is shared by two consumer scopes: the <c>/hubs/token</c> endpoint (calls
|
|
/// <see cref="Issue"/> for a cookie-authenticated caller) and
|
|
/// <c>HubTokenAuthenticationHandler</c> (transient, per-request; calls
|
|
/// <see cref="Validate"/> from the SignalR negotiate / connection path). Both
|
|
/// serve external/remote hub consumers — server-rendered dashboard pages read the
|
|
/// in-process feeds and never mint a hub token.
|
|
/// The underlying <see cref="ITimeLimitedDataProtector"/> is thread-safe, so
|
|
/// minting and validating concurrently from any number of callers is safe;
|
|
/// future maintainers should preserve the singleton lifetime to keep the
|
|
/// protector instance stable.
|
|
/// </remarks>
|
|
public sealed class HubTokenService
|
|
{
|
|
// Internal rather than private so a test can protect a hand-built payload through the same
|
|
// purpose and assert how Validate reads a payload shape this class no longer mints (a token
|
|
// predating the Tags field). Copying the literal into the test instead would let the two
|
|
// drift and silently turn that test into an assertion about an unrelated protector.
|
|
internal const string ProtectorPurpose = "ZB.MOM.WW.MxGateway.Dashboard.HubToken.v1";
|
|
|
|
// Hub bearer tokens are single-purpose, data-protection-encrypted, and NOT server-side
|
|
// revocable. A short lifetime bounds the exposure window of a token captured from a proxy
|
|
// or log after logout (the cookie is cleared on logout, but outstanding tokens are not), and
|
|
// bounds how long a stale role set survives a role change. It now bounds a stale *tag* grant
|
|
// the same way (SEC-25): the token carries the tags resolved from the caller's LDAP groups at
|
|
// mint time, so revoking a GroupToTag entry takes effect for token-authenticated hub
|
|
// connections within one lifetime — the natural place the deferred "tokens gain session
|
|
// binding" note landed. Five minutes is transparent to clients that re-fetch from /hubs/token
|
|
// on every (re)connect, which is what a remote hub consumer is expected to do; see
|
|
// docs/GatewayDashboardDesign.md. Heavier jti-denylist revocation stays deferred.
|
|
internal static readonly TimeSpan TokenLifetime = TimeSpan.FromMinutes(5);
|
|
|
|
private readonly ITimeLimitedDataProtector _protector;
|
|
private readonly IOptions<GatewayOptions> _options;
|
|
|
|
/// <summary>Initializes a new instance of the HubTokenService with a data protection provider.</summary>
|
|
/// <param name="dataProtection">The data protection provider for token encryption.</param>
|
|
/// <param name="options">
|
|
/// Gateway options supplying <c>MxGateway:Dashboard:GroupToTag</c>, the map used to resolve the
|
|
/// caller's granted visibility tags at mint time.
|
|
/// </param>
|
|
public HubTokenService(IDataProtectionProvider dataProtection, IOptions<GatewayOptions> options)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(dataProtection);
|
|
ArgumentNullException.ThrowIfNull(options);
|
|
_protector = dataProtection.CreateProtector(ProtectorPurpose).ToTimeLimitedDataProtector();
|
|
_options = options;
|
|
}
|
|
|
|
/// <summary>Issues a bearer token carrying the user's identity, roles, and granted tags.</summary>
|
|
/// <param name="user">The claims principal representing the user.</param>
|
|
/// <returns>The data-protected bearer token string.</returns>
|
|
public string Issue(ClaimsPrincipal user) => Issue(user, TokenLifetime);
|
|
|
|
/// <summary>
|
|
/// Issues a bearer token that expires after the supplied lifetime. Test seam so a caller can
|
|
/// mint an already-expired token deterministically without wall-clock delay; production callers
|
|
/// use <see cref="Issue(ClaimsPrincipal)"/> and get <see cref="TokenLifetime"/>.
|
|
/// </summary>
|
|
/// <param name="user">The claims principal representing the user.</param>
|
|
/// <param name="lifetime">The lifetime applied to the token; a non-positive value yields an already-expired token.</param>
|
|
/// <returns>The data-protected bearer token string.</returns>
|
|
internal string Issue(ClaimsPrincipal user, TimeSpan lifetime)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(user);
|
|
|
|
// Resolved from the caller's LDAP-group claims rather than copied from any tag claims the
|
|
// principal already carries: re-resolving is what makes the 5-minute lifetime an actual
|
|
// staleness bound on the grant. Tags are stamped for every caller — an Administrator
|
|
// bypasses the ACL, so theirs are simply moot rather than a special case here.
|
|
IReadOnlySet<string> grantedTags = DashboardGroupTagMapping.MapGroupsToTags(
|
|
user.FindAll(DashboardAuthenticationDefaults.LdapGroupClaimType).Select(c => c.Value),
|
|
_options.Value.Dashboard.GroupToTag);
|
|
|
|
HubTokenPayload payload = new(
|
|
user.Identity?.Name,
|
|
user.FindFirstValue(ClaimTypes.NameIdentifier),
|
|
[.. user.FindAll(ClaimTypes.Role).Select(c => c.Value)],
|
|
[.. grantedTags]);
|
|
return _protector.Protect(JsonSerializer.Serialize(payload), lifetime);
|
|
}
|
|
|
|
/// <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)
|
|
{
|
|
if (string.IsNullOrEmpty(token))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
try
|
|
{
|
|
HubTokenPayload? payload = JsonSerializer.Deserialize<HubTokenPayload>(_protector.Unprotect(token));
|
|
if (payload is null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (string.IsNullOrEmpty(payload.Name) && string.IsNullOrEmpty(payload.NameIdentifier))
|
|
{
|
|
return null;
|
|
}
|
|
|
|
List<Claim> claims = [];
|
|
if (!string.IsNullOrEmpty(payload.Name))
|
|
{
|
|
claims.Add(new Claim(ClaimTypes.Name, payload.Name));
|
|
}
|
|
|
|
if (!string.IsNullOrEmpty(payload.NameIdentifier))
|
|
{
|
|
claims.Add(new Claim(ClaimTypes.NameIdentifier, payload.NameIdentifier));
|
|
}
|
|
|
|
claims.AddRange((payload.Roles ?? []).Select(r => new Claim(ClaimTypes.Role, r)));
|
|
// Rehydrated alongside the roles so the reconstructed principal is what
|
|
// IDashboardSessionAcl reads on the hub path — a token minted before the tag field
|
|
// existed (or by a caller with no grant) simply yields an empty grant, which denies.
|
|
claims.AddRange((payload.Tags ?? []).Select(t => new Claim(
|
|
DashboardAuthenticationDefaults.DashboardTagClaimType,
|
|
t)));
|
|
|
|
ClaimsIdentity identity = new(
|
|
claims,
|
|
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
|
ClaimTypes.Name,
|
|
ClaimTypes.Role);
|
|
return new ClaimsPrincipal(identity);
|
|
}
|
|
catch (Exception ex) when (ex is CryptographicException or JsonException)
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
private sealed record HubTokenPayload(string? Name, string? NameIdentifier, string[]? Roles, string[]? Tags);
|
|
}
|