fix(auth): cached verifications skip the limiter; success no longer wipes the key aggregate (SEC-002, SEC-003, #245)
SEC-002: once a key id's cross-peer aggregate tripped, every request for it - including the holder's cached ones - competed for one probe slot per interval, so a spray of bad secrets against the public key id denied the key to its holder. The interceptor and /metrics handler now serve a cached success before consulting the limiter, and an address that verified the key in the window is exempt from the aggregate on a cache miss. SEC-003: Reset removed the aggregate on every success, so a key in steady use never accumulated one. Success now clears only the caller's own partition; the aggregate decays by window. Also corrects the MetricsAuthenticationHandler remark left stale by SEC-001.
This commit is contained in:
@@ -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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Read-only access to cached successful verifications, consulted by the auth surfaces before the
|
||||
/// failure limiter (SEC-002).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A hit means the presented token — key id <em>and</em> 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.
|
||||
/// </remarks>
|
||||
public interface IApiKeyVerificationCache
|
||||
{
|
||||
/// <summary>Returns a cached successful verification for the header, if one is within TTL.</summary>
|
||||
/// <param name="authorizationHeader">The raw <c>authorization</c> header value.</param>
|
||||
/// <param name="verification">The cached successful verification, when found.</param>
|
||||
/// <returns><see langword="true"/> on a cache hit.</returns>
|
||||
bool TryGetCachedSuccess(string? authorizationHeader, [NotNullWhen(true)] out ApiKeyVerification? verification);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An <see cref="IApiKeyVerifier"/> decorator that caches successful verifications for a short,
|
||||
/// configurable TTL (<see cref="SecurityOptions.ApiKeyVerificationCacheSeconds"/>), keyed on a
|
||||
@@ -72,7 +92,7 @@ public interface IApiKeyCacheInvalidator
|
||||
/// live cache rather than to every token ever verified.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
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<ApiKeyVerification> VerifyMissAsync(
|
||||
|
||||
@@ -21,9 +21,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
|
||||
/// <para>
|
||||
/// An over-limit state is a valve, not a wall: at most one request per
|
||||
/// <see cref="SecurityOptions.ApiKeyFailureProbeIntervalSeconds"/> 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 <c>(address, key id)</c> partition
|
||||
/// and marks that pair as verified for one window; it does <em>not</em> 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.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The tracked partition set is a bounded LRU (<see cref="SecurityOptions.ApiKeyFailureTrackedPeers"/>).
|
||||
@@ -71,6 +76,11 @@ public sealed class ApiKeyFailureLimiter
|
||||
private readonly ConcurrentDictionary<string, WindowState> _aggregates = new(StringComparer.Ordinal);
|
||||
private readonly ConcurrentDictionary<string, PeerKeyIds> _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<string, long> _verified = new(StringComparer.Ordinal);
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="ApiKeyFailureLimiter"/> class.</summary>
|
||||
/// <param name="security">Security options carrying the failure-limit knobs.</param>
|
||||
/// <param name="clock">The time provider.</param>
|
||||
@@ -115,6 +125,9 @@ public sealed class ApiKeyFailureLimiter
|
||||
/// <summary>Gets the number of tracked per-key-id aggregates. Test seam.</summary>
|
||||
internal int TrackedAggregateCount => _aggregates.Count;
|
||||
|
||||
/// <summary>Gets the number of tracked verified <c>(address, key id)</c> marks. Test seam.</summary>
|
||||
internal int VerifiedMarkCount => _verified.Count;
|
||||
|
||||
/// <summary>
|
||||
/// Test seam invoked between a probe claim and its compensating release; <see langword="null"/>
|
||||
/// 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);
|
||||
}
|
||||
|
||||
/// <summary>Clears both limiter layers for the partition after a successful verification.</summary>
|
||||
/// <summary>
|
||||
/// Records a successful verification: clears the caller's own partition and marks the
|
||||
/// <c>(address, key id)</c> pair verified. The key id's cross-peer aggregate is left to decay.
|
||||
/// </summary>
|
||||
/// <param name="partition">The throttle partition derived from the request.</param>
|
||||
public void Reset(ApiKeyThrottlePartition partition) => Reset(partition, PartitionResolution.Unresolved);
|
||||
|
||||
/// <summary>
|
||||
/// Clears both limiter layers for the partition after a successful verification, reusing the
|
||||
/// storage key <see cref="Check(ApiKeyThrottlePartition, out PartitionResolution)"/> already
|
||||
/// resolved for this request.
|
||||
/// Records a successful verification, reusing the storage key
|
||||
/// <see cref="Check(ApiKeyThrottlePartition, out PartitionResolution)"/> already resolved for
|
||||
/// this request.
|
||||
/// </summary>
|
||||
/// <param name="partition">The throttle partition derived from the request.</param>
|
||||
/// <param name="resolution">
|
||||
@@ -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<string, long> 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;
|
||||
}
|
||||
|
||||
/// <summary>Returns whether the partition currently has tracked failure state. Test seam.</summary>
|
||||
/// <param name="partition">The throttle partition to look up.</param>
|
||||
/// <returns><see langword="true"/> when the partition has a tracked window.</returns>
|
||||
|
||||
+24
-5
@@ -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;
|
||||
|
||||
/// <inheritdoc />
|
||||
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
|
||||
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))
|
||||
{
|
||||
|
||||
@@ -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 <c>429</c>, mirroring the gRPC
|
||||
/// <c>ResourceExhausted</c>. 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 <see cref="ApiKeyThrottlePeer"/>, so the two surfaces share both limiter
|
||||
/// layers. A cached successful verification skips the limiter here as it does on gRPC (SEC-002).
|
||||
/// </remarks>
|
||||
public sealed class MetricsAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
@@ -50,6 +51,8 @@ public sealed class MetricsAuthenticationHandler(
|
||||
GatewayMetrics metrics)
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
|
||||
{
|
||||
private readonly IApiKeyVerificationCache? _verificationCache = apiKeyVerifier as IApiKeyVerificationCache;
|
||||
|
||||
private bool _throttled;
|
||||
|
||||
/// <inheritdoc />
|
||||
@@ -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<Claim> claims = [new Claim(ClaimTypes.Name, verification.Identity.KeyId)];
|
||||
private AuthenticateResult Authenticated(ApiKeyVerification verification)
|
||||
{
|
||||
List<Claim> claims = [new Claim(ClaimTypes.Name, verification.Identity!.KeyId)];
|
||||
foreach (string scope in verification.Identity.Scopes)
|
||||
{
|
||||
claims.Add(new Claim(MetricsAuthorizationDefaults.ScopeClaimType, scope));
|
||||
|
||||
@@ -313,18 +313,21 @@ public sealed class ApiKeyFailureLimiterTests
|
||||
Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(partition));
|
||||
}
|
||||
|
||||
/// <summary>A successful verification clears both the composite partition and the key aggregate.</summary>
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
[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")));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
[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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+155
@@ -475,6 +475,141 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
|
||||
Assert.Equal(3, verifier.CallCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <param name="holderPeer">Address the holder calls from after the spray.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<RpcException>(
|
||||
() => interceptor.UnaryServerHandler(
|
||||
new OpenSessionRequest(),
|
||||
ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"),
|
||||
(_, _) => Task.FromResult(new OpenSessionReply())));
|
||||
}
|
||||
|
||||
RpcException sprayer = await Assert.ThrowsAsync<RpcException>(
|
||||
() => 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<RpcException>(
|
||||
() => 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[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<RpcException>(
|
||||
() => 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<RpcException>(
|
||||
() => 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);
|
||||
}
|
||||
|
||||
/// <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
|
||||
@@ -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;
|
||||
|
||||
/// <summary>Gets the number of verifications performed.</summary>
|
||||
public int CallCount => Volatile.Read(ref _callCount);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<ApiKeyVerification> 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
|
||||
{
|
||||
/// <summary>Gets whether the verifier was called.</summary>
|
||||
|
||||
Reference in New Issue
Block a user