fix(auth): partition the API-key failure limiter on remote IP, not IP:port (SEC-001, #244)

ServerCallContext.Peer carries the client's ephemeral source port, so every new
connection was a fresh limiter partition and a sprayer could reconnect before
reaching the limit. Both auth surfaces (gRPC interceptor, /metrics handler) now
derive the partition address through ApiKeyThrottlePeer, which strips the port
and reduces IPv4-mapped IPv6 to IPv4.
This commit is contained in:
Joseph Doherty
2026-12-03 09:48:03 -05:00
parent 27fdb576ba
commit a9f884f370
9 changed files with 211 additions and 10 deletions
@@ -11,6 +11,9 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// <see cref="GatewayGrpcAuthorizationInterceptor"/> (literal <c>mxgw</c> prefix, at least three
/// non-empty underscore segments, bounded key-id length) so junk tokens cannot mint partitions.
/// </remarks>
/// <param name="TransportPeer">The gRPC transport peer address (<c>ServerCallContext.Peer</c>).</param>
/// <param name="TransportPeer">
/// The client's remote IP with no port, as produced by <see cref="ApiKeyThrottlePeer"/>. The
/// source port is excluded because it changes with every connection (SEC-001).
/// </param>
/// <param name="KeyId">The key id claimed by a validly shaped token, or <see langword="null"/>.</param>
public readonly record struct ApiKeyThrottlePartition(string TransportPeer, string? KeyId);
@@ -0,0 +1,76 @@
using System.Net;
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// <summary>
/// Derives the address half of an <see cref="ApiKeyThrottlePartition"/>: the client's remote IP
/// with no source port, in one canonical form shared by the gRPC interceptor and the
/// <c>/metrics</c> handler.
/// </summary>
/// <remarks>
/// The port must not be part of the partition (SEC-001). It is the client's ephemeral source port,
/// so keying on it made every new TCP connection a fresh partition: an attacker could send
/// <c>limit - 1</c> bad secrets, reconnect, and repeat without ever being throttled, and each
/// connection minted a tracked partition. Both auth surfaces normalise through this type so a
/// failure on one counts against the same address on the other.
/// </remarks>
public static class ApiKeyThrottlePeer
{
private const string Ipv4Prefix = "ipv4:";
private const string Ipv6Prefix = "ipv6:[";
/// <summary>
/// Extracts the remote IP from a Grpc.AspNetCore peer string (<c>ipv4:1.2.3.4:5678</c> or
/// <c>ipv6:[::1]:5678</c>). A peer in any other form (<c>unknown</c>, a Unix socket) is returned
/// unchanged, since it carries no port to strip.
/// </summary>
/// <param name="grpcPeer">The value of <c>ServerCallContext.Peer</c>.</param>
/// <returns>The canonical address string.</returns>
public static string FromGrpcPeer(string grpcPeer)
{
ArgumentNullException.ThrowIfNull(grpcPeer);
ReadOnlySpan<char> address;
if (grpcPeer.StartsWith(Ipv4Prefix, StringComparison.Ordinal))
{
ReadOnlySpan<char> rest = grpcPeer.AsSpan(Ipv4Prefix.Length);
int portSeparator = rest.LastIndexOf(':');
address = portSeparator > 0 ? rest[..portSeparator] : rest;
}
else if (grpcPeer.StartsWith(Ipv6Prefix, StringComparison.Ordinal))
{
ReadOnlySpan<char> rest = grpcPeer.AsSpan(Ipv6Prefix.Length);
int close = rest.IndexOf(']');
if (close <= 0)
{
return grpcPeer;
}
address = rest[..close];
}
else
{
return grpcPeer;
}
return IPAddress.TryParse(address, out IPAddress? parsed) ? FromRemoteIp(parsed) : grpcPeer;
}
/// <summary>
/// Formats an HTTP connection's remote IP. An IPv4-mapped IPv6 address is reduced to IPv4 so a
/// dual-stack listener does not split one client across two partitions.
/// </summary>
/// <param name="remoteIpAddress">The connection's remote address, or <see langword="null"/>.</param>
/// <returns>The canonical address string, or <c>unknown</c>.</returns>
public static string FromRemoteIp(IPAddress? remoteIpAddress)
{
if (remoteIpAddress is null)
{
return "unknown";
}
return remoteIpAddress.IsIPv4MappedToIPv6
? remoteIpAddress.MapToIPv4().ToString()
: remoteIpAddress.ToString();
}
}
@@ -168,14 +168,17 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
return identity;
}
// Resolves the failure-limiter partition: always the transport peer, plus the presented key id
// when — and only when — the token is validly shaped. Both halves are unauthenticated input, so
// the peer half is what keeps a throttle bound to the address that earned it.
// Resolves the failure-limiter partition: always the remote IP (port stripped — the source port
// changes per connection, SEC-001), plus the presented key id when — and only when — the token
// is validly shaped. Both halves are unauthenticated input, so the address half is what keeps a
// throttle bound to the address that earned it.
private static ApiKeyThrottlePartition ResolveThrottlePartition(
string? authorizationHeader,
ServerCallContext context)
{
return new ApiKeyThrottlePartition(context.Peer, TryResolveKeyId(authorizationHeader));
return new ApiKeyThrottlePartition(
ApiKeyThrottlePeer.FromGrpcPeer(context.Peer),
TryResolveKeyId(authorizationHeader));
}
// Token shape mxgw_<keyId>_<secret>: the key id is the second underscore-delimited segment (the
@@ -64,7 +64,7 @@ public sealed class MetricsAuthenticationHandler(
// 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(
Context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
ApiKeyThrottlePeer.FromRemoteIp(Context.Connection.RemoteIpAddress),
GatewayGrpcAuthorizationInterceptor.TryResolveKeyId(authorizationHeader));
ApiKeyThrottleDecision decision = failureLimiter.Check(
partition,
@@ -0,0 +1,50 @@
using System.Net;
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization;
/// <summary>
/// Pins the address normalisation shared by the gRPC interceptor and the <c>/metrics</c> handler
/// (SEC-001): the source port never reaches the limiter partition, and both surfaces produce the
/// same string for the same client.
/// </summary>
public sealed class ApiKeyThrottlePeerTests
{
/// <summary>Strips the port from each Grpc.AspNetCore peer form.</summary>
/// <param name="grpcPeer">The <c>ServerCallContext.Peer</c> value.</param>
/// <param name="expected">The expected address.</param>
[Theory]
[InlineData("ipv4:203.0.113.7:40001", "203.0.113.7")]
[InlineData("ipv4:127.0.0.1:5000", "127.0.0.1")]
[InlineData("ipv6:[::1]:5000", "::1")]
[InlineData("ipv6:[2001:db8::7]:40001", "2001:db8::7")]
[InlineData("ipv6:[::ffff:203.0.113.7]:40001", "203.0.113.7")]
public void FromGrpcPeer_StripsPort(string grpcPeer, string expected)
{
Assert.Equal(expected, ApiKeyThrottlePeer.FromGrpcPeer(grpcPeer));
}
/// <summary>A peer with no address/port shape is kept verbatim rather than guessed at.</summary>
/// <param name="grpcPeer">The <c>ServerCallContext.Peer</c> value.</param>
[Theory]
[InlineData("unknown")]
[InlineData("unix:/tmp/mxgw.sock")]
[InlineData("ipv6:[not-an-address]:1")]
public void FromGrpcPeer_KeepsUnrecognisedForms(string grpcPeer)
{
Assert.Equal(grpcPeer, ApiKeyThrottlePeer.FromGrpcPeer(grpcPeer));
}
/// <summary>
/// The gRPC and HTTP surfaces agree, so a failure counted on one is charged to the same
/// partition on the other — including an IPv4 client seen through a dual-stack listener.
/// </summary>
[Fact]
public void FromRemoteIp_MatchesGrpcPeerForm()
{
Assert.Equal(
ApiKeyThrottlePeer.FromGrpcPeer("ipv4:203.0.113.7:40001"),
ApiKeyThrottlePeer.FromRemoteIp(IPAddress.Parse("::ffff:203.0.113.7")));
Assert.Equal("unknown", ApiKeyThrottlePeer.FromRemoteIp(null));
}
}
@@ -406,6 +406,75 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
Assert.Equal(3, verifier.CallCount);
}
/// <summary>
/// SEC-001: the partition is the remote IP, not the TCP connection. Failures from two
/// connections of one address (different ephemeral source ports) share one partition, so
/// reconnecting does not reset the count: nine failures on each connection trip the limit of
/// ten and the eleventh attempt overall is throttled without reaching the verifier.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Failures_FromSameAddressOnDifferentSourcePorts_ShareOnePartition()
{
CountingFailureVerifier verifier = new(Failure(ApiKeyFailure.SecretMismatch));
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10);
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
verifier,
new GatewayRequestIdentityAccessor(),
failureLimiter: limiter);
List<StatusCode> statuses = [];
foreach (string peer in new[] { "ipv4:203.0.113.7:40001", "ipv4:203.0.113.7:40002" })
{
for (int attempt = 0; attempt < 9; attempt++)
{
RpcException failure = await Assert.ThrowsAsync<RpcException>(
() => interceptor.UnaryServerHandler(
new OpenSessionRequest(),
ContextWithAuthorization("Bearer mxgw_operator01_bad-secret", peer),
(_, _) => Task.FromResult(new OpenSessionReply())));
statuses.Add(failure.StatusCode);
}
}
Assert.All(statuses.Take(10), status => Assert.Equal(StatusCode.Unauthenticated, status));
Assert.Equal(StatusCode.ResourceExhausted, statuses[10]);
Assert.Equal(10, verifier.CallCount);
Assert.Equal(1, limiter.TrackedPartitionCount);
}
/// <summary>
/// SEC-001, junk-token path: tokens with no key id fall back to the address partition, and that
/// partition must also survive a reconnect, or junk spraying would never be throttled.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task JunkTokens_FromSameAddressOnDifferentSourcePorts_AreThrottled()
{
CountingFailureVerifier verifier = new(Failure(ApiKeyFailure.MissingOrMalformed));
ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch);
ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3);
GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor(
verifier,
new GatewayRequestIdentityAccessor(),
failureLimiter: limiter);
StatusCode last = StatusCode.OK;
for (int port = 50000; port < 50004; port++)
{
RpcException failure = await Assert.ThrowsAsync<RpcException>(
() => interceptor.UnaryServerHandler(
new OpenSessionRequest(),
ContextWithAuthorization("Bearer garbage", $"ipv6:[2001:db8::7]:{port}"),
(_, _) => Task.FromResult(new OpenSessionReply())));
last = failure.StatusCode;
}
Assert.Equal(StatusCode.ResourceExhausted, last);
Assert.Equal(3, 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
@@ -609,7 +678,7 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
}
Assert.Equal(1, limiter.TrackedPartitionCount);
Assert.True(limiter.IsTracked(new ApiKeyThrottlePartition(AttackerPeer, KeyId: null)));
Assert.True(limiter.IsTracked(new ApiKeyThrottlePartition(ApiKeyThrottlePeer.FromGrpcPeer(AttackerPeer), KeyId: null)));
}
/// <summary>