diff --git a/docs/Authentication.md b/docs/Authentication.md
index 0e77d1f4..07c89ee4 100644
--- a/docs/Authentication.md
+++ b/docs/Authentication.md
@@ -141,7 +141,7 @@ Failures are never cached — a wrong secret always reaches the store — so the
failure path is shielded by `ApiKeyFailureLimiter` instead, consulted before
`VerifyAsync` runs. It counts failures over one sliding
`MxGateway:Security:ApiKeyFailureWindowSeconds` window in two layers: a composite
-`(transport peer, key id)` partition capped at `ApiKeyFailureLimit`, and a
+`(remote IP, key id)` partition capped at `ApiKeyFailureLimit`, and a
per-key-id aggregate across all peers capped at `ApiKeyFailureAggregateLimit`. The
key id never partitions on its own — it is public, so an attacker-supplied one
would otherwise let any peer throttle a key it does not hold — and it joins the
diff --git a/docs/Authorization.md b/docs/Authorization.md
index 40d5e385..a5f7a461 100644
--- a/docs/Authorization.md
+++ b/docs/Authorization.md
@@ -96,7 +96,7 @@ The status codes are deliberately distinct: `Unauthenticated` signals "we do not
Before the verification store read, the helper asks a cheap in-process failure counter (`ApiKeyFailureLimiter`) whether the attempt may proceed, so online guessing of API-key secrets cannot spend a SQLite read (and, in a naive design, a cache miss) per attempt. The counter has two layers over one sliding `ApiKeyFailureWindowSeconds` window:
-- **Composite `(transport peer, key id)` partitions.** Reaching `MxGateway:Security:ApiKeyFailureLimit` failures binds the throttle to the address that produced them. 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.
+- **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.
diff --git a/docs/GatewayConfiguration.md b/docs/GatewayConfiguration.md
index 076705f4..245465ba 100644
--- a/docs/GatewayConfiguration.md
+++ b/docs/GatewayConfiguration.md
@@ -458,7 +458,7 @@ model requires otherwise.
| `MxGateway:Security:ApiKeyLastUsedCoalesceSeconds` | `60` | Coalescing window, in seconds, for the `last_used_utc` write. The library verifier writes `last_used` on every successful verification; this bounds the write to at most one per key per window, so a hammered key does not churn the WAL. `0` forwards every write. Must be zero or greater. |
| `MxGateway:Security:LoginRateLimitPermitLimit` | `10` | Maximum `POST /auth/login` attempts permitted per remote IP within `LoginRateLimitWindowSeconds` before requests are rejected with HTTP 429. Throttles LDAP credential stuffing before the bind is relayed to the directory. Must be greater than zero. |
| `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 `(transport peer, key id)` partition, 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: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: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. |
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs
index 05dbe244..bdd73c38 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs
@@ -11,6 +11,9 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// (literal mxgw prefix, at least three
/// non-empty underscore segments, bounded key-id length) so junk tokens cannot mint partitions.
///
-/// The gRPC transport peer address (ServerCallContext.Peer).
+///
+/// The client's remote IP with no port, as produced by . The
+/// source port is excluded because it changes with every connection (SEC-001).
+///
/// The key id claimed by a validly shaped token, or .
public readonly record struct ApiKeyThrottlePartition(string TransportPeer, string? KeyId);
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePeer.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePeer.cs
new file mode 100644
index 00000000..d20c24a7
--- /dev/null
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePeer.cs
@@ -0,0 +1,76 @@
+using System.Net;
+
+namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
+
+///
+/// Derives the address half of an : the client's remote IP
+/// with no source port, in one canonical form shared by the gRPC interceptor and the
+/// /metrics handler.
+///
+///
+/// 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
+/// limit - 1 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.
+///
+public static class ApiKeyThrottlePeer
+{
+ private const string Ipv4Prefix = "ipv4:";
+ private const string Ipv6Prefix = "ipv6:[";
+
+ ///
+ /// Extracts the remote IP from a Grpc.AspNetCore peer string (ipv4:1.2.3.4:5678 or
+ /// ipv6:[::1]:5678). A peer in any other form (unknown, a Unix socket) is returned
+ /// unchanged, since it carries no port to strip.
+ ///
+ /// The value of ServerCallContext.Peer.
+ /// The canonical address string.
+ public static string FromGrpcPeer(string grpcPeer)
+ {
+ ArgumentNullException.ThrowIfNull(grpcPeer);
+
+ ReadOnlySpan address;
+ if (grpcPeer.StartsWith(Ipv4Prefix, StringComparison.Ordinal))
+ {
+ ReadOnlySpan rest = grpcPeer.AsSpan(Ipv4Prefix.Length);
+ int portSeparator = rest.LastIndexOf(':');
+ address = portSeparator > 0 ? rest[..portSeparator] : rest;
+ }
+ else if (grpcPeer.StartsWith(Ipv6Prefix, StringComparison.Ordinal))
+ {
+ ReadOnlySpan 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;
+ }
+
+ ///
+ /// 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.
+ ///
+ /// The connection's remote address, or .
+ /// The canonical address string, or unknown.
+ public static string FromRemoteIp(IPAddress? remoteIpAddress)
+ {
+ if (remoteIpAddress is null)
+ {
+ return "unknown";
+ }
+
+ return remoteIpAddress.IsIPv4MappedToIPv6
+ ? remoteIpAddress.MapToIPv4().ToString()
+ : remoteIpAddress.ToString();
+ }
+}
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 730c2e2e..800e6b8a 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs
@@ -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__: the key id is the second underscore-delimited segment (the
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 d9ed334f..e0693f6c 100644
--- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs
+++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs
@@ -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,
diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyThrottlePeerTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyThrottlePeerTests.cs
new file mode 100644
index 00000000..81da4808
--- /dev/null
+++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyThrottlePeerTests.cs
@@ -0,0 +1,50 @@
+using System.Net;
+using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
+
+namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization;
+
+///
+/// Pins the address normalisation shared by the gRPC interceptor and the /metrics handler
+/// (SEC-001): the source port never reaches the limiter partition, and both surfaces produce the
+/// same string for the same client.
+///
+public sealed class ApiKeyThrottlePeerTests
+{
+ /// Strips the port from each Grpc.AspNetCore peer form.
+ /// The ServerCallContext.Peer value.
+ /// The expected address.
+ [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));
+ }
+
+ /// A peer with no address/port shape is kept verbatim rather than guessed at.
+ /// The ServerCallContext.Peer value.
+ [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));
+ }
+
+ ///
+ /// 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.
+ ///
+ [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));
+ }
+}
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 64828fe8..6b28d57c 100644
--- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs
+++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs
@@ -406,6 +406,75 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
Assert.Equal(3, verifier.CallCount);
}
+ ///
+ /// 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.
+ ///
+ /// A task that represents the asynchronous operation.
+ [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 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(
+ () => 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);
+ }
+
+ ///
+ /// 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.
+ ///
+ /// A task that represents the asynchronous operation.
+ [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(
+ () => 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);
+ }
+
///
/// 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)));
}
///