diff --git a/docs/Authentication.md b/docs/Authentication.md
index b8c13234..5c0b2d3a 100644
--- a/docs/Authentication.md
+++ b/docs/Authentication.md
@@ -104,7 +104,12 @@ library:
it after writing the cache entry (set-then-recheck); a revoke that lands while a
verification is still in flight in the inner library therefore discards that
verification's repopulation instead of re-caching the just-revoked identity for a
- full TTL (SEC-34). The short TTL remains the backstop for two bounded-staleness
+ full TTL (SEC-34). The same revoke/rotate/delete also calls
+ `ApiKeyStreamRegistry.Revoke(keyId)`, which ends every streaming call the key
+ already has open (SEC-004): a streaming call is authenticated once, at open, so
+ evicting the cache alone left an open `StreamEvents`, `StreamAlarms` or
+ `WatchDeployEvents` delivering data until the client disconnected. See
+ [Authorization](./Authorization.md#streaming-calls-and-revocation). The short TTL remains the backstop for two bounded-staleness
windows it cannot close directly: (1) out-of-band mutations (a direct DB edit, or a
revoke run by the separate `apikey` CLI process, whose in-memory cache is not the
running gateway's cache); and (2) a key whose `ExpiresUtc` passes while cached keeps
diff --git a/docs/Authorization.md b/docs/Authorization.md
index ca4ada35..59439b54 100644
--- a/docs/Authorization.md
+++ b/docs/Authorization.md
@@ -105,6 +105,26 @@ Two rules keep the holder of the correct secret from being denied by a spray aga
The dashboard login surface is throttled independently: `POST /auth/login` carries a fixed-window ASP.NET Core rate-limiter policy keyed per remote IP (`MxGateway:Security:LoginRateLimit*`), rejecting a burst with HTTP 429 before the LDAP bind is relayed to the directory. See [GatewayConfiguration](./GatewayConfiguration.md#security-options).
+### Streaming calls and revocation
+
+A streaming call is authenticated once, when it opens. To keep a revoked key from
+holding a stream open indefinitely (SEC-004), the interceptor registers every
+streaming call (server, client and duplex) in `ApiKeyStreamRegistry` under the
+caller's key id, and hands the handler a `RevocableServerCallContext`: the real call
+context with a cancellation token that also fires when the key is revoked. The
+dashboard API Keys page calls `ApiKeyStreamRegistry.Revoke(keyId)` on Revoke, Rotate
+and Delete, right after it evicts the verification cache. The handler stops on its
+token as it would for a client cancel, and the interceptor reports the end of the
+call as `Unauthenticated` — the status a new call with that key now gets — whatever
+status the handler mapped its cancellation to. Rotate ends the key's streams too,
+since they were opened with the secret the rotation retires; the client reconnects
+with the new secret. Unary calls are not tracked: they complete within the command
+timeout.
+
+Only revocations made inside the gateway process reach the registry. A key revoked
+by the separate `apikey` CLI process keeps its open streams until they reconnect,
+the same out-of-band window its verification-cache entry has.
+
## Scope Resolution
`GatewayGrpcScopeResolver` is a stateless singleton that switches on the runtime request type. Top-level RPC requests map directly:
diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md
index 06debee3..2740c2e7 100644
--- a/docs/GatewayDashboardDesign.md
+++ b/docs/GatewayDashboardDesign.md
@@ -729,6 +729,9 @@ anonymous localhost session shows the same read-only view.
old one. Active keys only — rotating a revoked key would un-revoke it, so
the button is not shown on revoked rows.
- **Revoke** marks a key revoked; a revoked key cannot be un-revoked.
+ Revoke, Rotate and Delete also end every streaming gRPC call the key
+ already has open (`ApiKeyStreamRegistry`, SEC-004); the client sees
+ `Unauthenticated`.
- **Delete** permanently removes a key row from the auth database, but only
when the key is already revoked. `IApiKeyAdminStore.DeleteAsync` rejects
active keys (returns false) so the revoke event lands in the audit log
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs
index 41e773bc..070b53b4 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs
@@ -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,
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyStreamRegistry.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyStreamRegistry.cs
new file mode 100644
index 00000000..07999ae4
--- /dev/null
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyStreamRegistry.cs
@@ -0,0 +1,152 @@
+using System.Collections.Concurrent;
+
+namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
+
+///
+/// Tracks the streaming gRPC calls each API key has open, so revoking, rotating or deleting the key
+/// ends them (SEC-004).
+///
+///
+///
+/// A streaming call is authenticated once, when it opens. Evicting the verification cache on
+/// revoke stops new calls but leaves an open StreamEvents, StreamAlarms or
+/// WatchDeployEvents 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 ; the interceptor then
+/// reports the end of the call as Unauthenticated.
+///
+///
+/// Only revocations made through this gateway process reach the registry (the dashboard API Keys
+/// page). The separate apikey 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).
+///
+///
+public sealed class ApiKeyStreamRegistry
+{
+ private readonly ConcurrentDictionary> _byKeyId =
+ new(StringComparer.OrdinalIgnoreCase);
+
+ /// Gets the number of open streaming calls registered for a key id. Test seam.
+ /// The key id.
+ /// The open registration count.
+ internal int CountFor(string keyId) =>
+ _byKeyId.TryGetValue(keyId, out ConcurrentDictionary? set) ? set.Count : 0;
+
+ ///
+ /// Registers a streaming call. Dispose the returned registration when the call ends.
+ ///
+ /// The authenticated caller's key id.
+ /// The call's own cancellation token, linked into the registration's.
+ /// The registration whose the handler must observe.
+ public Registration Register(string keyId, CancellationToken callCancellation)
+ {
+ ArgumentException.ThrowIfNullOrEmpty(keyId);
+
+ Registration registration = new(this, keyId, callCancellation);
+ while (true)
+ {
+ ConcurrentDictionary 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? current)
+ && ReferenceEquals(current, set))
+ {
+ return registration;
+ }
+
+ set.TryRemove(registration, out _);
+ }
+ }
+
+ /// Ends every open streaming call registered for the key id.
+ /// The revoked, rotated or deleted key id.
+ /// The number of calls that were cancelled.
+ public int Revoke(string keyId)
+ {
+ if (string.IsNullOrEmpty(keyId) || !_byKeyId.TryGetValue(keyId, out ConcurrentDictionary? 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? set)
+ && set.TryRemove(registration, out _)
+ && set.IsEmpty)
+ {
+ _byKeyId.TryRemove(new KeyValuePair>(registration.KeyId, set));
+ }
+ }
+
+ /// One open streaming call.
+ 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);
+ }
+
+ /// Gets the key id the call authenticated with.
+ public string KeyId { get; }
+
+ /// Gets the token that fires when the call is cancelled or its key is revoked.
+ public CancellationToken Token => _cancellation.Token;
+
+ /// Gets a value indicating whether the key was revoked while the call was open.
+ public bool IsRevoked => Volatile.Read(ref _revoked) == 1;
+
+ ///
+ 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;
+ }
+ }
+}
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs
index 255096ec..5bb2a2e6 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs
@@ -18,8 +18,11 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
IGatewayRequestIdentityAccessor identityAccessor,
IOptions 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;
@@ -59,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);
}
}
@@ -81,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;
}
}
@@ -97,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 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));
}
}
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs
index 62e4d9af..7a535d63 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs
@@ -26,6 +26,7 @@ public static class GrpcAuthorizationServiceCollectionExtensions
sp.GetRequiredService().GetSection(SecurityOptions.SectionName).Get()
?? new SecurityOptions(),
sp.GetService() ?? TimeProvider.System));
+ services.AddSingleton();
services.AddSingleton();
services
.AddOptions()
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/RevocableServerCallContext.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/RevocableServerCallContext.cs
new file mode 100644
index 00000000..37677449
--- /dev/null
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/RevocableServerCallContext.cs
@@ -0,0 +1,84 @@
+using Grpc.Core;
+
+namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
+
+///
+/// A 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 , so they end a revoked stream
+/// without knowing about revocation.
+///
+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.
+ }
+ }
+
+ ///
+ protected override string MethodCore => _inner.Method;
+
+ ///
+ protected override string HostCore => _inner.Host;
+
+ ///
+ protected override string PeerCore => _inner.Peer;
+
+ ///
+ protected override DateTime DeadlineCore => _inner.Deadline;
+
+ ///
+ protected override Metadata RequestHeadersCore => _inner.RequestHeaders;
+
+ ///
+ protected override CancellationToken CancellationTokenCore => _cancellationToken;
+
+ ///
+ protected override Metadata ResponseTrailersCore => _inner.ResponseTrailers;
+
+ ///
+ protected override Status StatusCore
+ {
+ get => _inner.Status;
+ set => _inner.Status = value;
+ }
+
+ ///
+ protected override WriteOptions? WriteOptionsCore
+ {
+ get => _inner.WriteOptions;
+ set => _inner.WriteOptions = value;
+ }
+
+ ///
+ protected override AuthContext AuthContextCore => _inner.AuthContext;
+
+ ///
+ protected override IDictionary