From 835ed0bd04b58849607bfe144379314b3a17d3d6 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:55:43 -0500 Subject: [PATCH] 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. --- docs/Authentication.md | 7 +- docs/Authorization.md | 20 +++ docs/GatewayDashboardDesign.md | 3 + .../DashboardApiKeyManagementService.cs | 15 +- .../Authorization/ApiKeyStreamRegistry.cs | 152 ++++++++++++++++++ .../GatewayGrpcAuthorizationInterceptor.cs | 57 ++++++- ...uthorizationServiceCollectionExtensions.cs | 1 + .../RevocableServerCallContext.cs | 84 ++++++++++ .../DashboardApiKeyManagementServiceTests.cs | 29 +++- ...atewayGrpcAuthorizationInterceptorTests.cs | 83 +++++++++- .../RevocableServerCallContextTests.cs | 40 +++++ 11 files changed, 481 insertions(+), 10 deletions(-) create mode 100644 src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyStreamRegistry.cs create mode 100644 src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/RevocableServerCallContext.cs create mode 100644 src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/RevocableServerCallContextTests.cs 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 UserStateCore => _inner.UserState; + + /// + protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => + _inner.CreatePropagationToken(options); + + /// + protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => + _inner.WriteResponseHeadersAsync(responseHeaders); +} diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs index 4aecc340..abee5740 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs @@ -335,7 +335,31 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable Assert.Equal("API key pepper is not configured.", result.Message); } - private DashboardApiKeyManagementService CreateService(ServiceProvider services) + /// + /// SEC-004: revoking a key on the dashboard ends the streaming calls that key already has + /// open, not only future calls. + /// + /// A task that represents the asynchronous operation. + [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(), services.GetRequiredService(), services.GetRequiredService(), - new HttpContextAccessor { HttpContext = httpContext }); + new HttpContextAccessor { HttpContext = httpContext }, + streamRegistry: streamRegistry); } private ServiceProvider BuildServices(string? pepper = "test-pepper") diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs index d8d64da9..d7e30348 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs @@ -610,6 +610,83 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests Assert.Equal(verifierCallsBefore, verifier.CallCount); } + /// + /// SEC-004: revoking a key mid-stream ends the open streaming call with + /// , whatever status the handler maps its cancellation + /// to, and releases the registration. + /// + /// Whether the handler converts its cancellation to an RpcException(Cancelled), as the gateway services do. + /// A task that represents the asynchronous operation. + [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(), + 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(() => call.WaitAsync(TimeSpan.FromSeconds(10))); + Assert.Equal(StatusCode.Unauthenticated, exception.StatusCode); + Assert.Equal(0, registry.CountFor("operator01")); + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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(), + ContextWithAuthorization("Bearer mxgw_operator01_secret", HolderPeer), + (_, _, context) => + { + seenPeer = context.Peer; + return Task.CompletedTask; + }); + + Assert.Equal(HolderPeer, seenPeer); + Assert.Equal(0, registry.CountFor("operator01")); + } + /// /// 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( diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/RevocableServerCallContextTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/RevocableServerCallContextTests.cs new file mode 100644 index 00000000..ecfe51a8 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/RevocableServerCallContextTests.cs @@ -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; + +/// +/// The context handed to streaming handlers (SEC-004) must behave as the real call context in +/// every respect except its cancellation token. +/// +public sealed class RevocableServerCallContextTests +{ + /// Metadata, status, trailers, user state and the HttpContext all pass through. + [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); + } +}