fix(auth): revoking, rotating or deleting a key ends its open gRPC streams (SEC-004)

A streaming call was authenticated only at open, and revoke/rotate/delete only
evicted the verification cache, so a leaked key's open StreamEvents/StreamAlarms
kept delivering after the revoke. The interceptor now registers every streaming
call by key id in ApiKeyStreamRegistry and gives the handler a call context
whose token also fires on revoke; the dashboard key actions call Revoke, and the
call ends with Unauthenticated.
This commit is contained in:
Joseph Doherty
2026-12-03 09:55:43 -05:00
parent 824107a56b
commit 835ed0bd04
11 changed files with 481 additions and 10 deletions
@@ -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,
@@ -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;
}
}
}
@@ -18,8 +18,11 @@ 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;
@@ -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<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));
}
}
@@ -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>()
@@ -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);
}
@@ -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")
@@ -610,6 +610,83 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
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
@@ -1086,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,
@@ -1100,7 +1178,8 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
}
}),
failureLimiter ?? CreateLimiter(TimeProvider.System, limit: 1000),
new GatewayMetrics());
new GatewayMetrics(),
streamRegistry);
}
private static ApiKeyFailureLimiter CreateLimiter(
@@ -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);
}
}