diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs index 684dc0f4..5a72d481 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs @@ -166,10 +166,23 @@ public sealed class ApiKeyFailureLimiter } long now = _clock.GetUtcNow().UtcTicks; - (string partitionKey, string? effectiveKeyId) = ResolvePartitionKey(peer, partition.KeyId, mint: false); - resolution = new PartitionResolution(partitionKey, effectiveKeyId); - WindowState? peerState = _partitions.TryGetValue(partitionKey, out WindowState? tracked) ? tracked : null; + // The common case on a quiet limiter is that no peer partition exists at all. Skipping the + // resolve then avoids building the composite (peer, key id) string only to miss the lookup + // with it (SEC-012). A failure that a concurrent request records after this read is not one + // this request's later success clears; it decays by window like any other. + WindowState? peerState = null; + if (_partitions.IsEmpty) + { + resolution = PartitionResolution.NoTrackedState; + } + else + { + (string partitionKey, string? effectiveKeyId) = ResolvePartitionKey(peer, partition.KeyId, mint: false); + resolution = new PartitionResolution(partitionKey, effectiveKeyId); + peerState = _partitions.TryGetValue(partitionKey, out WindowState? tracked) ? tracked : null; + } + WindowState? aggregateState = null; if (partition.KeyId is not null && _aggregateLimit > 0 @@ -275,34 +288,50 @@ public sealed class ApiKeyFailureLimiter internal void Reset(ApiKeyThrottlePartition partition, PartitionResolution resolution) { string peer = RequirePeer(partition); - (string partitionKey, string? effectiveKeyId) = resolution.IsResolved - ? (resolution.PartitionKey!, resolution.EffectiveKeyId) - : ResolvePartitionKey(peer, partition.KeyId, mint: false); - // Clear only a partition this caller actually owns. When its key id was squeezed into the - // address's shared fallback bucket by the per-peer cap, that bucket also holds failures - // contributed by other key ids — and by junk-shaped tokens — from the same address, so - // removing it would let one successful authentication wipe an in-progress spray. The shared - // bucket decays by window expiry instead; the caller still recovers through probe admission. - if (effectiveKeyId is not null - && string.Equals(effectiveKeyId, partition.KeyId, StringComparison.Ordinal)) + // A disabled limiter never records a partition or consults a verified mark. + if (_limit <= 0) { - RemovePartition(partitionKey); + return; + } + + // The composite (peer, key id) string the check built, when it built one this caller owns; + // the verified mark below reuses it rather than building it again. + string? ownComposite = null; + + // A check that saw no tracked partition has nothing for this success to clear (SEC-012). + if (!resolution.Untracked) + { + (string partitionKey, string? effectiveKeyId) = resolution.IsResolved + ? (resolution.PartitionKey!, resolution.EffectiveKeyId) + : ResolvePartitionKey(peer, partition.KeyId, mint: false); + + // Clear only a partition this caller actually owns. When its key id was squeezed into the + // address's shared fallback bucket by the per-peer cap, that bucket also holds failures + // contributed by other key ids — and by junk-shaped tokens — from the same address, so + // removing it would let one successful authentication wipe an in-progress spray. The shared + // bucket decays by window expiry instead; the caller still recovers through probe admission. + if (effectiveKeyId is not null + && string.Equals(effectiveKeyId, partition.KeyId, StringComparison.Ordinal)) + { + RemovePartition(partitionKey); + ownComposite = partitionKey; + } } // 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) + if (partition.KeyId is not null && _aggregateLimit > 0) { - MarkVerified(peer, partition.KeyId, _clock.GetUtcNow().UtcTicks); + MarkVerified(ownComposite ?? Composite(peer, partition.KeyId), _clock.GetUtcNow().UtcTicks); } } - private void MarkVerified(string peer, string keyId, long now) + private void MarkVerified(string composite, long now) { - _verified[Composite(peer, keyId)] = now; + _verified[composite] = now; if (_verified.Count <= _maxPartitions) { return; @@ -633,11 +662,18 @@ public sealed class ApiKeyFailureLimiter /// The key id that actually earned a partition, or when the token carried /// none or the per-peer cap collapsed it onto the transport-peer fallback. /// - internal readonly record struct PartitionResolution(string? PartitionKey, string? EffectiveKeyId) + /// + /// when the check found no peer partition tracked at all and so skipped + /// resolving a storage key; the reset then has no partition to clear. + /// + internal readonly record struct PartitionResolution(string? PartitionKey, string? EffectiveKeyId, bool Untracked = false) { /// Gets the sentinel for "not resolved yet"; the receiving call resolves it itself. internal static PartitionResolution Unresolved => default; + /// Gets the sentinel for "the check saw no tracked peer partition". + internal static PartitionResolution NoTrackedState => new(null, null, Untracked: true); + /// Gets a value indicating whether this carries a resolved storage key. internal bool IsResolved => PartitionKey is not null; } 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 5bb2a2e6..236a6170 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs @@ -154,7 +154,9 @@ public sealed class GatewayGrpcAuthorizationInterceptor( /// The scope the call requires, resolved by the caller. /// RPC server call context. /// Authenticated API key identity, or null if authentication is disabled. - private async Task AuthenticateAndAuthorizeAsync( + // ValueTask: a cache hit completes synchronously, and a Task would be one more allocation on + // every authenticated RPC (SEC-012). + private async ValueTask AuthenticateAndAuthorizeAsync( string requiredScope, ServerCallContext context) { diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs index d9d66524..e95a6a44 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs @@ -557,6 +557,66 @@ public sealed class ApiKeyFailureLimiterTests Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(arriving)); } + /// + /// SEC-012: on a quiet limiter the check resolves no composite key and allocates nothing, and + /// the matching reset still writes the verified mark that keeps the aggregate from locking the + /// holder out (SEC-002). + /// + [Fact] + public void Check_WithNoTrackedPartition_AllocatesNothing_AndResetStillMarksVerified() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3, aggregateLimit: 5); + ApiKeyThrottlePartition holder = new("ipv4:10.0.0.1", "victim"); + + // Warm up JIT and any lazy statics before measuring. + limiter.Check(holder, out _); + + long before = GC.GetAllocatedBytesForCurrentThread(); + ApiKeyThrottleDecision decision = limiter.Check(holder, out ApiKeyFailureLimiter.PartitionResolution resolution); + long allocated = GC.GetAllocatedBytesForCurrentThread() - before; + + Assert.Equal(ApiKeyThrottleDecision.Allowed, decision); + Assert.Equal(0, allocated); + Assert.True(resolution.Untracked); + + limiter.Reset(holder, resolution); + Assert.Equal(1, limiter.VerifiedMarkCount); + + // The mark still bypasses an aggregate a sprayer then drives over its limit. + for (int i = 0; i < 5; i++) + { + limiter.RecordFailure(new ApiKeyThrottlePartition($"ipv4:10.0.1.{i}", "victim")); + } + + Assert.Equal(ApiKeyThrottleDecision.Allowed, limiter.Check(holder)); + Assert.Equal( + ApiKeyThrottleDecision.ThrottledByAggregate, + limiter.Check(new ApiKeyThrottlePartition("ipv4:10.0.2.1", "victim"))); + } + + /// + /// SEC-012: once any partition is tracked the check resolves again, and a success still clears + /// the caller's own partition through the resolution it handed back. + /// + [Fact] + public void Check_WithTrackedPartition_ResolvesAndResetClearsOwnPartition() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3, aggregateLimit: 5); + ApiKeyThrottlePartition holder = new("ipv4:10.0.0.1", "victim"); + RecordFailures(limiter, holder, 2); + + limiter.Check(holder, out ApiKeyFailureLimiter.PartitionResolution resolution); + Assert.False(resolution.Untracked); + Assert.True(resolution.IsResolved); + + limiter.Reset(holder, resolution); + + Assert.False(limiter.IsTracked(holder)); + Assert.Equal(1, limiter.VerifiedMarkCount); + } + private static void RecordFailures(ApiKeyFailureLimiter limiter, ApiKeyThrottlePartition partition, int count) { for (int i = 0; i < count; i++)