diff --git a/docs/Authentication.md b/docs/Authentication.md index 07c89ee4..b8c13234 100644 --- a/docs/Authentication.md +++ b/docs/Authentication.md @@ -153,8 +153,11 @@ the cross-peer aggregate: its failures still feed and consult the key-id aggrega whose own cardinality is bounded by the configured LRU cap. An over-limit state admits one probe per `ApiKeyFailureProbeIntervalSeconds` through to the real verifier and refuses everything else with `ResourceExhausted` before the store read, so a legitimate -holder presenting the correct secret always reaches the constant-time compare and -resets both layers; the counter's LRU eviction (`ApiKeyFailureTrackedPeers`) +holder presenting the correct secret always reaches the constant-time compare. A +success clears the caller's own partition and exempts its address from the key's +aggregate for one window, but leaves the aggregate itself to decay, and a cached +success skips the limiter altogether (see [Authorization](./Authorization.md)); +the counter's LRU eviction (`ApiKeyFailureTrackedPeers`) prefers expired windows and will not drop an over-limit partition below a 2x overshoot ceiling, so the memory bound cannot be turned into a way to clear an active block. See [Authorization](./Authorization.md) for the enforcement path. diff --git a/docs/Authorization.md b/docs/Authorization.md index a5f7a461..ca4ada35 100644 --- a/docs/Authorization.md +++ b/docs/Authorization.md @@ -99,7 +99,9 @@ Before the verification store read, the helper asks a cheap in-process failure c - **Composite `(remote IP, key id)` partitions.** Reaching `MxGateway:Security:ApiKeyFailureLimit` failures binds the throttle to the address that produced them. The address is the client's IP with the source port stripped (`ApiKeyThrottlePeer`): the port is ephemeral, and keying on it made every new TCP connection a fresh partition, so a client could send `limit - 1` bad secrets, reconnect, and repeat without ever being throttled (SEC-001). The gRPC interceptor (parsing `ServerCallContext.Peer`) and the `/metrics` handler (`Connection.RemoteIpAddress`) normalise through the same helper, with IPv4-mapped IPv6 reduced to IPv4, so a failure on either surface counts against the same partition. The key id alone is never the partition: key ids are not secret — they ride in every token and are listed on the dashboard — so keying on them let any network peer deny a key to its legitimate holder. The key id joins the partition only after a token-shape check (literal `mxgw` prefix, at least three non-empty `_` segments, key id of at most 64 characters), and one address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition. - **A per-key-id aggregate** across all peers (`ApiKeyFailureAggregateLimit`, default 30), which bounds a distributed or source-rotating sprayer that never trips any single partition. -An over-limit state is a valve, not a wall: one request per `ApiKeyFailureProbeIntervalSeconds` (default 5 s) is admitted through to the real verifier, and everything else is refused with `StatusCode.ResourceExhausted` before the store read. The slot is claimed atomically, so a burst arriving together at an interval boundary still yields exactly one admission, and a slot claimed for a request that a later layer then refuses is handed back under a per-state version stamp — never by timestamp comparison, which collides whenever a concurrent failure re-arms the same state on the same clock tick. A successful verification resets both layers — which is why the reset path stays reachable while a key is under active spray. One exception: when the caller's key id was collapsed into its address's shared fallback partition by the per-peer cap, a success clears the key's aggregate but leaves that shared partition alone, since it also holds failures contributed by other key ids from the same address. The tracked partitions form a bounded LRU (`ApiKeyFailureTrackedPeers`) whose eviction prefers fully expired windows and never removes an over-limit partition below a 2x transient overshoot ceiling, so the cap bounds memory without becoming a reset button for an active block. `ResourceExhausted` reveals only that throttling is in effect, not whether any particular secret was valid, preserving the opaque-failure property. Refusals increment `mxgateway.auth.throttled`, tagged `stage=peer|aggregate` and nothing else — `/metrics` is anonymous by default (`MxGateway:Metrics:RequireAuthentication` is opt-in), so neither key ids nor peer addresses may appear there. +An over-limit state is a valve, not a wall: one request per `ApiKeyFailureProbeIntervalSeconds` (default 5 s) is admitted through to the real verifier, and everything else is refused with `StatusCode.ResourceExhausted` before the store read. The slot is claimed atomically, so a burst arriving together at an interval boundary still yields exactly one admission, and a slot claimed for a request that a later layer then refuses is handed back under a per-state version stamp — never by timestamp comparison, which collides whenever a concurrent failure re-arms the same state on the same clock tick. A successful verification clears the caller's own `(remote IP, key id)` partition and marks that pair verified for one window; it does **not** clear the key id's cross-peer aggregate, which decays by window expiry only (SEC-003). Clearing the aggregate on success meant a key in steady use — many successful calls a second — never accumulated one, so a sprayer guessing that key id from other addresses was bounded by neither layer. When the caller's key id was collapsed into its address's shared fallback partition by the per-peer cap, a success leaves that shared partition alone too, since it also holds failures contributed by other key ids from the same address. + +Two rules keep the holder of the correct secret from being denied by a spray against its public key id (SEC-002). First, the interceptor (and the `/metrics` handler) consult the verification cache **before** the limiter: a cached success (`IApiKeyVerificationCache`, implemented by `CachingApiKeyVerifier`) is proof of the correct token and costs no store read — the only thing the limiter protects — so it skips the limiter entirely. Second, on a cache miss, an address that verified the key inside the window skips the aggregate layer, so the holder does not have to win the probe slot against the sprayer once its cache entry expires. Neither path is reachable without the correct secret; a new address presenting the correct secret while the aggregate is tripped still goes through the probe slot once, then is exempt. The tracked partitions form a bounded LRU (`ApiKeyFailureTrackedPeers`) whose eviction prefers fully expired windows and never removes an over-limit partition below a 2x transient overshoot ceiling, so the cap bounds memory without becoming a reset button for an active block. `ResourceExhausted` reveals only that throttling is in effect, not whether any particular secret was valid, preserving the opaque-failure property. Refusals increment `mxgateway.auth.throttled`, tagged `stage=peer|aggregate` and nothing else — `/metrics` is anonymous by default (`MxGateway:Metrics:RequireAuthentication` is opt-in), so neither key ids nor peer addresses may appear there. 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). diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 245465ba..e54a7e34 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -460,7 +460,7 @@ model requires otherwise. | `MxGateway:Security:LoginRateLimitWindowSeconds` | `60` | Fixed-window length, in seconds, for the per-IP login rate limit. Must be greater than zero. | | `MxGateway:Security:ApiKeyFailureLimit` | `10` | Failed API-key verifications, per `(remote IP, key id)` partition (the source port is not part of it), within `ApiKeyFailureWindowSeconds` that trip the in-process short-circuit. Once tripped, the gRPC auth path rejects further attempts from that partition with `ResourceExhausted` **before** the store read — except for the probe admitted every `ApiKeyFailureProbeIntervalSeconds` — and a successful verification resets the partition. The partition always includes the sender's transport address: key ids are public (they ride in every token and are listed on the dashboard), so keying on the key id alone let any peer deny a key to its legitimate holder. Must be greater than zero. | | `MxGateway:Security:ApiKeyFailureWindowSeconds` | `60` | Sliding-window length, in seconds, over which API-key verification failures are counted, for both the per-partition and the per-key-id aggregate layer. Must be greater than zero. | -| `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(peer, key id)` partition. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. | +| `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(remote IP, key id)` partition. A successful verification does not clear it (it decays by window); addresses that verified the key inside the window, and cached verifications, are exempt so the holder is never locked out. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. | | `MxGateway:Security:ApiKeyFailureProbeIntervalSeconds` | `5` | Minimum interval, in seconds, between probe admissions for an over-limit partition or key-id aggregate. An over-limit state is a valve rather than a wall: one request per interval reaches the real verifier — exactly one, even when a burst arrives together at the interval boundary — so the holder of the correct secret always gets through and clears the state, while everything else is still refused before the store read. `0` blocks absolutely instead — **not recommended**, because an unauthenticated peer can then deny the key to its holder for the whole window. Must be zero or greater. | | `MxGateway:Security:AuditRetentionDays` | `90` | Days of canonical audit history kept in the `audit_event` table. The audit drain sweeps once at startup and hourly thereafter, deleting rows older than this window; without it the table grows without bound inside the same SQLite file the authentication hot path reads. Rows whose timestamp SQLite cannot parse are never swept. Must be greater than zero — retention can be widened but not switched off. | | `MxGateway:Security:ApiKeyFailureTrackedPeers` | `4096` | Maximum distinct partitions tracked by the failure counter (a bounded LRU) so a spray of unique tokens cannot grow memory without limit. It cannot be used to flush an active block either: only a validly shaped `mxgw__` token mints a key-id partition (everything else lands on the sender's transport-peer partition), each address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition, and eviction prefers fully expired windows, never removing an over-limit partition until the map exceeds twice this cap. Must be greater than zero. | diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs index 113516a8..bb1b2741 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs @@ -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); } +/// +/// Read-only access to cached successful verifications, consulted by the auth surfaces before the +/// failure limiter (SEC-002). +/// +/// +/// A hit means the presented token — key id and 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. +/// +public interface IApiKeyVerificationCache +{ + /// Returns a cached successful verification for the header, if one is within TTL. + /// The raw authorization header value. + /// The cached successful verification, when found. + /// on a cache hit. + bool TryGetCachedSuccess(string? authorizationHeader, [NotNullWhen(true)] out ApiKeyVerification? verification); +} + /// /// An decorator that caches successful verifications for a short, /// configurable TTL (), keyed on a @@ -72,7 +92,7 @@ public interface IApiKeyCacheInvalidator /// live cache rather than to every token ever verified. /// /// -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); } + /// + 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 VerifyMissAsync( 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 7fbc8875..684dc0f4 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs @@ -21,9 +21,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization; /// /// An over-limit state is a valve, not a wall: at most one request per /// 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 (address, key id) partition +/// and marks that pair as verified for one window; it does not 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. /// /// /// The tracked partition set is a bounded LRU (). @@ -71,6 +76,11 @@ public sealed class ApiKeyFailureLimiter private readonly ConcurrentDictionary _aggregates = new(StringComparer.Ordinal); private readonly ConcurrentDictionary _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 _verified = new(StringComparer.Ordinal); + /// Initializes a new instance of the class. /// Security options carrying the failure-limit knobs. /// The time provider. @@ -115,6 +125,9 @@ public sealed class ApiKeyFailureLimiter /// Gets the number of tracked per-key-id aggregates. Test seam. internal int TrackedAggregateCount => _aggregates.Count; + /// Gets the number of tracked verified (address, key id) marks. Test seam. + internal int VerifiedMarkCount => _verified.Count; + /// /// Test seam invoked between a probe claim and its compensating release; /// 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); } - /// Clears both limiter layers for the partition after a successful verification. + /// + /// Records a successful verification: clears the caller's own partition and marks the + /// (address, key id) pair verified. The key id's cross-peer aggregate is left to decay. + /// /// The throttle partition derived from the request. public void Reset(ApiKeyThrottlePartition partition) => Reset(partition, PartitionResolution.Unresolved); /// - /// Clears both limiter layers for the partition after a successful verification, reusing the - /// storage key already - /// resolved for this request. + /// Records a successful verification, reusing the storage key + /// already resolved for + /// this request. /// /// The throttle partition derived from the request. /// @@ -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 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; + } + /// Returns whether the partition currently has tracked failure state. Test seam. /// The throttle partition to look up. /// when the partition has a tracked window. 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 800e6b8a..255096ec 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs @@ -24,6 +24,10 @@ public sealed class GatewayGrpcAuthorizationInterceptor( // 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; + /// public override async Task UnaryServerHandler( TRequest request, @@ -112,6 +116,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 +163,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)) { diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs index e0693f6c..eaf8d94d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs @@ -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 429, mirroring the gRPC /// ResourceExhausted. 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 , so the two surfaces share both limiter +/// layers. A cached successful verification skips the limiter here as it does on gRPC (SEC-002). /// public sealed class MetricsAuthenticationHandler( IOptionsMonitor options, @@ -50,6 +51,8 @@ public sealed class MetricsAuthenticationHandler( GatewayMetrics metrics) : AuthenticationHandler(options, logger, encoder) { + private readonly IApiKeyVerificationCache? _verificationCache = apiKeyVerifier as IApiKeyVerificationCache; + private bool _throttled; /// @@ -61,6 +64,14 @@ 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( @@ -86,8 +97,12 @@ public sealed class MetricsAuthenticationHandler( } failureLimiter.Reset(partition, resolution); + return Authenticated(verification); + } - List claims = [new Claim(ClaimTypes.Name, verification.Identity.KeyId)]; + private AuthenticateResult Authenticated(ApiKeyVerification verification) + { + List claims = [new Claim(ClaimTypes.Name, verification.Identity!.KeyId)]; foreach (string scope in verification.Identity.Scopes) { claims.Add(new Claim(MetricsAuthorizationDefaults.ScopeClaimType, scope)); 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 17b05d57..d9d66524 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs @@ -313,18 +313,21 @@ public sealed class ApiKeyFailureLimiterTests Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(partition)); } - /// A successful verification clears both the composite partition and the key aggregate. + /// + /// 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). + /// [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"))); + } + + /// + /// 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. + /// + [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)); + } + + /// + /// 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. + /// + [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)); } /// 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 6b28d57c..d8d64da9 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs @@ -475,6 +475,141 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests Assert.Equal(3, verifier.CallCount); } + /// + /// 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. + /// + /// Address the holder calls from after the spray. + /// A task that represents the asynchronous operation. + [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( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"), + (_, _) => Task.FromResult(new OpenSessionReply()))); + } + + RpcException sprayer = await Assert.ThrowsAsync( + () => 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); + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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( + () => 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); + } + } + + /// + /// 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. + /// + /// A task that represents the asynchronous operation. + [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( + () => 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( + () => 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); + } + /// /// 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 @@ -1124,6 +1259,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; + + /// Gets the number of verifications performed. + public int CallCount => Volatile.Read(ref _callCount); + + /// + public Task 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 { /// Gets whether the verifier was called.