Merge fix/review-2026-12-phase0 (2026-12-02 review fix plan)
This commit is contained in:
@@ -1,7 +1,27 @@
|
||||
@* AuthorizeRouteView, not RouteView (DSH-001): the router is interactive, so a navigation that
|
||||
starts inside a circuit never issues an HTTP request and never meets endpoint authorization.
|
||||
Only AuthorizeRouteView evaluates a page's [Authorize] attribute on that path — the Alarms page
|
||||
(AlarmsPolicy) and the shared Secrets page (secrets:manage) both rely on it. Pages without an
|
||||
attribute are rendered as before; the endpoint ViewerPolicy still gates the initial request. *@
|
||||
<Router AppAssembly="@typeof(Routes).Assembly"
|
||||
AdditionalAssemblies="new[]{ typeof(ZB.MOM.WW.Secrets.Ui.SecretsPage).Assembly }">
|
||||
<Found Context="routeData">
|
||||
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
|
||||
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
|
||||
<NotAuthorized>
|
||||
<PageTitle>Dashboard - Not Authorized</PageTitle>
|
||||
<section class="dashboard-section">
|
||||
<h1 class="h4 mb-3">Not Authorized</h1>
|
||||
@if (context.User.Identity?.IsAuthenticated == true)
|
||||
{
|
||||
<p class="mb-0">Your dashboard role does not grant access to this page.</p>
|
||||
}
|
||||
else
|
||||
{
|
||||
<p class="mb-0">This page requires a signed-in dashboard role. <a href="/login">Sign in</a></p>
|
||||
}
|
||||
</section>
|
||||
</NotAuthorized>
|
||||
</AuthorizeRouteView>
|
||||
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
|
||||
</Found>
|
||||
<NotFound>
|
||||
|
||||
@@ -18,7 +18,8 @@ public sealed class DashboardApiKeyManagementService(
|
||||
IApiKeyPepperProvider pepperProvider,
|
||||
IAuditWriter auditWriter,
|
||||
IHttpContextAccessor httpContextAccessor,
|
||||
IApiKeyCacheInvalidator? cacheInvalidator = null) : IDashboardApiKeyManagementService
|
||||
IApiKeyCacheInvalidator? cacheInvalidator = null,
|
||||
ApiKeyStreamRegistry? streamRegistry = null) : IDashboardApiKeyManagementService
|
||||
{
|
||||
private const string UnauthorizedMessage = "Sign in with an authorized LDAP account to manage API keys.";
|
||||
private const string PepperNotConfiguredMessage = "API key pepper is not configured.";
|
||||
@@ -108,6 +109,10 @@ public sealed class DashboardApiKeyManagementService(
|
||||
|
||||
cacheInvalidator?.Invalidate(normalizedKeyId);
|
||||
|
||||
// The cache eviction stops new calls; this ends the streams the key already has open
|
||||
// (SEC-004), which were authenticated once at open and would otherwise keep delivering.
|
||||
streamRegistry?.Revoke(normalizedKeyId);
|
||||
|
||||
await WriteDashboardAuditAsync(
|
||||
user,
|
||||
normalizedKeyId,
|
||||
@@ -151,6 +156,10 @@ public sealed class DashboardApiKeyManagementService(
|
||||
|
||||
cacheInvalidator?.Invalidate(normalizedKeyId);
|
||||
|
||||
// The cache eviction stops new calls; this ends the streams the key already has open
|
||||
// (SEC-004), which were authenticated once at open and would otherwise keep delivering.
|
||||
streamRegistry?.Revoke(normalizedKeyId);
|
||||
|
||||
bool succeeded = rotated.Token is not null;
|
||||
|
||||
await WriteDashboardAuditAsync(
|
||||
@@ -192,6 +201,10 @@ public sealed class DashboardApiKeyManagementService(
|
||||
|
||||
cacheInvalidator?.Invalidate(normalizedKeyId);
|
||||
|
||||
// The cache eviction stops new calls; this ends the streams the key already has open
|
||||
// (SEC-004), which were authenticated once at open and would otherwise keep delivering.
|
||||
streamRegistry?.Revoke(normalizedKeyId);
|
||||
|
||||
await WriteDashboardAuditAsync(
|
||||
user,
|
||||
normalizedKeyId,
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Diagnostics;
|
||||
using Grpc.Core;
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
@@ -24,6 +25,60 @@ public sealed class MxAccessGatewayService(
|
||||
ILogger<MxAccessGatewayService> logger,
|
||||
IGatewayAlarmService alarmService) : MxAccessGateway.MxAccessGatewayBase
|
||||
{
|
||||
/// <summary>
|
||||
/// Command kinds <see cref="ApplyConstraintsAsync"/> checks against the caller's read or
|
||||
/// write constraints because their payload names a tag address or an item handle that maps
|
||||
/// back to one.
|
||||
/// </summary>
|
||||
internal static readonly FrozenSet<MxCommandKind> ConstrainedCommandKinds = new[]
|
||||
{
|
||||
MxCommandKind.AddItem,
|
||||
MxCommandKind.AddItem2,
|
||||
MxCommandKind.AddBufferedItem,
|
||||
MxCommandKind.AddItemBulk,
|
||||
MxCommandKind.SubscribeBulk,
|
||||
MxCommandKind.AdviseItemBulk,
|
||||
MxCommandKind.ReadBulk,
|
||||
MxCommandKind.Write,
|
||||
MxCommandKind.Write2,
|
||||
MxCommandKind.WriteSecured,
|
||||
MxCommandKind.WriteSecured2,
|
||||
MxCommandKind.WriteBulk,
|
||||
MxCommandKind.Write2Bulk,
|
||||
MxCommandKind.WriteSecuredBulk,
|
||||
MxCommandKind.WriteSecured2Bulk,
|
||||
}.ToFrozenSet();
|
||||
|
||||
/// <summary>
|
||||
/// Command kinds that carry no tag address, so they pass <see cref="ApplyConstraintsAsync"/>
|
||||
/// without a constraint check. Handle-only commands (<c>Advise</c>, <c>RemoveItem</c>, ...)
|
||||
/// belong here because the add that produced the handle was checked. Any kind in neither
|
||||
/// set is refused with <c>PermissionDenied</c>, so a new tag-bearing kind cannot slip
|
||||
/// through unchecked; the enum-coverage test fails until it is classified.
|
||||
/// </summary>
|
||||
internal static readonly FrozenSet<MxCommandKind> UnconstrainedCommandKinds = new[]
|
||||
{
|
||||
MxCommandKind.Register,
|
||||
MxCommandKind.Unregister,
|
||||
MxCommandKind.RemoveItem,
|
||||
MxCommandKind.Advise,
|
||||
MxCommandKind.UnAdvise,
|
||||
MxCommandKind.AdviseSupervisory,
|
||||
MxCommandKind.SetBufferedUpdateInterval,
|
||||
MxCommandKind.Suspend,
|
||||
MxCommandKind.Activate,
|
||||
MxCommandKind.AuthenticateUser,
|
||||
MxCommandKind.ArchestraUserToId,
|
||||
MxCommandKind.RemoveItemBulk,
|
||||
MxCommandKind.UnAdviseItemBulk,
|
||||
MxCommandKind.UnsubscribeBulk,
|
||||
MxCommandKind.Ping,
|
||||
MxCommandKind.GetSessionState,
|
||||
MxCommandKind.GetWorkerInfo,
|
||||
MxCommandKind.DrainEvents,
|
||||
MxCommandKind.ShutdownWorker,
|
||||
}.ToFrozenSet();
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<OpenSessionReply> OpenSession(
|
||||
OpenSessionRequest request,
|
||||
@@ -83,6 +138,14 @@ public sealed class MxAccessGatewayService(
|
||||
try
|
||||
{
|
||||
requestValidator.ValidateCloseSession(request);
|
||||
|
||||
// Owner-scoped close: only the key that opened the session may close it. An unknown id
|
||||
// falls through so the session manager reports SessionNotFound exactly as before.
|
||||
if (sessionManager.TryGetSession(request.SessionId, out GatewaySession? session) && session is not null)
|
||||
{
|
||||
EnsureOwner(session);
|
||||
}
|
||||
|
||||
SessionCloseResult result = await sessionManager
|
||||
.CloseSessionAsync(request.SessionId, context.CancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
@@ -115,6 +178,7 @@ public sealed class MxAccessGatewayService(
|
||||
// would duplicate InvokeAsync's fault mapping (SessionNotFound / state checks / metrics)
|
||||
// at a second entry point — deliberately not worth it until a profile says otherwise.
|
||||
GatewaySession session = ResolveSession(request.SessionId);
|
||||
EnsureOwner(session);
|
||||
MxCommand command = request.Command;
|
||||
BulkConstraintPlan? bulkConstraintPlan = await ApplyConstraintsAsync(
|
||||
session,
|
||||
@@ -335,6 +399,25 @@ public sealed class MxAccessGatewayService(
|
||||
return session;
|
||||
}
|
||||
|
||||
// Owner-scoped session RPCs (security control, SES-002): Invoke and CloseSession act on a
|
||||
// session only for the API key that opened it — the same ordinal compare EventStreamService
|
||||
// applies to StreamEvents attach. Possessing the matching scope and knowing a session id is
|
||||
// not enough; without this, an events:read key could DrainEvents another key's queue, and an
|
||||
// invoke:write key could write through another key's session. There is deliberately no admin
|
||||
// override: operators close or kill any session from the dashboard, which calls
|
||||
// ISessionManager directly and never passes through here. A null owner (session opened with
|
||||
// authentication disabled) matches only a null caller key.
|
||||
private void EnsureOwner(GatewaySession session)
|
||||
{
|
||||
string? callerKeyId = identityAccessor.Current?.KeyId;
|
||||
if (!string.Equals(session.OwnerKeyId, callerKeyId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new SessionManagerException(
|
||||
SessionManagerErrorCode.PermissionDenied,
|
||||
$"Session {session.SessionId} is owned by a different API key; session RPCs are owner-scoped.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<BulkConstraintPlan?> ApplyConstraintsAsync(
|
||||
GatewaySession session,
|
||||
MxCommand command,
|
||||
@@ -352,6 +435,10 @@ public sealed class MxAccessGatewayService(
|
||||
await EnforceReadTagAsync(identity, command.Kind, command.AddItem2.ItemDefinition, correlationId, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return null;
|
||||
case MxCommandKind.AddBufferedItem:
|
||||
await EnforceReadTagAsync(identity, command.Kind, command.AddBufferedItem.ItemDefinition, correlationId, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return null;
|
||||
case MxCommandKind.AddItemBulk:
|
||||
return await FilterTagBulkAsync(
|
||||
identity,
|
||||
@@ -478,10 +565,34 @@ public sealed class MxAccessGatewayService(
|
||||
.ConfigureAwait(false);
|
||||
return null;
|
||||
default:
|
||||
if (UnconstrainedCommandKinds.Contains(command.Kind))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
// Fail closed: a kind that is neither checked above nor on the no-tag allow-list
|
||||
// (a gateway-internal alarm kind, or a kind added to the contract after this
|
||||
// switch) may carry a tag address the API-key constraints never saw.
|
||||
await RefuseUnconstrainedCommandAsync(identity, command.Kind, correlationId, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task RefuseUnconstrainedCommandAsync(
|
||||
ApiKeyIdentity? identity,
|
||||
MxCommandKind commandKind,
|
||||
string? correlationId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ConstraintFailure failure = new(
|
||||
"command-kind",
|
||||
$"Command kind {commandKind} is not accepted on Invoke: it has no API-key constraint check.");
|
||||
await constraintEnforcer.RecordDenialAsync(identity, commandKind.ToString(), commandKind.ToString(), failure, correlationId, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
throw new RpcException(new Status(StatusCode.PermissionDenied, failure.Message));
|
||||
}
|
||||
|
||||
private async Task EnforceReadTagAsync(
|
||||
ApiKeyIdentity? identity,
|
||||
MxCommandKind commandKind,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
@@ -19,6 +20,25 @@ public interface IApiKeyCacheInvalidator
|
||||
void Invalidate(string keyId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read-only access to cached successful verifications, consulted by the auth surfaces before the
|
||||
/// failure limiter (SEC-002).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A hit means the presented token — key id <em>and</em> secret — hashed to an entry that a real
|
||||
/// verification stored within the TTL. It costs no store read, which is the only thing the failure
|
||||
/// limiter protects, so a hit bypasses the limiter: a spray of bad secrets against a public key id
|
||||
/// can then never deny the key to the client holding the correct one.
|
||||
/// </remarks>
|
||||
public interface IApiKeyVerificationCache
|
||||
{
|
||||
/// <summary>Returns a cached successful verification for the header, if one is within TTL.</summary>
|
||||
/// <param name="authorizationHeader">The raw <c>authorization</c> header value.</param>
|
||||
/// <param name="verification">The cached successful verification, when found.</param>
|
||||
/// <returns><see langword="true"/> on a cache hit.</returns>
|
||||
bool TryGetCachedSuccess(string? authorizationHeader, [NotNullWhen(true)] out ApiKeyVerification? verification);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An <see cref="IApiKeyVerifier"/> decorator that caches successful verifications for a short,
|
||||
/// configurable TTL (<see cref="SecurityOptions.ApiKeyVerificationCacheSeconds"/>), keyed on a
|
||||
@@ -72,7 +92,7 @@ public interface IApiKeyCacheInvalidator
|
||||
/// live cache rather than to every token ever verified.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalidator
|
||||
public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalidator, IApiKeyVerificationCache
|
||||
{
|
||||
private const string CacheKeyPrefix = "mxgw:apikeyverif:";
|
||||
private const string TokenPrefix = "mxgw";
|
||||
@@ -217,6 +237,22 @@ public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalid
|
||||
return await verification.WaitAsync(ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryGetCachedSuccess(string? authorizationHeader, [NotNullWhen(true)] out ApiKeyVerification? verification)
|
||||
{
|
||||
if (_ttl > TimeSpan.Zero
|
||||
&& TryComputeCacheKey(authorizationHeader, out string cacheKey)
|
||||
&& _cache.TryGetValue(cacheKey, out ApiKeyVerification? cached)
|
||||
&& cached is not null)
|
||||
{
|
||||
verification = cached;
|
||||
return true;
|
||||
}
|
||||
|
||||
verification = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
// The shared body of one single-flight miss. Not bound to any caller's token: a caller that
|
||||
// gives up must not cancel the verification other callers are waiting on.
|
||||
private async Task<ApiKeyVerification> VerifyMissAsync(
|
||||
|
||||
@@ -21,9 +21,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
/// <para>
|
||||
/// An over-limit state is a valve, not a wall: at most one request per
|
||||
/// <see cref="SecurityOptions.ApiKeyFailureProbeIntervalSeconds"/> is admitted through to the real
|
||||
/// verifier, and a successful verification resets both layers. The reset path therefore stays
|
||||
/// reachable while throttled — the earlier design keyed solely on the attacker-supplied key id and
|
||||
/// rejected before verification, so the legitimate holder could never clear the block.
|
||||
/// verifier. A successful verification clears the caller's own <c>(address, key id)</c> partition
|
||||
/// and marks that pair as verified for one window; it does <em>not</em> clear the key id's
|
||||
/// cross-peer aggregate (SEC-003), which decays by window expiry only — otherwise every call from
|
||||
/// a key in steady use would wipe the aggregate and a sprayer would never be bounded by it. The
|
||||
/// verified mark is what keeps the holder from being denied by a spray against its public key id
|
||||
/// (SEC-002): an address that verified the key inside the window skips the aggregate layer, and the
|
||||
/// interceptor serves a cached verification without consulting the limiter at all. Neither path is
|
||||
/// reachable without the correct secret.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The tracked partition set is a bounded LRU (<see cref="SecurityOptions.ApiKeyFailureTrackedPeers"/>).
|
||||
@@ -71,6 +76,11 @@ public sealed class ApiKeyFailureLimiter
|
||||
private readonly ConcurrentDictionary<string, WindowState> _aggregates = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, PeerKeyIds> _peerKeyIds = new(StringComparer.Ordinal);
|
||||
|
||||
// Composite (address, key id) -> ticks of the last successful verification from that address.
|
||||
// Only a correct secret writes here, so it is bounded by legitimate traffic, and it is pruned to
|
||||
// the same partition cap on the success path.
|
||||
private readonly ConcurrentDictionary<string, long> _verified = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="ApiKeyFailureLimiter"/> class.</summary>
|
||||
/// <param name="security">Security options carrying the failure-limit knobs.</param>
|
||||
/// <param name="clock">The time provider.</param>
|
||||
@@ -115,6 +125,9 @@ public sealed class ApiKeyFailureLimiter
|
||||
/// <summary>Gets the number of tracked per-key-id aggregates. Test seam.</summary>
|
||||
internal int TrackedAggregateCount => _aggregates.Count;
|
||||
|
||||
/// <summary>Gets the number of tracked verified <c>(address, key id)</c> marks. Test seam.</summary>
|
||||
internal int VerifiedMarkCount => _verified.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Test seam invoked between a probe claim and its compensating release; <see langword="null"/>
|
||||
/// in production, where it costs one null check on the already-refused path.
|
||||
@@ -166,7 +179,9 @@ public sealed class ApiKeyFailureLimiter
|
||||
}
|
||||
|
||||
bool peerOver = peerState is not null && IsOverLimit(peerState, now, _limit);
|
||||
bool aggregateOver = aggregateState is not null && IsOverLimit(aggregateState, now, _aggregateLimit);
|
||||
bool aggregateOver = aggregateState is not null
|
||||
&& IsOverLimit(aggregateState, now, _aggregateLimit)
|
||||
&& !IsRecentlyVerified(peer, partition.KeyId!, now);
|
||||
if (!peerOver && !aggregateOver)
|
||||
{
|
||||
return ApiKeyThrottleDecision.Allowed;
|
||||
@@ -239,14 +254,17 @@ public sealed class ApiKeyFailureLimiter
|
||||
EvictIfOverCapacity(_aggregates, now, _aggregateLimit, releaseKeyIds: false);
|
||||
}
|
||||
|
||||
/// <summary>Clears both limiter layers for the partition after a successful verification.</summary>
|
||||
/// <summary>
|
||||
/// Records a successful verification: clears the caller's own partition and marks the
|
||||
/// <c>(address, key id)</c> pair verified. The key id's cross-peer aggregate is left to decay.
|
||||
/// </summary>
|
||||
/// <param name="partition">The throttle partition derived from the request.</param>
|
||||
public void Reset(ApiKeyThrottlePartition partition) => Reset(partition, PartitionResolution.Unresolved);
|
||||
|
||||
/// <summary>
|
||||
/// Clears both limiter layers for the partition after a successful verification, reusing the
|
||||
/// storage key <see cref="Check(ApiKeyThrottlePartition, out PartitionResolution)"/> already
|
||||
/// resolved for this request.
|
||||
/// Records a successful verification, reusing the storage key
|
||||
/// <see cref="Check(ApiKeyThrottlePartition, out PartitionResolution)"/> already resolved for
|
||||
/// this request.
|
||||
/// </summary>
|
||||
/// <param name="partition">The throttle partition derived from the request.</param>
|
||||
/// <param name="resolution">
|
||||
@@ -272,15 +290,42 @@ public sealed class ApiKeyFailureLimiter
|
||||
RemovePartition(partitionKey);
|
||||
}
|
||||
|
||||
// The aggregate is cleared on the presented key id even when the composite partition
|
||||
// collapsed to the fallback: a verified secret is proof the key is not under successful
|
||||
// attack, and clearing is what makes the block recoverable.
|
||||
if (partition.KeyId is not null)
|
||||
// The aggregate is deliberately NOT cleared (SEC-003). A key in steady use succeeds many
|
||||
// times a second, so clearing it on success meant it never accumulated and a sprayer guessing
|
||||
// the same key id from other addresses was bounded by neither layer. It decays by window.
|
||||
// Instead the verifying address is marked, so the aggregate cannot lock the holder out.
|
||||
if (partition.KeyId is not null && _aggregateLimit > 0 && _limit > 0)
|
||||
{
|
||||
_aggregates.TryRemove(partition.KeyId, out _);
|
||||
MarkVerified(peer, partition.KeyId, _clock.GetUtcNow().UtcTicks);
|
||||
}
|
||||
}
|
||||
|
||||
private void MarkVerified(string peer, string keyId, long now)
|
||||
{
|
||||
_verified[Composite(peer, keyId)] = now;
|
||||
if (_verified.Count <= _maxPartitions)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// Over the cap: drop marks that have aged out of the window. If legitimate traffic alone
|
||||
// still exceeds the cap the map overshoots; it is written only by correct secrets.
|
||||
foreach (KeyValuePair<string, long> entry in _verified)
|
||||
{
|
||||
if (now - entry.Value >= _windowTicks)
|
||||
{
|
||||
_verified.TryRemove(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsRecentlyVerified(string peer, string keyId, long now)
|
||||
{
|
||||
return !_verified.IsEmpty
|
||||
&& _verified.TryGetValue(Composite(peer, keyId), out long verifiedAt)
|
||||
&& now - verifiedAt < _windowTicks;
|
||||
}
|
||||
|
||||
/// <summary>Returns whether the partition currently has tracked failure state. Test seam.</summary>
|
||||
/// <param name="partition">The throttle partition to look up.</param>
|
||||
/// <returns><see langword="true"/> when the partition has a tracked window.</returns>
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
using System.Collections.Concurrent;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Tracks the streaming gRPC calls each API key has open, so revoking, rotating or deleting the key
|
||||
/// ends them (SEC-004).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A streaming call is authenticated once, when it opens. Evicting the verification cache on
|
||||
/// revoke stops new calls but leaves an open <c>StreamEvents</c>, <c>StreamAlarms</c> or
|
||||
/// <c>WatchDeployEvents</c> delivering data until the client disconnects. The authorization
|
||||
/// interceptor registers every streaming call here under the caller's key id and hands the handler
|
||||
/// a call context whose cancellation token also fires on <see cref="Revoke"/>; the interceptor then
|
||||
/// reports the end of the call as <c>Unauthenticated</c>.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Only revocations made through this gateway process reach the registry (the dashboard API Keys
|
||||
/// page). The separate <c>apikey</c> CLI process cannot signal it, so a key revoked there ends its
|
||||
/// open streams only when they reconnect — the same bounded window its cache eviction has.
|
||||
/// Key ids compare ordinal-ignore-case, matching the verification cache (mxaccessgw#173).
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class ApiKeyStreamRegistry
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, ConcurrentDictionary<Registration, byte>> _byKeyId =
|
||||
new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>Gets the number of open streaming calls registered for a key id. Test seam.</summary>
|
||||
/// <param name="keyId">The key id.</param>
|
||||
/// <returns>The open registration count.</returns>
|
||||
internal int CountFor(string keyId) =>
|
||||
_byKeyId.TryGetValue(keyId, out ConcurrentDictionary<Registration, byte>? set) ? set.Count : 0;
|
||||
|
||||
/// <summary>
|
||||
/// Registers a streaming call. Dispose the returned registration when the call ends.
|
||||
/// </summary>
|
||||
/// <param name="keyId">The authenticated caller's key id.</param>
|
||||
/// <param name="callCancellation">The call's own cancellation token, linked into the registration's.</param>
|
||||
/// <returns>The registration whose <see cref="Registration.Token"/> the handler must observe.</returns>
|
||||
public Registration Register(string keyId, CancellationToken callCancellation)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrEmpty(keyId);
|
||||
|
||||
Registration registration = new(this, keyId, callCancellation);
|
||||
while (true)
|
||||
{
|
||||
ConcurrentDictionary<Registration, byte> set = _byKeyId.GetOrAdd(keyId, static _ => new());
|
||||
set[registration] = 0;
|
||||
|
||||
// Lost a race with the last registration of this key id removing an empty set: re-add
|
||||
// into whatever set is current so a later Revoke can still find this call.
|
||||
if (_byKeyId.TryGetValue(keyId, out ConcurrentDictionary<Registration, byte>? current)
|
||||
&& ReferenceEquals(current, set))
|
||||
{
|
||||
return registration;
|
||||
}
|
||||
|
||||
set.TryRemove(registration, out _);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Ends every open streaming call registered for the key id.</summary>
|
||||
/// <param name="keyId">The revoked, rotated or deleted key id.</param>
|
||||
/// <returns>The number of calls that were cancelled.</returns>
|
||||
public int Revoke(string keyId)
|
||||
{
|
||||
if (string.IsNullOrEmpty(keyId) || !_byKeyId.TryGetValue(keyId, out ConcurrentDictionary<Registration, byte>? set))
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
int cancelled = 0;
|
||||
foreach (Registration registration in set.Keys)
|
||||
{
|
||||
if (registration.MarkRevoked())
|
||||
{
|
||||
cancelled++;
|
||||
}
|
||||
}
|
||||
|
||||
return cancelled;
|
||||
}
|
||||
|
||||
private void Unregister(Registration registration)
|
||||
{
|
||||
if (_byKeyId.TryGetValue(registration.KeyId, out ConcurrentDictionary<Registration, byte>? set)
|
||||
&& set.TryRemove(registration, out _)
|
||||
&& set.IsEmpty)
|
||||
{
|
||||
_byKeyId.TryRemove(new KeyValuePair<string, ConcurrentDictionary<Registration, byte>>(registration.KeyId, set));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>One open streaming call.</summary>
|
||||
public sealed class Registration : IDisposable
|
||||
{
|
||||
private readonly ApiKeyStreamRegistry _owner;
|
||||
private readonly CancellationTokenSource _cancellation;
|
||||
private int _revoked;
|
||||
private int _disposed;
|
||||
|
||||
internal Registration(ApiKeyStreamRegistry owner, string keyId, CancellationToken callCancellation)
|
||||
{
|
||||
_owner = owner;
|
||||
KeyId = keyId;
|
||||
_cancellation = CancellationTokenSource.CreateLinkedTokenSource(callCancellation);
|
||||
}
|
||||
|
||||
/// <summary>Gets the key id the call authenticated with.</summary>
|
||||
public string KeyId { get; }
|
||||
|
||||
/// <summary>Gets the token that fires when the call is cancelled or its key is revoked.</summary>
|
||||
public CancellationToken Token => _cancellation.Token;
|
||||
|
||||
/// <summary>Gets a value indicating whether the key was revoked while the call was open.</summary>
|
||||
public bool IsRevoked => Volatile.Read(ref _revoked) == 1;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _disposed, 1) == 1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_owner.Unregister(this);
|
||||
_cancellation.Dispose();
|
||||
}
|
||||
|
||||
internal bool MarkRevoked()
|
||||
{
|
||||
if (Interlocked.Exchange(ref _revoked, 1) == 1 || Volatile.Read(ref _disposed) == 1)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_cancellation.Cancel();
|
||||
}
|
||||
catch (ObjectDisposedException)
|
||||
{
|
||||
// The call ended between the checks above and the cancel; nothing left to stop.
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,9 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
/// <see cref="GatewayGrpcAuthorizationInterceptor"/> (literal <c>mxgw</c> prefix, at least three
|
||||
/// non-empty underscore segments, bounded key-id length) so junk tokens cannot mint partitions.
|
||||
/// </remarks>
|
||||
/// <param name="TransportPeer">The gRPC transport peer address (<c>ServerCallContext.Peer</c>).</param>
|
||||
/// <param name="TransportPeer">
|
||||
/// The client's remote IP with no port, as produced by <see cref="ApiKeyThrottlePeer"/>. The
|
||||
/// source port is excluded because it changes with every connection (SEC-001).
|
||||
/// </param>
|
||||
/// <param name="KeyId">The key id claimed by a validly shaped token, or <see langword="null"/>.</param>
|
||||
public readonly record struct ApiKeyThrottlePartition(string TransportPeer, string? KeyId);
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
using System.Net;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Derives the address half of an <see cref="ApiKeyThrottlePartition"/>: the client's remote IP
|
||||
/// with no source port, in one canonical form shared by the gRPC interceptor and the
|
||||
/// <c>/metrics</c> handler.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The port must not be part of the partition (SEC-001). It is the client's ephemeral source port,
|
||||
/// so keying on it made every new TCP connection a fresh partition: an attacker could send
|
||||
/// <c>limit - 1</c> bad secrets, reconnect, and repeat without ever being throttled, and each
|
||||
/// connection minted a tracked partition. Both auth surfaces normalise through this type so a
|
||||
/// failure on one counts against the same address on the other.
|
||||
/// </remarks>
|
||||
public static class ApiKeyThrottlePeer
|
||||
{
|
||||
private const string Ipv4Prefix = "ipv4:";
|
||||
private const string Ipv6Prefix = "ipv6:[";
|
||||
|
||||
/// <summary>
|
||||
/// Extracts the remote IP from a Grpc.AspNetCore peer string (<c>ipv4:1.2.3.4:5678</c> or
|
||||
/// <c>ipv6:[::1]:5678</c>). A peer in any other form (<c>unknown</c>, a Unix socket) is returned
|
||||
/// unchanged, since it carries no port to strip.
|
||||
/// </summary>
|
||||
/// <param name="grpcPeer">The value of <c>ServerCallContext.Peer</c>.</param>
|
||||
/// <returns>The canonical address string.</returns>
|
||||
public static string FromGrpcPeer(string grpcPeer)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(grpcPeer);
|
||||
|
||||
ReadOnlySpan<char> address;
|
||||
if (grpcPeer.StartsWith(Ipv4Prefix, StringComparison.Ordinal))
|
||||
{
|
||||
ReadOnlySpan<char> rest = grpcPeer.AsSpan(Ipv4Prefix.Length);
|
||||
int portSeparator = rest.LastIndexOf(':');
|
||||
address = portSeparator > 0 ? rest[..portSeparator] : rest;
|
||||
}
|
||||
else if (grpcPeer.StartsWith(Ipv6Prefix, StringComparison.Ordinal))
|
||||
{
|
||||
ReadOnlySpan<char> rest = grpcPeer.AsSpan(Ipv6Prefix.Length);
|
||||
int close = rest.IndexOf(']');
|
||||
if (close <= 0)
|
||||
{
|
||||
return grpcPeer;
|
||||
}
|
||||
|
||||
address = rest[..close];
|
||||
}
|
||||
else
|
||||
{
|
||||
return grpcPeer;
|
||||
}
|
||||
|
||||
return IPAddress.TryParse(address, out IPAddress? parsed) ? FromRemoteIp(parsed) : grpcPeer;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Formats an HTTP connection's remote IP. An IPv4-mapped IPv6 address is reduced to IPv4 so a
|
||||
/// dual-stack listener does not split one client across two partitions.
|
||||
/// </summary>
|
||||
/// <param name="remoteIpAddress">The connection's remote address, or <see langword="null"/>.</param>
|
||||
/// <returns>The canonical address string, or <c>unknown</c>.</returns>
|
||||
public static string FromRemoteIp(IPAddress? remoteIpAddress)
|
||||
{
|
||||
if (remoteIpAddress is null)
|
||||
{
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
return remoteIpAddress.IsIPv4MappedToIPv6
|
||||
? remoteIpAddress.MapToIPv4().ToString()
|
||||
: remoteIpAddress.ToString();
|
||||
}
|
||||
}
|
||||
+84
-13
@@ -18,12 +18,19 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
|
||||
IGatewayRequestIdentityAccessor identityAccessor,
|
||||
IOptions<GatewayOptions> options,
|
||||
ApiKeyFailureLimiter failureLimiter,
|
||||
GatewayMetrics metrics) : Interceptor
|
||||
GatewayMetrics metrics,
|
||||
ApiKeyStreamRegistry? streamRegistry = null) : Interceptor
|
||||
{
|
||||
private const string RevokedMessage = "The API key was revoked while the call was open.";
|
||||
|
||||
// Generated key ids are far shorter; the cap only exists to stop an invented "key id" of
|
||||
// arbitrary length from becoming a limiter partition.
|
||||
private const int MaxKeyIdLength = 64;
|
||||
|
||||
// The production verifier is the caching decorator; a test double that is not a cache simply
|
||||
// always takes the limiter path.
|
||||
private readonly IApiKeyVerificationCache? _verificationCache = apiKeyVerifier as IApiKeyVerificationCache;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
|
||||
TRequest request,
|
||||
@@ -55,7 +62,11 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
|
||||
IDisposable? identityScope = identity is null ? null : identityAccessor.Push(identity);
|
||||
using (identityScope)
|
||||
{
|
||||
await continuation(request, responseStream, context).ConfigureAwait(false);
|
||||
await RunRevocableAsync(
|
||||
identity,
|
||||
context,
|
||||
revocableContext => continuation(request, responseStream, revocableContext))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -77,7 +88,13 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
|
||||
IDisposable? identityScope = identity is null ? null : identityAccessor.Push(identity);
|
||||
using (identityScope)
|
||||
{
|
||||
return await continuation(requestStream, context).ConfigureAwait(false);
|
||||
TResponse response = default!;
|
||||
await RunRevocableAsync(
|
||||
identity,
|
||||
context,
|
||||
async revocableContext => response = await continuation(requestStream, revocableContext).ConfigureAwait(false))
|
||||
.ConfigureAwait(false);
|
||||
return response;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +110,43 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
|
||||
IDisposable? identityScope = identity is null ? null : identityAccessor.Push(identity);
|
||||
using (identityScope)
|
||||
{
|
||||
await continuation(requestStream, responseStream, context).ConfigureAwait(false);
|
||||
await RunRevocableAsync(
|
||||
identity,
|
||||
context,
|
||||
revocableContext => continuation(requestStream, responseStream, revocableContext))
|
||||
.ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Runs a streaming handler registered under the caller's key id (SEC-004). The handler sees a
|
||||
// call context whose cancellation token also fires when the key is revoked, rotated or deleted
|
||||
// through this process, so an open stream ends instead of outliving its credential. However the
|
||||
// handler then finishes — its own Cancelled mapping, a normal return — a revoked call is
|
||||
// reported as Unauthenticated, the status a fresh call with the same key would get.
|
||||
private async Task RunRevocableAsync(
|
||||
ApiKeyIdentity? identity,
|
||||
ServerCallContext context,
|
||||
Func<ServerCallContext, Task> handler)
|
||||
{
|
||||
if (identity is null || streamRegistry is null)
|
||||
{
|
||||
await handler(context).ConfigureAwait(false);
|
||||
return;
|
||||
}
|
||||
|
||||
using ApiKeyStreamRegistry.Registration registration = streamRegistry.Register(identity.KeyId, context.CancellationToken);
|
||||
try
|
||||
{
|
||||
await handler(new RevocableServerCallContext(context, registration.Token)).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception) when (registration.IsRevoked)
|
||||
{
|
||||
throw new RpcException(new Status(StatusCode.Unauthenticated, RevokedMessage));
|
||||
}
|
||||
|
||||
if (registration.IsRevoked)
|
||||
{
|
||||
throw new RpcException(new Status(StatusCode.Unauthenticated, RevokedMessage));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,6 +165,15 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
|
||||
|
||||
string? authorizationHeader = context.RequestHeaders.GetValue("authorization");
|
||||
|
||||
// A cached successful verification is proof of the correct secret and costs no store read,
|
||||
// so it skips the failure limiter entirely (SEC-002): a spray of bad secrets against this
|
||||
// key id, from anywhere, cannot deny the key to the client that holds it.
|
||||
if (_verificationCache is not null
|
||||
&& _verificationCache.TryGetCachedSuccess(authorizationHeader, out ApiKeyVerification? cached))
|
||||
{
|
||||
return AuthorizeVerifiedIdentity(cached, requiredScope);
|
||||
}
|
||||
|
||||
// Short-circuit a partition that has already failed too many times inside the sliding window
|
||||
// BEFORE the verification store read, so online guessing cannot spend a SQLite read per
|
||||
// attempt. The partition is the composite (transport peer, key id) — never the key id alone,
|
||||
@@ -150,13 +212,19 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
|
||||
"Missing or invalid API key."));
|
||||
}
|
||||
|
||||
// Successful authentication clears both limiter layers, so a legitimate client that
|
||||
// fat-fingered a few attempts is not penalised once it recovers — and, because the check
|
||||
// above admits a probe rather than blocking absolutely, this reset stays reachable while the
|
||||
// key is under an active spray.
|
||||
// Successful authentication clears this caller's own partition, so a legitimate client that
|
||||
// fat-fingered a few attempts is not penalised once it recovers, and marks the address as
|
||||
// verified for the key id so the cross-peer aggregate cannot lock it out. It leaves the
|
||||
// aggregate itself to decay by window (SEC-003): clearing it on every success meant a key in
|
||||
// steady use never accumulated one.
|
||||
failureLimiter.Reset(throttlePartition, throttleResolution);
|
||||
|
||||
ApiKeyIdentity identity = GatewayApiKeyIdentityMapper.ToGatewayIdentity(verification.Identity);
|
||||
return AuthorizeVerifiedIdentity(verification, requiredScope);
|
||||
}
|
||||
|
||||
private static ApiKeyIdentity AuthorizeVerifiedIdentity(ApiKeyVerification verification, string requiredScope)
|
||||
{
|
||||
ApiKeyIdentity identity = GatewayApiKeyIdentityMapper.ToGatewayIdentity(verification.Identity!);
|
||||
|
||||
if (!identity.Scopes.Contains(requiredScope))
|
||||
{
|
||||
@@ -168,14 +236,17 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
|
||||
return identity;
|
||||
}
|
||||
|
||||
// Resolves the failure-limiter partition: always the transport peer, plus the presented key id
|
||||
// when — and only when — the token is validly shaped. Both halves are unauthenticated input, so
|
||||
// the peer half is what keeps a throttle bound to the address that earned it.
|
||||
// Resolves the failure-limiter partition: always the remote IP (port stripped — the source port
|
||||
// changes per connection, SEC-001), plus the presented key id when — and only when — the token
|
||||
// is validly shaped. Both halves are unauthenticated input, so the address half is what keeps a
|
||||
// throttle bound to the address that earned it.
|
||||
private static ApiKeyThrottlePartition ResolveThrottlePartition(
|
||||
string? authorizationHeader,
|
||||
ServerCallContext context)
|
||||
{
|
||||
return new ApiKeyThrottlePartition(context.Peer, TryResolveKeyId(authorizationHeader));
|
||||
return new ApiKeyThrottlePartition(
|
||||
ApiKeyThrottlePeer.FromGrpcPeer(context.Peer),
|
||||
TryResolveKeyId(authorizationHeader));
|
||||
}
|
||||
|
||||
// Token shape mxgw_<keyId>_<secret>: the key id is the second underscore-delimited segment (the
|
||||
|
||||
+1
@@ -26,6 +26,7 @@ public static class GrpcAuthorizationServiceCollectionExtensions
|
||||
sp.GetRequiredService<IConfiguration>().GetSection(SecurityOptions.SectionName).Get<SecurityOptions>()
|
||||
?? new SecurityOptions(),
|
||||
sp.GetService<TimeProvider>() ?? TimeProvider.System));
|
||||
services.AddSingleton<ApiKeyStreamRegistry>();
|
||||
services.AddSingleton<GatewayGrpcAuthorizationInterceptor>();
|
||||
services
|
||||
.AddOptions<global::Grpc.AspNetCore.Server.GrpcServiceOptions>()
|
||||
|
||||
@@ -7,6 +7,7 @@ using ZB.MOM.WW.Auth.Abstractions.ApiKeys;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
using ZB.MOM.WW.MxGateway.Server.Metrics;
|
||||
using ZB.MOM.WW.MxGateway.Server.Security.Authentication;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
|
||||
@@ -35,9 +36,9 @@ public static class MetricsAuthorizationDefaults
|
||||
/// cookie scheme on the policy directly would turn an anonymous scrape into a 302 redirect to the
|
||||
/// login page. A throttled key partition answers <c>429</c>, mirroring the gRPC
|
||||
/// <c>ResourceExhausted</c>. Failure reasons are never echoed to the caller and the presented
|
||||
/// secret is never logged. The limiter's per-peer partition here is the remote IP, whereas the gRPC
|
||||
/// interceptor's is the gRPC peer string (address and port, i.e. per connection), so the two paths
|
||||
/// share only the per-key-id aggregate layer.
|
||||
/// secret is never logged. Both this handler and the gRPC interceptor partition the limiter on the
|
||||
/// remote IP through <see cref="ApiKeyThrottlePeer"/>, so the two surfaces share both limiter
|
||||
/// layers. A cached successful verification skips the limiter here as it does on gRPC (SEC-002).
|
||||
/// </remarks>
|
||||
public sealed class MetricsAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
@@ -50,6 +51,8 @@ public sealed class MetricsAuthenticationHandler(
|
||||
GatewayMetrics metrics)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
private readonly IApiKeyVerificationCache? _verificationCache = apiKeyVerifier as IApiKeyVerificationCache;
|
||||
|
||||
private bool _throttled;
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -61,10 +64,18 @@ public sealed class MetricsAuthenticationHandler(
|
||||
return await AuthenticateDashboardCookieAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
// Same order as the gRPC interceptor: a cached success (correct secret, no store read)
|
||||
// skips the limiter, so a spray against the key id cannot deny the scraper that holds it.
|
||||
if (_verificationCache is not null
|
||||
&& _verificationCache.TryGetCachedSuccess(authorizationHeader, out ApiKeyVerification? cached))
|
||||
{
|
||||
return Authenticated(cached);
|
||||
}
|
||||
|
||||
// Same throttle as the gRPC interceptor: checked before the store read so online guessing
|
||||
// against /metrics cannot spend a verification per attempt or bypass the gRPC limiter.
|
||||
ApiKeyThrottlePartition partition = new(
|
||||
Context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
|
||||
ApiKeyThrottlePeer.FromRemoteIp(Context.Connection.RemoteIpAddress),
|
||||
GatewayGrpcAuthorizationInterceptor.TryResolveKeyId(authorizationHeader));
|
||||
ApiKeyThrottleDecision decision = failureLimiter.Check(
|
||||
partition,
|
||||
@@ -86,8 +97,12 @@ public sealed class MetricsAuthenticationHandler(
|
||||
}
|
||||
|
||||
failureLimiter.Reset(partition, resolution);
|
||||
return Authenticated(verification);
|
||||
}
|
||||
|
||||
List<Claim> claims = [new Claim(ClaimTypes.Name, verification.Identity.KeyId)];
|
||||
private AuthenticateResult Authenticated(ApiKeyVerification verification)
|
||||
{
|
||||
List<Claim> claims = [new Claim(ClaimTypes.Name, verification.Identity!.KeyId)];
|
||||
foreach (string scope in verification.Identity.Scopes)
|
||||
{
|
||||
claims.Add(new Claim(MetricsAuthorizationDefaults.ScopeClaimType, scope));
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
using Grpc.Core;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// A <see cref="ServerCallContext"/> that forwards everything to the real call context except its
|
||||
/// cancellation token, which also fires when the caller's API key is revoked (SEC-004). Handlers
|
||||
/// already stop on <see cref="ServerCallContext.CancellationToken"/>, so they end a revoked stream
|
||||
/// without knowing about revocation.
|
||||
/// </summary>
|
||||
internal sealed class RevocableServerCallContext : ServerCallContext
|
||||
{
|
||||
// Grpc.AspNetCore's GetHttpContext() falls back to this user-state key for a ServerCallContext
|
||||
// that is not its own type; seeding it keeps that extension working through the wrapper.
|
||||
private const string HttpContextUserStateKey = "__HttpContext";
|
||||
|
||||
private readonly ServerCallContext _inner;
|
||||
private readonly CancellationToken _cancellationToken;
|
||||
|
||||
public RevocableServerCallContext(ServerCallContext inner, CancellationToken cancellationToken)
|
||||
{
|
||||
_inner = inner;
|
||||
_cancellationToken = cancellationToken;
|
||||
|
||||
try
|
||||
{
|
||||
HttpContext httpContext = inner.GetHttpContext();
|
||||
inner.UserState.TryAdd(HttpContextUserStateKey, httpContext);
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// Not hosted by ASP.NET Core (unit tests); nothing to forward.
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string MethodCore => _inner.Method;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string HostCore => _inner.Host;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override string PeerCore => _inner.Peer;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override DateTime DeadlineCore => _inner.Deadline;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Metadata RequestHeadersCore => _inner.RequestHeaders;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override CancellationToken CancellationTokenCore => _cancellationToken;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Metadata ResponseTrailersCore => _inner.ResponseTrailers;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Status StatusCore
|
||||
{
|
||||
get => _inner.Status;
|
||||
set => _inner.Status = value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override WriteOptions? WriteOptionsCore
|
||||
{
|
||||
get => _inner.WriteOptions;
|
||||
set => _inner.WriteOptions = value;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override AuthContext AuthContextCore => _inner.AuthContext;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override IDictionary<object, object> UserStateCore => _inner.UserState;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) =>
|
||||
_inner.CreatePropagationToken(options);
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) =>
|
||||
_inner.WriteResponseHeadersAsync(responseHeaders);
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.AspNetCore.Components.Routing;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
using Microsoft.AspNetCore.Components.Web.HtmlRendering;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.JSInterop;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
using ZB.MOM.WW.MxGateway.Server.Alarms;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard.Components;
|
||||
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
|
||||
using ZB.MOM.WW.Secrets.Ui;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// Proves the dashboard router enforces page <c>[Authorize]</c> attributes on in-circuit
|
||||
/// navigation (DSH-001, #243).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// A page's <c>[Authorize]</c> attribute is enforced by endpoint routing only on a full HTTP
|
||||
/// request. The dashboard router is interactive, so a navigation that starts inside an existing
|
||||
/// circuit (a click on an in-page link, or <c>Blazor.navigateTo</c> from the console) never issues
|
||||
/// an HTTP request: the in-circuit <c>Router</c> resolves the route and renders it. A plain
|
||||
/// <c>RouteView</c> does not evaluate <c>[Authorize]</c>; <c>AuthorizeRouteView</c> does.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// These tests render the production <see cref="Routes"/> component, park it on a page that has
|
||||
/// no attribute, then call <see cref="NavigationManager.NavigateTo(string, bool)"/> — the same
|
||||
/// <c>LocationChanged</c> path an in-circuit navigation drives. Each negative test asserts both
|
||||
/// that the gated page's markup is absent and that its data source was never called, so a page
|
||||
/// that rendered and then threw cannot pass for a gate.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The shared <c>ZB.MOM.WW.Secrets.Ui</c> page is not rendered for real: under the static
|
||||
/// <see cref="HtmlRenderer"/> its Theme-based markup overflows the HTML writer's stack in this
|
||||
/// harness, and its internals are not what is under test. A component activator substitutes a
|
||||
/// marker component when the router activates <see cref="SecretsPage"/>, so "activated" means
|
||||
/// exactly "the router decided to render the page".
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class DashboardRouteAuthorizationTests
|
||||
{
|
||||
private const string StartPath = "/route-authorization-test-start";
|
||||
private const string SecretsPageMarker = "secrets-page-activated";
|
||||
private const string AlarmsPageMarker = "Active Alarms";
|
||||
private const string NotAuthorizedMarker = "Not Authorized";
|
||||
|
||||
/// <summary>
|
||||
/// A Viewer is not granted <c>secrets:manage</c>. Navigating in-circuit to
|
||||
/// <c>/admin/secrets</c> must render the not-authorized content and must not list secrets.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Viewer_InCircuitNavigationToSecrets_IsNotAuthorized()
|
||||
{
|
||||
RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Viewer);
|
||||
await using (harness.ConfigureAwait(false))
|
||||
{
|
||||
string html = await harness.NavigateAsync("/admin/secrets");
|
||||
|
||||
Assert.DoesNotContain(SecretsPageMarker, html, StringComparison.Ordinal);
|
||||
Assert.Contains(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
||||
Assert.Equal(0, harness.Activator.SecretsPageActivations);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Control for the Viewer case: an Administrator satisfies <c>secrets:manage</c>, so the same
|
||||
/// in-circuit navigation renders the page and lists secrets. Without this, a router that
|
||||
/// rendered nothing at all would pass the negative test.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Administrator_InCircuitNavigationToSecrets_RendersPage()
|
||||
{
|
||||
RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Admin);
|
||||
await using (harness.ConfigureAwait(false))
|
||||
{
|
||||
string html = await harness.NavigateAsync("/admin/secrets");
|
||||
|
||||
Assert.Contains(SecretsPageMarker, html, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
||||
Assert.Equal(1, harness.Activator.SecretsPageActivations);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Anonymous localhost passes the endpoint <c>ViewerPolicy</c> but never the Alarms policy.
|
||||
/// In-circuit navigation to <c>/alarms</c> must not render the galaxy-wide alarm list or
|
||||
/// start its poll loop.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Anonymous_InCircuitNavigationToAlarms_IsNotAuthorized()
|
||||
{
|
||||
RouteHarness harness = await RouteHarness.StartAsync();
|
||||
await using (harness.ConfigureAwait(false))
|
||||
{
|
||||
string html = await harness.NavigateAsync("/alarms");
|
||||
|
||||
Assert.DoesNotContain(AlarmsPageMarker, html, StringComparison.Ordinal);
|
||||
Assert.Contains(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
||||
Assert.Equal(0, harness.LiveData.AlarmQueries);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Control for the anonymous case: an authenticated Viewer holds a real dashboard role and so
|
||||
/// satisfies the Alarms policy; the page renders and polls.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Viewer_InCircuitNavigationToAlarms_RendersPage()
|
||||
{
|
||||
RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Viewer);
|
||||
await using (harness.ConfigureAwait(false))
|
||||
{
|
||||
string html = await harness.NavigateAsync("/alarms");
|
||||
|
||||
Assert.Contains(AlarmsPageMarker, html, StringComparison.Ordinal);
|
||||
Assert.DoesNotContain(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
||||
Assert.True(harness.LiveData.AlarmQueries >= 1);
|
||||
}
|
||||
}
|
||||
|
||||
// Owns the service provider, the renderer and the rendered Routes root for one test.
|
||||
private sealed class RouteHarness : IAsyncDisposable
|
||||
{
|
||||
private readonly ServiceProvider _provider;
|
||||
private readonly HtmlRenderer _renderer;
|
||||
private readonly HtmlRootComponent _root;
|
||||
|
||||
private RouteHarness(
|
||||
ServiceProvider provider,
|
||||
HtmlRenderer renderer,
|
||||
HtmlRootComponent root,
|
||||
SecretsPageSubstitutingActivator activator,
|
||||
CountingLiveDataService liveData)
|
||||
{
|
||||
_provider = provider;
|
||||
_renderer = renderer;
|
||||
_root = root;
|
||||
Activator = activator;
|
||||
LiveData = liveData;
|
||||
}
|
||||
|
||||
public SecretsPageSubstitutingActivator Activator { get; }
|
||||
|
||||
public CountingLiveDataService LiveData { get; }
|
||||
|
||||
public static async Task<RouteHarness> StartAsync(params string[] roles)
|
||||
{
|
||||
SecretsPageSubstitutingActivator activator = new();
|
||||
CountingLiveDataService liveData = new();
|
||||
|
||||
ServiceCollection services = new();
|
||||
services.AddLogging();
|
||||
services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddSecretsAuthorization();
|
||||
options.AddPolicy(
|
||||
DashboardAuthenticationDefaults.AlarmsPolicy,
|
||||
policy => policy.AddRequirements(AuthenticatedDashboardRoleRequirement.AnyDashboardRole));
|
||||
});
|
||||
services.AddSingleton<IAuthorizationHandler, AuthenticatedDashboardRoleHandler>();
|
||||
services.AddCascadingAuthenticationState();
|
||||
services.AddSingleton<AuthenticationStateProvider>(new StubAuthenticationStateProvider(roles));
|
||||
services.AddSingleton<NavigationManager, InCircuitNavigationManager>();
|
||||
services.AddSingleton<INavigationInterception, NoOpNavigationInterception>();
|
||||
services.AddSingleton<IScrollToLocationHash, NoOpScrollToLocationHash>();
|
||||
services.AddSingleton<IJSRuntime, NoOpJsRuntime>();
|
||||
services.AddSingleton<IComponentActivator>(activator);
|
||||
services.AddSingleton<IDashboardLiveDataService>(liveData);
|
||||
services.AddSingleton<IGatewayAlarmService>(new FakeGatewayAlarmService());
|
||||
services.AddSingleton<IOptions<GatewayOptions>>(
|
||||
Options.Create(new GatewayOptions { Alarms = new AlarmsOptions { Enabled = true } }));
|
||||
|
||||
ServiceProvider provider = services.BuildServiceProvider();
|
||||
HtmlRenderer renderer = new(provider, provider.GetRequiredService<ILoggerFactory>());
|
||||
HtmlRootComponent root = await renderer.Dispatcher.InvokeAsync(
|
||||
() => renderer.RenderComponentAsync<Routes>());
|
||||
|
||||
return new RouteHarness(provider, renderer, root, activator, liveData);
|
||||
}
|
||||
|
||||
public async Task<string> NavigateAsync(string path)
|
||||
{
|
||||
NavigationManager navigation = _provider.GetRequiredService<NavigationManager>();
|
||||
await _renderer.Dispatcher.InvokeAsync(() => navigation.NavigateTo(path));
|
||||
|
||||
// The router re-renders asynchronously after LocationChanged; wait for the start
|
||||
// page's not-found content to be replaced before reading the markup.
|
||||
string html = string.Empty;
|
||||
await Eventually.WaitUntilAsync(
|
||||
async () =>
|
||||
{
|
||||
html = await _renderer.Dispatcher.InvokeAsync(_root.ToHtmlString);
|
||||
return !html.Contains("The requested dashboard page does not exist", StringComparison.Ordinal);
|
||||
},
|
||||
TimeSpan.FromSeconds(10),
|
||||
$"the router to leave the start page after navigating to {path}");
|
||||
return html;
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
await _renderer.DisposeAsync();
|
||||
await _provider.DisposeAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// A principal with an authentication type and role claims, or an unauthenticated one when no
|
||||
// roles are given (the anonymous-localhost shape).
|
||||
private sealed class StubAuthenticationStateProvider(string[] roles) : AuthenticationStateProvider
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public override Task<AuthenticationState> GetAuthenticationStateAsync()
|
||||
{
|
||||
ClaimsIdentity identity = roles.Length == 0
|
||||
? new ClaimsIdentity()
|
||||
: new ClaimsIdentity(
|
||||
roles.Select(role => new Claim(ZbClaimTypes.Role, role)),
|
||||
authenticationType: "Test",
|
||||
nameType: ZbClaimTypes.Name,
|
||||
roleType: ZbClaimTypes.Role);
|
||||
|
||||
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation stays in process: NavigateTo updates the URI and raises LocationChanged, which
|
||||
// is exactly what an in-circuit navigation does — no HTTP request, so no endpoint authorization.
|
||||
private sealed class InCircuitNavigationManager : NavigationManager
|
||||
{
|
||||
/// <summary>Initializes the manager on the attribute-free start path.</summary>
|
||||
public InCircuitNavigationManager() => Initialize("https://localhost/", $"https://localhost{StartPath}");
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void NavigateToCore(string uri, NavigationOptions options)
|
||||
{
|
||||
Uri = ToAbsoluteUri(uri).ToString();
|
||||
NotifyLocationChanged(isInterceptedLink: false);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class NoOpNavigationInterception : INavigationInterception
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task EnableNavigationInterceptionAsync() => Task.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class NoOpScrollToLocationHash : IScrollToLocationHash
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task RefreshScrollPositionForHash(string locationAbsolute) => Task.CompletedTask;
|
||||
}
|
||||
|
||||
private sealed class NoOpJsRuntime : IJSRuntime
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args) => default;
|
||||
|
||||
/// <inheritdoc />
|
||||
public ValueTask<TValue> InvokeAsync<TValue>(
|
||||
string identifier,
|
||||
CancellationToken cancellationToken,
|
||||
object?[]? args) => default;
|
||||
}
|
||||
|
||||
// Answers the Alarms page's poll with an empty result and counts the calls; a non-zero count
|
||||
// means the page initialized and started its galaxy-wide alarm loop.
|
||||
private sealed class CountingLiveDataService : IDashboardLiveDataService
|
||||
{
|
||||
private int _alarmQueries;
|
||||
|
||||
public int AlarmQueries => Volatile.Read(ref _alarmQueries);
|
||||
|
||||
public Task<DashboardLiveReadResult> ReadAsync(
|
||||
IReadOnlyCollection<string> tagAddresses,
|
||||
CancellationToken cancellationToken) =>
|
||||
Task.FromResult(DashboardLiveReadResult.Empty);
|
||||
|
||||
public async Task<DashboardAlarmQueryResult> QueryAlarmsAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Interlocked.Increment(ref _alarmQueries) > 1)
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
return new DashboardAlarmQueryResult(
|
||||
Alarms: [],
|
||||
Error: null,
|
||||
WorkerProcessId: null,
|
||||
SnapshotTruncated: false);
|
||||
}
|
||||
}
|
||||
|
||||
// Activates components normally, except SecretsPage, which it counts and replaces with a
|
||||
// marker. Renderer resolves IComponentActivator from the service provider.
|
||||
private sealed class SecretsPageSubstitutingActivator : IComponentActivator
|
||||
{
|
||||
private int _secretsPageActivations;
|
||||
|
||||
public int SecretsPageActivations => Volatile.Read(ref _secretsPageActivations);
|
||||
|
||||
/// <inheritdoc />
|
||||
public IComponent CreateInstance(Type componentType)
|
||||
{
|
||||
if (componentType == typeof(SecretsPage))
|
||||
{
|
||||
Interlocked.Increment(ref _secretsPageActivations);
|
||||
return new SecretsPageStandIn();
|
||||
}
|
||||
|
||||
return (IComponent)System.Activator.CreateInstance(componentType)!;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SecretsPageStandIn : ComponentBase
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder)
|
||||
{
|
||||
builder.AddMarkupContent(0, $"<p>{SecretsPageMarker}</p>");
|
||||
}
|
||||
}
|
||||
}
|
||||
+27
-2
@@ -335,7 +335,31 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
||||
Assert.Equal("API key pepper is not configured.", result.Message);
|
||||
}
|
||||
|
||||
private DashboardApiKeyManagementService CreateService(ServiceProvider services)
|
||||
/// <summary>
|
||||
/// SEC-004: revoking a key on the dashboard ends the streaming calls that key already has
|
||||
/// open, not only future calls.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RevokeAsync_AuthorizedUser_CancelsTheKeysOpenStreams()
|
||||
{
|
||||
await using ServiceProvider services = BuildServices();
|
||||
ApiKeyStreamRegistry registry = new();
|
||||
DashboardApiKeyManagementService service = CreateService(services, registry);
|
||||
await service.CreateAsync(CreateAuthorizedUser(), CreateRequest(), CancellationToken.None);
|
||||
using ApiKeyStreamRegistry.Registration revoked = registry.Register("operator01", CancellationToken.None);
|
||||
using ApiKeyStreamRegistry.Registration other = registry.Register("operator02", CancellationToken.None);
|
||||
|
||||
await service.RevokeAsync(CreateAuthorizedUser(), "operator01", CancellationToken.None);
|
||||
|
||||
Assert.True(revoked.IsRevoked);
|
||||
Assert.True(revoked.Token.IsCancellationRequested);
|
||||
Assert.False(other.Token.IsCancellationRequested);
|
||||
}
|
||||
|
||||
private DashboardApiKeyManagementService CreateService(
|
||||
ServiceProvider services,
|
||||
ApiKeyStreamRegistry? streamRegistry = null)
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
httpContext.Connection.RemoteIpAddress = System.Net.IPAddress.Loopback;
|
||||
@@ -346,7 +370,8 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
|
||||
services.GetRequiredService<IApiKeyAdminStore>(),
|
||||
services.GetRequiredService<ZB.MOM.WW.Auth.ApiKeys.IApiKeyPepperProvider>(),
|
||||
services.GetRequiredService<ZB.MOM.WW.Audit.IAuditWriter>(),
|
||||
new HttpContextAccessor { HttpContext = httpContext });
|
||||
new HttpContextAccessor { HttpContext = httpContext },
|
||||
streamRegistry: streamRegistry);
|
||||
}
|
||||
|
||||
private ServiceProvider BuildServices(string? pepper = "test-pepper")
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -689,6 +689,140 @@ public sealed class MxAccessGatewayServiceConstraintTests
|
||||
Assert.Equal("Secret.Tag", enforcer.RecordedDenials[0].Target);
|
||||
}
|
||||
|
||||
// === AddBufferedItem and the fail-closed command-kind switch (SES-003) ===
|
||||
|
||||
/// <summary>
|
||||
/// <c>AddBufferedItem</c> names a tag like the other adds, so an out-of-scope tag is
|
||||
/// refused with <see cref="StatusCode.PermissionDenied"/>, the denial is audited, and the
|
||||
/// worker never sees the command.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Invoke_AddBufferedItem_WithDeniedTag_ThrowsPermissionDeniedAndDoesNotCallWorker()
|
||||
{
|
||||
PredicateConstraintEnforcer enforcer = new()
|
||||
{
|
||||
DenyTag = tag => tag == "AreaB.Tank.Level",
|
||||
};
|
||||
FakeSessionManager sessionManager = CreateSessionManagerWithSeed();
|
||||
MxAccessGatewayService service = CreateService(sessionManager, enforcer);
|
||||
|
||||
MxCommandRequest request = new()
|
||||
{
|
||||
SessionId = SessionId,
|
||||
ClientCorrelationId = "corr-buffered",
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AddBufferedItem,
|
||||
AddBufferedItem = new AddBufferedItemCommand { ServerHandle = 7, ItemDefinition = "AreaB.Tank.Level" },
|
||||
},
|
||||
};
|
||||
|
||||
RpcException exception = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(request, new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode);
|
||||
Assert.Equal(0, sessionManager.InvokeCount);
|
||||
(string commandKind, string target, string? correlationId) = Assert.Single(enforcer.RecordedDenials);
|
||||
Assert.Equal(nameof(MxCommandKind.AddBufferedItem), commandKind);
|
||||
Assert.Equal("AreaB.Tank.Level", target);
|
||||
Assert.Equal("corr-buffered", correlationId);
|
||||
}
|
||||
|
||||
/// <summary>An in-scope <c>AddBufferedItem</c> still reaches the worker.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Invoke_AddBufferedItem_WithAllowedTag_ReachesWorker()
|
||||
{
|
||||
PredicateConstraintEnforcer enforcer = new()
|
||||
{
|
||||
DenyTag = tag => tag == "AreaB.Tank.Level",
|
||||
};
|
||||
FakeSessionManager sessionManager = CreateSessionManagerWithSeed();
|
||||
MxAccessGatewayService service = CreateService(sessionManager, enforcer);
|
||||
|
||||
await service.Invoke(
|
||||
new MxCommandRequest
|
||||
{
|
||||
SessionId = SessionId,
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AddBufferedItem,
|
||||
AddBufferedItem = new AddBufferedItemCommand { ServerHandle = 7, ItemDefinition = "AreaA.Tank.Level" },
|
||||
},
|
||||
},
|
||||
new TestServerCallContext());
|
||||
|
||||
Assert.Equal(1, sessionManager.InvokeCount);
|
||||
Assert.Empty(enforcer.RecordedDenials);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Every <see cref="MxCommandKind"/> is classified exactly once: constraint-checked,
|
||||
/// on the no-tag allow-list, or one of the gateway-internal alarm kinds the switch
|
||||
/// refuses. A new contract value fails this test until someone decides whether it
|
||||
/// carries a tag; at runtime an unclassified kind is refused, not passed through.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void EveryCommandKind_IsClassifiedExactlyOnceForConstraintEnforcement()
|
||||
{
|
||||
HashSet<MxCommandKind> refusedOnInvoke =
|
||||
[
|
||||
MxCommandKind.SubscribeAlarms,
|
||||
MxCommandKind.UnsubscribeAlarms,
|
||||
MxCommandKind.AcknowledgeAlarm,
|
||||
MxCommandKind.QueryActiveAlarms,
|
||||
MxCommandKind.AcknowledgeAlarmByName,
|
||||
MxCommandKind.UpdateAlarmWatchList,
|
||||
];
|
||||
|
||||
foreach (MxCommandKind kind in Enum.GetValues<MxCommandKind>())
|
||||
{
|
||||
if (kind == MxCommandKind.Unspecified)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
int classifications =
|
||||
(MxAccessGatewayService.ConstrainedCommandKinds.Contains(kind) ? 1 : 0)
|
||||
+ (MxAccessGatewayService.UnconstrainedCommandKinds.Contains(kind) ? 1 : 0)
|
||||
+ (refusedOnInvoke.Contains(kind) ? 1 : 0);
|
||||
Assert.True(classifications == 1, $"MxCommandKind.{kind} is classified {classifications} times; expected exactly once.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A kind on neither list — a gateway-internal alarm kind, or a value the switch has never
|
||||
/// seen — is refused with <see cref="StatusCode.PermissionDenied"/> and an audited denial
|
||||
/// even for an unconstrained key, and never reaches the worker.
|
||||
/// </summary>
|
||||
/// <param name="kindValue">Numeric <see cref="MxCommandKind"/> value.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData((int)MxCommandKind.SubscribeAlarms)]
|
||||
[InlineData((int)MxCommandKind.UpdateAlarmWatchList)]
|
||||
[InlineData((int)MxCommandKind.AcknowledgeAlarmByName)]
|
||||
[InlineData(999)]
|
||||
public async Task Invoke_UnclassifiedCommandKind_FailsClosed(int kindValue)
|
||||
{
|
||||
PredicateConstraintEnforcer enforcer = new();
|
||||
FakeSessionManager sessionManager = CreateSessionManagerWithSeed();
|
||||
MxAccessGatewayService service = CreateService(sessionManager, enforcer);
|
||||
|
||||
RpcException exception = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(
|
||||
new MxCommandRequest
|
||||
{
|
||||
SessionId = SessionId,
|
||||
Command = new MxCommand { Kind = (MxCommandKind)kindValue },
|
||||
},
|
||||
new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode);
|
||||
Assert.Equal(0, sessionManager.InvokeCount);
|
||||
Assert.Single(enforcer.RecordedDenials);
|
||||
}
|
||||
|
||||
// === Helpers ===
|
||||
|
||||
private static MxAccessGatewayService CreateService(
|
||||
|
||||
@@ -722,6 +722,127 @@ public sealed class MxAccessGatewayServiceTests
|
||||
Assert.Equal(expectedReason, exception.Trailers.GetValue(ResourceExhaustedReasons.TrailerKey));
|
||||
}
|
||||
|
||||
// === Owner-scoped session RPCs (SES-002, #241) ===
|
||||
|
||||
/// <summary>
|
||||
/// A foreign key — even one holding <c>admin</c> — cannot drain, write through or close
|
||||
/// another key's session: each call is refused with <c>PermissionDenied</c> before the
|
||||
/// session manager is reached, and the owner's session stays <c>Ready</c>.
|
||||
/// </summary>
|
||||
/// <param name="foreignScope">Scope the foreign key holds.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(GatewayScopes.EventsRead)]
|
||||
[InlineData(GatewayScopes.Admin)]
|
||||
public async Task SessionRpcs_FromForeignKey_ThrowPermissionDeniedAndLeaveSessionReady(string foreignScope)
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
GatewaySession ownedSession = CreateOwnedSession("session-owned", ownerKeyId: "key-a");
|
||||
sessionManager.SeedSession(ownedSession);
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("key-b", foreignScope));
|
||||
|
||||
MxCommandRequest drain = new()
|
||||
{
|
||||
SessionId = "session-owned",
|
||||
Command = new MxCommand { Kind = MxCommandKind.DrainEvents, DrainEvents = new DrainEventsCommand() },
|
||||
};
|
||||
MxCommandRequest write = new()
|
||||
{
|
||||
SessionId = "session-owned",
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.Write,
|
||||
Write = new WriteCommand { ServerHandle = 1, ItemHandle = 2, Value = new MxValue { StringValue = "v" } },
|
||||
},
|
||||
};
|
||||
|
||||
RpcException drainException = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(drain, new TestServerCallContext()));
|
||||
RpcException writeException = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(write, new TestServerCallContext()));
|
||||
RpcException closeException = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.CloseSession(
|
||||
new CloseSessionRequest { SessionId = "session-owned" },
|
||||
new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, drainException.StatusCode);
|
||||
Assert.Equal(StatusCode.PermissionDenied, writeException.StatusCode);
|
||||
Assert.Equal(StatusCode.PermissionDenied, closeException.StatusCode);
|
||||
Assert.Equal(0, sessionManager.InvokeCount);
|
||||
Assert.Equal(0, sessionManager.CloseCount);
|
||||
Assert.Equal(SessionState.Ready, ownedSession.State);
|
||||
}
|
||||
|
||||
/// <summary>The owning key still reaches Invoke and CloseSession on its own session.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SessionRpcs_FromOwnerKey_ReachSessionManager()
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
sessionManager.SeedSession(CreateOwnedSession("session-owned", ownerKeyId: "key-a"));
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("key-a", GatewayScopes.InvokeRead));
|
||||
|
||||
await service.Invoke(CreatePingRequest("session-owned"), new TestServerCallContext());
|
||||
CloseSessionReply reply = await service.CloseSession(
|
||||
new CloseSessionRequest { SessionId = "session-owned" },
|
||||
new TestServerCallContext());
|
||||
|
||||
Assert.Equal(1, sessionManager.InvokeCount);
|
||||
Assert.Equal(1, sessionManager.CloseCount);
|
||||
Assert.Equal("session-owned", reply.SessionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The owner compare is ordinal: a key id that differs only by case is a different key.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Invoke_FromKeyDifferingOnlyByCase_ThrowsPermissionDenied()
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
sessionManager.SeedSession(CreateOwnedSession("session-owned", ownerKeyId: "key-a"));
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("KEY-A", GatewayScopes.InvokeRead));
|
||||
|
||||
RpcException exception = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(CreatePingRequest("session-owned"), new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode);
|
||||
Assert.Equal(0, sessionManager.InvokeCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An authenticated key cannot act on a session opened with authentication disabled (a
|
||||
/// <see langword="null"/> owner matches only a <see langword="null"/> caller).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CloseSession_OnUnownedSessionFromAuthenticatedKey_ThrowsPermissionDenied()
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
sessionManager.SeedSession(CreateOwnedSession("session-unowned", ownerKeyId: null));
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("key-b", GatewayScopes.SessionClose));
|
||||
|
||||
RpcException exception = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.CloseSession(
|
||||
new CloseSessionRequest { SessionId = "session-unowned" },
|
||||
new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode);
|
||||
Assert.Equal(0, sessionManager.CloseCount);
|
||||
}
|
||||
|
||||
private static MxAccessGatewayService CreateService(
|
||||
FakeSessionManager sessionManager,
|
||||
IGatewayRequestIdentityAccessor? identityAccessor = null,
|
||||
@@ -752,6 +873,37 @@ public sealed class MxAccessGatewayServiceTests
|
||||
Scopes: new HashSet<string>(StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
private static ApiKeyIdentity CreateIdentity(string keyId, string scope)
|
||||
{
|
||||
return new ApiKeyIdentity(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: $"mxgw_{keyId}",
|
||||
DisplayName: keyId,
|
||||
Scopes: new HashSet<string>([scope], StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
private static GatewaySession CreateOwnedSession(string sessionId, string? ownerKeyId)
|
||||
{
|
||||
GatewaySession session = new(
|
||||
sessionId,
|
||||
GatewayContractInfo.DefaultBackendName,
|
||||
"pipe",
|
||||
"nonce",
|
||||
"Owner Key",
|
||||
ownerKeyId,
|
||||
"operator-session",
|
||||
"client-correlation",
|
||||
TimeSpan.FromSeconds(7),
|
||||
TimeSpan.FromSeconds(30),
|
||||
TimeSpan.FromSeconds(10),
|
||||
TimeSpan.FromMinutes(5),
|
||||
DateTimeOffset.UtcNow);
|
||||
session.AttachWorkerClient(new FakeWorkerClient(1234));
|
||||
session.MarkReady();
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
private static GatewaySession CreateSession(
|
||||
string sessionId,
|
||||
int processId)
|
||||
@@ -860,6 +1012,9 @@ public sealed class MxAccessGatewayServiceTests
|
||||
/// <summary>The number of times InvokeAsync was called.</summary>
|
||||
public int InvokeCount { get; private set; }
|
||||
|
||||
/// <summary>The number of times CloseSessionAsync was called.</summary>
|
||||
public int CloseCount { get; private set; }
|
||||
|
||||
/// <summary>The events the fake event stream service replays for this manager.</summary>
|
||||
public List<WorkerEvent> Events { get; } = [];
|
||||
|
||||
@@ -940,6 +1095,7 @@ public sealed class MxAccessGatewayServiceTests
|
||||
string sessionId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
CloseCount++;
|
||||
return Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false));
|
||||
}
|
||||
|
||||
|
||||
@@ -313,18 +313,21 @@ public sealed class ApiKeyFailureLimiterTests
|
||||
Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(partition));
|
||||
}
|
||||
|
||||
/// <summary>A successful verification clears both the composite partition and the key aggregate.</summary>
|
||||
/// <summary>
|
||||
/// A successful verification clears the caller's own partition and exempts that address from
|
||||
/// the key's aggregate, but leaves the aggregate in place for every other address (SEC-003).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Reset_ClearsCompositeAndAggregateLayers()
|
||||
public void Reset_ClearsOwnPartitionAndLeavesAggregateForOtherAddresses()
|
||||
{
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3, aggregateLimit: 5);
|
||||
ApiKeyThrottlePartition partition = new("ipv4:10.0.0.1:1", "victim");
|
||||
ApiKeyThrottlePartition partition = new("10.0.0.1", "victim");
|
||||
|
||||
RecordFailures(limiter, partition, 3);
|
||||
for (int peer = 1; peer < 3; peer++)
|
||||
{
|
||||
limiter.RecordFailure(new ApiKeyThrottlePartition($"ipv4:10.0.1.{peer}:1", "victim"));
|
||||
limiter.RecordFailure(new ApiKeyThrottlePartition($"10.0.1.{peer}", "victim"));
|
||||
}
|
||||
|
||||
Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(partition));
|
||||
@@ -332,10 +335,56 @@ public sealed class ApiKeyFailureLimiterTests
|
||||
limiter.Reset(partition);
|
||||
|
||||
Assert.Equal(ApiKeyThrottleDecision.Allowed, limiter.Check(partition));
|
||||
Assert.Equal(0, limiter.TrackedAggregateCount);
|
||||
Assert.Equal(1, limiter.TrackedAggregateCount);
|
||||
Assert.Equal(
|
||||
ApiKeyThrottleDecision.Allowed,
|
||||
limiter.Check(new ApiKeyThrottlePartition("ipv4:10.0.9.9:1", "victim")));
|
||||
ApiKeyThrottleDecision.ThrottledByAggregate,
|
||||
limiter.Check(new ApiKeyThrottlePartition("10.0.9.9", "victim")));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-003: a key in steady use from its holder still accrues cross-peer failures. One success
|
||||
/// between every failure used to wipe the aggregate, so it never reached its limit.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Aggregate_InterleavedWithHolderSuccesses_StillTrips()
|
||||
{
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30);
|
||||
ApiKeyThrottlePartition holder = new("198.51.100.4", "victim");
|
||||
|
||||
for (int i = 0; i < 30; i++)
|
||||
{
|
||||
limiter.RecordFailure(new ApiKeyThrottlePartition($"203.0.113.{i}", "victim"));
|
||||
Assert.NotEqual(ApiKeyThrottleDecision.ThrottledByAggregate, limiter.Check(holder));
|
||||
limiter.Reset(holder);
|
||||
}
|
||||
|
||||
Assert.Equal(
|
||||
ApiKeyThrottleDecision.ThrottledByAggregate,
|
||||
limiter.Check(new ApiKeyThrottlePartition("203.0.113.200", "victim")));
|
||||
Assert.Equal(ApiKeyThrottleDecision.Allowed, limiter.Check(holder));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The verified exemption lasts one window: once it ages out, an address with no fresh success
|
||||
/// is subject to a still-tripped aggregate like any other.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void VerifiedExemption_ExpiresWithTheWindow()
|
||||
{
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 3);
|
||||
ApiKeyThrottlePartition holder = new("198.51.100.4", "victim");
|
||||
|
||||
limiter.Reset(holder);
|
||||
clock.Advance(Window);
|
||||
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
limiter.RecordFailure(new ApiKeyThrottlePartition($"203.0.113.{i}", "victim"));
|
||||
}
|
||||
|
||||
Assert.Equal(ApiKeyThrottleDecision.ThrottledByAggregate, limiter.Check(holder));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
using System.Net;
|
||||
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// Pins the address normalisation shared by the gRPC interceptor and the <c>/metrics</c> handler
|
||||
/// (SEC-001): the source port never reaches the limiter partition, and both surfaces produce the
|
||||
/// same string for the same client.
|
||||
/// </summary>
|
||||
public sealed class ApiKeyThrottlePeerTests
|
||||
{
|
||||
/// <summary>Strips the port from each Grpc.AspNetCore peer form.</summary>
|
||||
/// <param name="grpcPeer">The <c>ServerCallContext.Peer</c> value.</param>
|
||||
/// <param name="expected">The expected address.</param>
|
||||
[Theory]
|
||||
[InlineData("ipv4:203.0.113.7:40001", "203.0.113.7")]
|
||||
[InlineData("ipv4:127.0.0.1:5000", "127.0.0.1")]
|
||||
[InlineData("ipv6:[::1]:5000", "::1")]
|
||||
[InlineData("ipv6:[2001:db8::7]:40001", "2001:db8::7")]
|
||||
[InlineData("ipv6:[::ffff:203.0.113.7]:40001", "203.0.113.7")]
|
||||
public void FromGrpcPeer_StripsPort(string grpcPeer, string expected)
|
||||
{
|
||||
Assert.Equal(expected, ApiKeyThrottlePeer.FromGrpcPeer(grpcPeer));
|
||||
}
|
||||
|
||||
/// <summary>A peer with no address/port shape is kept verbatim rather than guessed at.</summary>
|
||||
/// <param name="grpcPeer">The <c>ServerCallContext.Peer</c> value.</param>
|
||||
[Theory]
|
||||
[InlineData("unknown")]
|
||||
[InlineData("unix:/tmp/mxgw.sock")]
|
||||
[InlineData("ipv6:[not-an-address]:1")]
|
||||
public void FromGrpcPeer_KeepsUnrecognisedForms(string grpcPeer)
|
||||
{
|
||||
Assert.Equal(grpcPeer, ApiKeyThrottlePeer.FromGrpcPeer(grpcPeer));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The gRPC and HTTP surfaces agree, so a failure counted on one is charged to the same
|
||||
/// partition on the other — including an IPv4 client seen through a dual-stack listener.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void FromRemoteIp_MatchesGrpcPeerForm()
|
||||
{
|
||||
Assert.Equal(
|
||||
ApiKeyThrottlePeer.FromGrpcPeer("ipv4:203.0.113.7:40001"),
|
||||
ApiKeyThrottlePeer.FromRemoteIp(IPAddress.Parse("::ffff:203.0.113.7")));
|
||||
Assert.Equal("unknown", ApiKeyThrottlePeer.FromRemoteIp(null));
|
||||
}
|
||||
}
|
||||
+306
-3
@@ -406,6 +406,287 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
|
||||
Assert.Equal(3, verifier.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-001: the partition is the remote IP, not the TCP connection. Failures from two
|
||||
/// connections of one address (different ephemeral source ports) share one partition, so
|
||||
/// reconnecting does not reset the count: nine failures on each connection trip the limit of
|
||||
/// ten and the eleventh attempt overall is throttled without reaching the verifier.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Failures_FromSameAddressOnDifferentSourcePorts_ShareOnePartition()
|
||||
{
|
||||
CountingFailureVerifier verifier = new(Failure(ApiKeyFailure.SecretMismatch));
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10);
|
||||
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
|
||||
verifier,
|
||||
new GatewayRequestIdentityAccessor(),
|
||||
failureLimiter: limiter);
|
||||
|
||||
List<StatusCode> statuses = [];
|
||||
foreach (string peer in new[] { "ipv4:203.0.113.7:40001", "ipv4:203.0.113.7:40002" })
|
||||
{
|
||||
for (int attempt = 0; attempt < 9; attempt++)
|
||||
{
|
||||
RpcException failure = await Assert.ThrowsAsync<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_bad-secret", peer),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
statuses.Add(failure.StatusCode);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.All(statuses.Take(10), status => Assert.Equal(StatusCode.Unauthenticated, status));
|
||||
Assert.Equal(StatusCode.ResourceExhausted, statuses[10]);
|
||||
Assert.Equal(10, verifier.CallCount);
|
||||
Assert.Equal(1, limiter.TrackedPartitionCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-001, junk-token path: tokens with no key id fall back to the address partition, and that
|
||||
/// partition must also survive a reconnect, or junk spraying would never be throttled.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task JunkTokens_FromSameAddressOnDifferentSourcePorts_AreThrottled()
|
||||
{
|
||||
CountingFailureVerifier verifier = new(Failure(ApiKeyFailure.MissingOrMalformed));
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3);
|
||||
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
|
||||
verifier,
|
||||
new GatewayRequestIdentityAccessor(),
|
||||
failureLimiter: limiter);
|
||||
|
||||
StatusCode last = StatusCode.OK;
|
||||
for (int port = 50000; port < 50004; port++)
|
||||
{
|
||||
RpcException failure = await Assert.ThrowsAsync<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer garbage", $"ipv6:[2001:db8::7]:{port}"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
last = failure.StatusCode;
|
||||
}
|
||||
|
||||
Assert.Equal(StatusCode.ResourceExhausted, last);
|
||||
Assert.Equal(3, verifier.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-002: a holder whose verification is cached is never refused by a spray against its key
|
||||
/// id. Thirty bad secrets from thirty addresses trip the aggregate; the holder's next call —
|
||||
/// inside the cache TTL and inside the probe interval — is served from the cache without
|
||||
/// consulting the limiter, even from an address that never verified before.
|
||||
/// </summary>
|
||||
/// <param name="holderPeer">Address the holder calls from after the spray.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(HolderPeer)]
|
||||
[InlineData("ipv4:192.0.2.55:41000")]
|
||||
public async Task CachedHolder_AfterAggregateSpray_IsNotThrottled(string holderPeer)
|
||||
{
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30);
|
||||
SecretMatchingVerifier inner = new("correct");
|
||||
using Microsoft.Extensions.Caching.Memory.MemoryCache cache = new(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions());
|
||||
CachingApiKeyVerifier verifier = new(inner, cache, TimeSpan.FromMinutes(5));
|
||||
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
|
||||
verifier,
|
||||
new GatewayRequestIdentityAccessor(),
|
||||
failureLimiter: limiter);
|
||||
|
||||
await interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_correct", HolderPeer),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply()));
|
||||
|
||||
for (int peer = 0; peer < 30; peer++)
|
||||
{
|
||||
await Assert.ThrowsAsync<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
}
|
||||
|
||||
RpcException sprayer = await Assert.ThrowsAsync<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_guess", "ipv4:203.0.113.250:5000"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
Assert.Equal(StatusCode.ResourceExhausted, sprayer.StatusCode);
|
||||
|
||||
int innerCallsBefore = inner.CallCount;
|
||||
OpenSessionReply reply = await interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_correct", holderPeer),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply { SessionId = "session-1" }));
|
||||
|
||||
Assert.Equal("session-1", reply.SessionId);
|
||||
Assert.Equal(innerCallsBefore, inner.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-002 without a cache hit (TTL expired, or a non-caching verifier): an address that
|
||||
/// verified the key inside the window is exempt from the tripped aggregate, so it still reaches
|
||||
/// the verifier instead of competing with the sprayer for the probe slot.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task RecentlyVerifiedHolder_OnCacheMiss_IsExemptFromTrippedAggregate()
|
||||
{
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30);
|
||||
SecretMatchingVerifier verifier = new("correct");
|
||||
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
|
||||
verifier,
|
||||
new GatewayRequestIdentityAccessor(),
|
||||
failureLimiter: limiter);
|
||||
|
||||
await interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_correct", HolderPeer),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply()));
|
||||
|
||||
for (int peer = 0; peer < 31; peer++)
|
||||
{
|
||||
await Assert.ThrowsAsync<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
}
|
||||
|
||||
for (int call = 0; call < 3; call++)
|
||||
{
|
||||
OpenSessionReply reply = await interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_correct", "ipv4:198.51.100.4:6000"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply { SessionId = "session-1" }));
|
||||
Assert.Equal("session-1", reply.SessionId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-003 end to end: one holder success between every bad guess no longer wipes the
|
||||
/// aggregate, so after thirty guesses from thirty addresses a new address is throttled.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task ActiveKey_InterleavedWithSpray_StillAccruesAggregate()
|
||||
{
|
||||
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
|
||||
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30);
|
||||
SecretMatchingVerifier verifier = new("correct");
|
||||
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
|
||||
verifier,
|
||||
new GatewayRequestIdentityAccessor(),
|
||||
failureLimiter: limiter);
|
||||
|
||||
for (int peer = 0; peer < 30; peer++)
|
||||
{
|
||||
await interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_correct", HolderPeer),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply()));
|
||||
await Assert.ThrowsAsync<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
}
|
||||
|
||||
int verifierCallsBefore = verifier.CallCount;
|
||||
RpcException throttled = await Assert.ThrowsAsync<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_guess", "ipv4:203.0.113.250:5000"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
|
||||
Assert.Equal(StatusCode.ResourceExhausted, throttled.StatusCode);
|
||||
Assert.Equal(verifierCallsBefore, verifier.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// SEC-004: revoking a key mid-stream ends the open streaming call with
|
||||
/// <see cref="StatusCode.Unauthenticated"/>, whatever status the handler maps its cancellation
|
||||
/// to, and releases the registration.
|
||||
/// </summary>
|
||||
/// <param name="handlerMapsCancellation">Whether the handler converts its cancellation to an RpcException(Cancelled), as the gateway services do.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task RevokeKey_MidStream_EndsStreamWithUnauthenticated(bool handlerMapsCancellation)
|
||||
{
|
||||
ApiKeyStreamRegistry registry = new();
|
||||
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
|
||||
new FakeApiKeyVerifier(SuccessWithScopes(GatewayScopes.EventsRead)),
|
||||
new GatewayRequestIdentityAccessor(),
|
||||
streamRegistry: registry);
|
||||
TaskCompletionSource streaming = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
Task call = interceptor.ServerStreamingServerHandler(
|
||||
new StreamEventsRequest { SessionId = "session-1" },
|
||||
new RecordingServerStreamWriter<MxEvent>(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_secret"),
|
||||
async (_, _, context) =>
|
||||
{
|
||||
streaming.SetResult();
|
||||
try
|
||||
{
|
||||
await Task.Delay(Timeout.Infinite, context.CancellationToken);
|
||||
}
|
||||
catch (OperationCanceledException) when (handlerMapsCancellation)
|
||||
{
|
||||
throw new RpcException(new Status(StatusCode.Cancelled, "gRPC request was canceled."));
|
||||
}
|
||||
});
|
||||
|
||||
await streaming.Task.WaitAsync(TimeSpan.FromSeconds(10));
|
||||
Assert.Equal(1, registry.CountFor("operator01"));
|
||||
|
||||
Assert.Equal(0, registry.Revoke("someone-else"));
|
||||
Assert.False(call.IsCompleted);
|
||||
Assert.Equal(1, registry.Revoke("operator01"));
|
||||
|
||||
RpcException exception = await Assert.ThrowsAsync<RpcException>(() => call.WaitAsync(TimeSpan.FromSeconds(10)));
|
||||
Assert.Equal(StatusCode.Unauthenticated, exception.StatusCode);
|
||||
Assert.Equal(0, registry.CountFor("operator01"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A stream that ends on its own is not reported as revoked, and the handler sees the real
|
||||
/// call's metadata through the revocable context.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task StreamingCall_WithoutRevocation_CompletesNormallyAndUnregisters()
|
||||
{
|
||||
ApiKeyStreamRegistry registry = new();
|
||||
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
|
||||
new FakeApiKeyVerifier(SuccessWithScopes(GatewayScopes.EventsRead)),
|
||||
new GatewayRequestIdentityAccessor(),
|
||||
streamRegistry: registry);
|
||||
string? seenPeer = null;
|
||||
|
||||
await interceptor.ServerStreamingServerHandler(
|
||||
new StreamEventsRequest { SessionId = "session-1" },
|
||||
new RecordingServerStreamWriter<MxEvent>(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_secret", HolderPeer),
|
||||
(_, _, context) =>
|
||||
{
|
||||
seenPeer = context.Peer;
|
||||
return Task.CompletedTask;
|
||||
});
|
||||
|
||||
Assert.Equal(HolderPeer, seenPeer);
|
||||
Assert.Equal(0, registry.CountFor("operator01"));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lockout inversion: an attacker who floods failures for a victim's key id from its
|
||||
/// own address must not deny that key to the legitimate holder. The holder presents the correct
|
||||
@@ -609,7 +890,7 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
|
||||
}
|
||||
|
||||
Assert.Equal(1, limiter.TrackedPartitionCount);
|
||||
Assert.True(limiter.IsTracked(new ApiKeyThrottlePartition(AttackerPeer, KeyId: null)));
|
||||
Assert.True(limiter.IsTracked(new ApiKeyThrottlePartition(ApiKeyThrottlePeer.FromGrpcPeer(AttackerPeer), KeyId: null)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -882,7 +1163,8 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
|
||||
IApiKeyVerifier apiKeyVerifier,
|
||||
IGatewayRequestIdentityAccessor identityAccessor,
|
||||
AuthenticationMode authenticationMode = AuthenticationMode.ApiKey,
|
||||
ApiKeyFailureLimiter? failureLimiter = null)
|
||||
ApiKeyFailureLimiter? failureLimiter = null,
|
||||
ApiKeyStreamRegistry? streamRegistry = null)
|
||||
{
|
||||
return new GatewayGrpcAuthorizationInterceptor(
|
||||
apiKeyVerifier,
|
||||
@@ -896,7 +1178,8 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
|
||||
}
|
||||
}),
|
||||
failureLimiter ?? CreateLimiter(TimeProvider.System, limit: 1000),
|
||||
new GatewayMetrics());
|
||||
new GatewayMetrics(),
|
||||
streamRegistry);
|
||||
}
|
||||
|
||||
private static ApiKeyFailureLimiter CreateLimiter(
|
||||
@@ -1055,6 +1338,26 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
|
||||
}
|
||||
}
|
||||
|
||||
// Succeeds (with session:open) only for a token whose secret is the configured one; every
|
||||
// other token fails as a secret mismatch. Counts calls so a test can tell a cache hit or a
|
||||
// throttle from a real verification.
|
||||
private sealed class SecretMatchingVerifier(string correctSecret) : IApiKeyVerifier
|
||||
{
|
||||
private int _callCount;
|
||||
|
||||
/// <summary>Gets the number of verifications performed.</summary>
|
||||
public int CallCount => Volatile.Read(ref _callCount);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<ApiKeyVerification> VerifyAsync(string authorizationHeader, CancellationToken ct)
|
||||
{
|
||||
Interlocked.Increment(ref _callCount);
|
||||
return Task.FromResult(authorizationHeader.EndsWith("_" + correctSecret, StringComparison.Ordinal)
|
||||
? SuccessWithScopes(GatewayScopes.SessionOpen)
|
||||
: Failure(ApiKeyFailure.SecretMismatch));
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FakeApiKeyVerifier(ApiKeyVerification result) : IApiKeyVerifier
|
||||
{
|
||||
/// <summary>Gets whether the verifier was called.</summary>
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
using Grpc.Core;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization;
|
||||
|
||||
/// <summary>
|
||||
/// The context handed to streaming handlers (SEC-004) must behave as the real call context in
|
||||
/// every respect except its cancellation token.
|
||||
/// </summary>
|
||||
public sealed class RevocableServerCallContextTests
|
||||
{
|
||||
/// <summary>Metadata, status, trailers, user state and the HttpContext all pass through.</summary>
|
||||
[Fact]
|
||||
public void Wrapper_ForwardsEverythingButCancellation()
|
||||
{
|
||||
DefaultHttpContext httpContext = new();
|
||||
TestServerCallContext inner = new(
|
||||
[new Metadata.Entry("x-test", "1")],
|
||||
peer: "ipv4:192.0.2.1:5000");
|
||||
inner.UserState["__HttpContext"] = httpContext;
|
||||
using CancellationTokenSource revocation = new();
|
||||
|
||||
RevocableServerCallContext wrapper = new(inner, revocation.Token);
|
||||
wrapper.Status = new Status(StatusCode.Unauthenticated, "revoked");
|
||||
wrapper.ResponseTrailers.Add("x-trailer", "2");
|
||||
|
||||
Assert.Equal("ipv4:192.0.2.1:5000", wrapper.Peer);
|
||||
Assert.Equal("1", wrapper.RequestHeaders.GetValue("x-test"));
|
||||
Assert.Equal(StatusCode.Unauthenticated, inner.Status.StatusCode);
|
||||
Assert.Equal("2", inner.ResponseTrailers.GetValue("x-trailer"));
|
||||
Assert.Same(httpContext, wrapper.GetHttpContext());
|
||||
|
||||
Assert.False(wrapper.CancellationToken.IsCancellationRequested);
|
||||
revocation.Cancel();
|
||||
Assert.True(wrapper.CancellationToken.IsCancellationRequested);
|
||||
Assert.False(inner.CancellationToken.IsCancellationRequested);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user