Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(security): key every per-client limiter on the IPv6 /64

Yudhi Armyndharis5a36ea5e23f0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 25a3bc26f..2bd602158 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -181,6 +181,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Media conversion runs only the ffmpeg demuxers of single-file media containers, so a crafted input can no longer make ffmpeg read other local files.
- The MCP pre-auth per-IP limit counts each message of a JSON-RPC batch, so one unauthenticated request can no longer write an audit row per batch element.
- Per-client rate limits key an IPv6 client on its /64, so rotating addresses inside one allocation no longer escapes them ([#1686](https://github.com/rmyndharis/OpenWA/issues/1686)). Thanks @Saksham-official.
+- The MCP, Bull Board and WebSocket pre-auth limiters, the WebSocket rate-limit audit sampler, the per-client upload body budget and the health route's auth-failure audit limiter key an IPv6 client on its /64 as well ([#1695](https://github.com/rmyndharis/OpenWA/issues/1695)).
## [0.23.5] - 2026-09-15
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index f8934b3d9..cf91b7ca8 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -269,6 +269,8 @@ All limits are **global and per client IP** (resolved through `TRUSTED_PROXIES`)
TTL values are in milliseconds. The `/api/metrics` and `/api/health*` routes are exempt (`@SkipThrottle`). To enforce tighter per-route limits, lower the global windows or add a limiter at your reverse proxy.
+An IPv6 client is keyed on its /64, so rotating addresses inside one allocation does not mint fresh buckets. The same key is used by every other per-client limit: the MCP and Bull Board pre-auth throttles, the WebSocket limits below, the per-client share of the in-flight body budget, and the health route's auth-failure audit bound. `allowedIps` matching and audit rows still see the full address.
+
### Response on limit
Exceeding a window returns `429 Too Many Requests`. Because the windows are **named** throttlers (`short` / `medium` / `long`), `@nestjs/throttler` suffixes every rate-limit header with the throttler name, so there are no unsuffixed `X-RateLimit-*` headers. `Retry-After` is the exception: on a `429` the guard emits the plain spelling too, because no HTTP client reads a suffixed one.
@@ -289,11 +291,11 @@ The API exposes the rate-limit headers via CORS (`exposedHeaders`) so browser cl
Socket.IO frames never pass through the Nest enhancer pipeline, so the HTTP windows above do **not** apply to the WebSocket surface. `EventsGateway` enforces its own in-process limits instead (all keyed in-memory per process; any blank/non-positive/non-numeric env value falls back to the default):
-| Limit | Keyed on | Default | Env overrides |
-| ------------------------------------------------------------------- | ---------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------- |
-| Client frames (subscribe/unsubscribe/ping) — token bucket | API key (IP before auth completes) | 60 frames/s sustained, 120-frame burst | `WS_RATE_LIMIT_FRAME_PER_SECOND` / `WS_RATE_LIMIT_FRAME_BURST` |
-| New handshakes — sliding window, enforced **before** key validation | client IP (resolved through `TRUSTED_PROXIES`) | 10 per 60 s | `WS_RATE_LIMIT_HANDSHAKE_MAX` / `WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS` |
-| Simultaneous sockets | API key | 16 | `WS_MAX_SOCKETS_PER_KEY` |
+| Limit | Keyed on | Default | Env overrides |
+| ------------------------------------------------------------------- | --------------------------------------------------------------- | -------------------------------------- | ------------------------------------------------------------------- |
+| Client frames (subscribe/unsubscribe/ping) — token bucket | API key (IP, IPv6 on its /64, before auth completes) | 60 frames/s sustained, 120-frame burst | `WS_RATE_LIMIT_FRAME_PER_SECOND` / `WS_RATE_LIMIT_FRAME_BURST` |
+| New handshakes — sliding window, enforced **before** key validation | client IP (resolved through `TRUSTED_PROXIES`, IPv6 on its /64) | 10 per 60 s | `WS_RATE_LIMIT_HANDSHAKE_MAX` / `WS_RATE_LIMIT_HANDSHAKE_WINDOW_MS` |
+| Simultaneous sockets | API key | 16 | `WS_MAX_SOCKETS_PER_KEY` |
The frame budget is sized ~6x above legitimate traffic: the dashboard emits ~8 subscribe frames at page mount and only occasional ping/unsubscribe frames afterwards (server→client event fan-out is not limited). The handshake window stops an unauthenticated connection flood from forcing a DB `validateApiKey` per attempt; Socket.IO's exponential-backoff reconnect (~6 attempts/min per tab) stays under it. The socket cap covers multi-tab dashboards and SDK clients sharing one key. A rejected handshake or excess socket is answered with a `RATE_LIMITED` error frame and a clean disconnect; an over-budget frame gets a `RATE_LIMITED` error frame and is not dispatched. Violations are audited as `rate_limit_exceeded`, sampled to at most one row per subject+kind per minute (suppressed occurrences are counted into the next row) so the audit trail itself cannot become the flood.
diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.ts
index 29b7d8c9b..21fda06ba 100644
--- a/src/common/security/bull-board-auth.middleware.spec.ts
+++ b/src/common/security/bull-board-auth.middleware.spec.ts
@@ -214,6 +214,23 @@ describe('BullBoardAuthMiddleware pre-auth IP throttle (mirrors MCP createIpThro
expect(authService.validateApiKey).toHaveBeenCalledWith('admin', '203.0.113.9');
});
+ it('buckets an IPv6 client on its /64 but validates the key against the full address', async () => {
+ const mw = adminMw(1);
+ const headers = { 'x-api-key': 'admin' };
+ const first = jest.fn();
+ await mw.use(reqFromIp('2001:db8:1:2::a', headers), res, first);
+ expect(first).toHaveBeenCalledWith();
+ expect(authService.validateApiKey).toHaveBeenCalledWith('admin', '2001:db8:1:2::a');
+
+ const sameSubnet = jest.fn();
+ await mw.use(reqFromIp('2001:db8:1:2::b', headers), res, sameSubnet);
+ expect((firstNextArg(sameSubnet) as HttpException).getStatus()).toBe(429);
+
+ const otherSubnet = jest.fn();
+ await mw.use(reqFromIp('2001:db8:1:3::a', headers), res, otherSubnet);
+ expect(otherSubnet).toHaveBeenCalledWith();
+ });
+
it('a missing key still consumes a throttle slot (pre-auth gate fires first)', async () => {
const mw = adminMw(1);
// First request: no key → Unauthorized, but the throttle slot is consumed (check runs before extractKey).
diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.ts
index 74faf5f5c..5abd1683d 100644
--- a/src/common/security/bull-board-auth.middleware.ts
+++ b/src/common/security/bull-board-auth.middleware.ts
@@ -6,7 +6,7 @@ import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';
import { AuditService } from '../../modules/audit/audit.service';
import { AuditAction } from '../../modules/audit/entities/audit-log.entity';
import { KeyRateLimiter, readIpRateLimitConfig } from '../../modules/mcp/mcp-rate-limit';
-import { resolveClientIp } from '../utils/ip';
+import { limiterKeyForIp, resolveClientIp } from '../utils/ip';
import { setRequestActor } from '../services/request-context';
/**
@@ -62,7 +62,7 @@ export class BullBoardAuthMiddleware implements NestMiddleware {
// Pre-auth, per-IP throttle — runs BEFORE the credential check so a login-attempt flood is rejected
// before the DB lookup. Mirrors MCP's createIpThrottle. Throws HttpException(429) when exceeded;
// forwarded to Nest's exception layer below as a standard 429.
- this.ipRateLimiter.check(clientIp);
+ this.ipRateLimiter.check(limiterKeyForIp(clientIp));
const rawKey = this.extractKey(req);
if (!rawKey) {
diff --git a/src/common/utils/ip.spec.ts b/src/common/utils/ip.spec.ts
index 4210838bc..56eb8302e 100644
--- a/src/common/utils/ip.spec.ts
+++ b/src/common/utils/ip.spec.ts
@@ -1,4 +1,4 @@
-import { normalizeIp, ipMatches } from './ip';
+import { normalizeIp, ipMatches, limiterKeyForIp } from './ip';
describe('normalizeIp', () => {
it('strips an IPv4-mapped IPv6 prefix', () => {
@@ -14,6 +14,24 @@ describe('normalizeIp', () => {
});
});
+describe('limiterKeyForIp', () => {
+ it('gives two IPv6 addresses in one /64 the same key', () => {
+ expect(limiterKeyForIp('2001:db8:1:2::a')).toBe(limiterKeyForIp('2001:db8:1:2:ffff:ffff:ffff:ffff'));
+ expect(limiterKeyForIp('2001:db8:1:2::a')).toBe('2001:db8:1:2::/64');
+ });
+
+ it('keeps IPv6 addresses in different /64s apart', () => {
+ expect(limiterKeyForIp('2001:db8:1:2::a')).not.toBe(limiterKeyForIp('2001:db8:1:3::a'));
+ });
+
+ it('keys IPv4 and loopback as they are, and an IPv4-mapped address as its IPv4 form', () => {
+ expect(limiterKeyForIp('203.0.113.7')).toBe('203.0.113.7');
+ expect(limiterKeyForIp('::ffff:203.0.113.7')).toBe('203.0.113.7');
+ expect(limiterKeyForIp('::1')).toBe('::1');
+ expect(limiterKeyForIp('')).toBe('');
+ });
+});
+
describe('ipMatches', () => {
it('matches an exact IP', () => {
expect(ipMatches('10.0.0.5', '10.0.0.5')).toBe(true);
diff --git a/src/common/utils/ip.ts b/src/common/utils/ip.ts
index 817228042..5ae9205d1 100644
--- a/src/common/utils/ip.ts
+++ b/src/common/utils/ip.ts
@@ -1,3 +1,5 @@
+import { normalizeIp as maskIpv6Subnet } from '@nestjs/throttler';
+
/**
* Strip an IPv4-mapped IPv6 prefix so comparisons work consistently.
* Node often reports socket addresses as `::ffff:1.2.3.4` behind dual-stack
@@ -57,6 +59,18 @@ export function resolveClientIp(req: RequestLike, trustedProxies: string[]): str
return socketIp;
}
+/**
+ * Key for a per-client limiter, budget or counter: an IPv6 address is masked to its /64 (the
+ * `@nestjs/throttler` default the global guard uses), so a client holding a /64 cannot rotate
+ * addresses into fresh buckets. IPv4 and loopback addresses come back unchanged, and an IPv4-mapped
+ * address as its dotted IPv4 form.
+ * For limiter keys ONLY: allowlist matching, audit rows, logs and responses need the real
+ * address from `resolveClientIp`.
+ */
+export function limiterKeyForIp(ip: string): string {
+ return maskIpv6Subnet(ip, 64);
+}
+
function ipv4ToInt(ip: string): number | null {
const parts = ip.split('.');
if (parts.length !== 4) return null;
diff --git a/src/config/inflight-body-budget.spec.ts b/src/config/inflight-body-budget.spec.ts
index 0acc75258..55423e79a 100644
--- a/src/config/inflight-body-budget.spec.ts
+++ b/src/config/inflight-body-budget.spec.ts
@@ -396,6 +396,23 @@ describe('stall reaper', () => {
expect(other).toHaveBeenCalledTimes(1);
});
+ it('keys an IPv6 client on its /64, so a rotated address draws on the same share', () => {
+ const budget = createInflightBodyBudget(1000);
+ const { next: firstOk } = runFrom(budget, '2001:db8:1:2::a', { 'content-length': '400' });
+ expect(firstOk).toHaveBeenCalledTimes(1);
+
+ const { next: sameSubnet, state } = runFrom(budget, '2001:db8:1:2::b', { 'content-length': '200' });
+ expect(sameSubnet).not.toHaveBeenCalled();
+ expect(state.code).toBe(503);
+
+ const probe = makeReq();
+ (probe as unknown as { socket: { remoteAddress: string } }).socket.remoteAddress = '2001:db8:1:2::ffff';
+ expect(budget.clientBytes(probe as never)).toBe(400);
+
+ const { next: otherSubnet } = runFrom(budget, '2001:db8:1:3::a', { 'content-length': '400' });
+ expect(otherSubnet).toHaveBeenCalledTimes(1);
+ });
+
it('releases the client ledger exactly once: a finished body frees the share', () => {
const budget = createInflightBodyBudget(1000);
const { res } = runFrom(budget, '198.51.100.1', { 'content-length': '400' });
diff --git a/src/config/inflight-body-budget.ts b/src/config/inflight-body-budget.ts
index c857aa956..0b5c96864 100644
--- a/src/config/inflight-body-budget.ts
+++ b/src/config/inflight-body-budget.ts
@@ -34,7 +34,7 @@
*/
import { Request, Response, NextFunction } from 'express';
import { resolveBodyLimit } from './bootstrap-security';
-import { resolveClientIp } from '../common/utils/ip';
+import { limiterKeyForIp, resolveClientIp } from '../common/utils/ip';
/**
* Default budget = 4 × the per-request body cap: a handful of concurrent full-size media uploads
@@ -134,8 +134,9 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
const trustedProxies = options?.trustedProxies ?? [];
const share = Math.min(1, Math.max(Number.EPSILON, options?.perClientShare ?? 0.5));
const perClientCap = Math.max(1, Math.floor(budgetBytes * share));
- // Per-client in-flight bytes. The key is the resolved client IP; entries are created lazily and
- // deleted by the same exactly-once release that decrements the aggregate, so the map cannot
+ // Per-client in-flight bytes, keyed on the resolved client IP (an IPv6 client on its /64).
+ // Entries are created lazily and deleted by the same exactly-once release that decrements the
+ // aggregate, so the map cannot
// leak a client that finished. A cap on the MAP itself guards the pathological many-spoofed-IPs
// case: past it, a NEW client key is treated as busiest (refused) rather than evicting a live
// one - refusing beats corrupting another client's accounting.
@@ -216,7 +217,7 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
// The per-client check is what makes the DoS bounded per attacker rather than per deployment:
// four trickle connections from one source exhaust only that source's share, and every other
// client's uploads still land.
- const clientKey = resolveClientIp(req, trustedProxies);
+ const clientKey = limiterKeyForIp(resolveClientIp(req, trustedProxies));
const clientBusy = clientInFlight.get(clientKey) ?? 0;
const mapAtCapacity = clientInFlight.size >= MAX_TRACKED_CLIENTS && !clientInFlight.has(clientKey);
if (inFlightBytes + reserved > budgetBytes || clientBusy + reserved > perClientCap || mapAtCapacity) {
@@ -327,7 +328,7 @@ export function createInflightBodyBudget(budgetBytes: number, options?: Inflight
return {
middleware,
currentBytes: () => inFlightBytes,
- clientBytes: req => clientInFlight.get(resolveClientIp(req, trustedProxies)) ?? 0,
+ clientBytes: req => clientInFlight.get(limiterKeyForIp(resolveClientIp(req, trustedProxies))) ?? 0,
};
}
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.ts
index b2090cefb..82dfed756 100644
--- a/src/modules/events/events.gateway.spec.ts
+++ b/src/modules/events/events.gateway.spec.ts
@@ -701,9 +701,9 @@ describe('EventsGateway rate limiting', () => {
let auditService: { logWarn: jest.Mock };
let savedEnv: Record<string, string | undefined>;
- const makeSock = (id: string, auth: { apiKey?: string } = {}): MockSocket => ({
+ const makeSock = (id: string, auth: { apiKey?: string } = {}, address = '203.0.113.5'): MockSocket => ({
id,
- handshake: { headers: {}, query: {}, auth, address: '203.0.113.5' },
+ handshake: { headers: {}, query: {}, auth, address },
data: {},
emit: jest.fn(),
disconnect: jest.fn(),
@@ -947,6 +947,54 @@ describe('EventsGateway rate limiting', () => {
});
});
+ describe('IPv6 clients are limited on their /64', () => {
+ const ipOf = ([, ctx]: [AuditAction, WarnContext?]): unknown =>
+ (ctx as { ipAddress?: string } | undefined)?.ipAddress;
+
+ it('shares the handshake window and the violation sample across a /64, keeping the real address', async () => {
+ process.env.WS_RATE_LIMIT_HANDSHAKE_MAX = '1';
+ authService.validateApiKey.mockRejectedValue(new Error('bad key'));
+ const gw = buildGateway();
+
+ await gw.handleConnection(asSocket(makeSock('a', { apiKey: 'good' }, '2001:db8:1:2::a')));
+ const rotatedOnce = makeSock('b', { apiKey: 'good' }, '2001:db8:1:2::b');
+ await gw.handleConnection(asSocket(rotatedOnce));
+ const rotatedTwice = makeSock('c', { apiKey: 'good' }, '2001:db8:1:2::c');
+ await gw.handleConnection(asSocket(rotatedTwice));
+ expect(rotatedOnce.emit).toHaveBeenCalledWith('message', expect.objectContaining({ code: 'RATE_LIMITED' }));
+ expect(rotatedTwice.emit).toHaveBeenCalledWith('message', expect.objectContaining({ code: 'RATE_LIMITED' }));
+ expect(authService.validateApiKey).toHaveBeenCalledTimes(1);
+
+ const rateLimited = warnCalls().filter(([action]) => action === AuditAction.RATE_LIMIT_EXCEEDED);
+ expect(rateLimited).toHaveLength(1);
+ expect(ipOf(rateLimited[0])).toBe('2001:db8:1:2::b');
+
+ await gw.handleConnection(asSocket(makeSock('d', { apiKey: 'good' }, '2001:db8:1:3::a')));
+ expect(authService.validateApiKey).toHaveBeenCalledTimes(2);
+ });
+
+ it('meters a not-yet-authenticated socket on its /64', async () => {
+ process.env.WS_RATE_LIMIT_FRAME_PER_SECOND = '1';
+ process.env.WS_RATE_LIMIT_FRAME_BURST = '1';
+ const gw = buildGateway();
+ const ping = { type: 'ping', requestId: 'p' } as unknown as WSClientMessage;
+
+ const first = (await gw.handleMessage(asSocket(makeSock('a', {}, '2001:db8:1:2::a')), ping)) as { type: string };
+ expect(first.type).not.toBe('error');
+ const sameSubnet = (await gw.handleMessage(asSocket(makeSock('b', {}, '2001:db8:1:2::b')), ping)) as {
+ code?: string;
+ };
+ expect(sameSubnet.code).toBe('RATE_LIMITED');
+ const frameViolation = warnCalls().find(([action]) => action === AuditAction.RATE_LIMIT_EXCEEDED);
+ expect(frameViolation && ipOf(frameViolation)).toBe('2001:db8:1:2::b');
+
+ const otherSubnet = (await gw.handleMessage(asSocket(makeSock('c', {}, '2001:db8:1:3::a')), ping)) as {
+ type: string;
+ };
+ expect(otherSubnet.type).not.toBe('error');
+ });
+ });
+
describe('per-key simultaneous socket cap', () => {
it('rejects the socket above the cap with a clear error, and frees the slot on disconnect', async () => {
process.env.WS_MAX_SOCKETS_PER_KEY = '2';
diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.ts
index 0e9f4f79b..39ec75de6 100644
--- a/src/modules/events/events.gateway.ts
+++ b/src/modules/events/events.gateway.ts
@@ -15,7 +15,7 @@ import { AuthService } from '../auth/auth.service';
import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { resolveCorsPolicy } from '../../config/bootstrap-security';
-import { resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';
+import { limiterKeyForIp, resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';
import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';
import { ApiKeyRole, type ApiKey } from '../auth/entities/api-key.entity';
import { apiKeyAuthorizationFingerprint, apiKeyExpiryTime } from '../auth/api-key-authorization';
@@ -312,7 +312,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
// Pre-auth, per-IP handshake throttle. This must run BEFORE any credential handling: an
// unauthenticated handshake flood otherwise reaches the DB validateApiKey below on every
// attempt (same gap the MCP pre-auth IP throttle covers for the /mcp mount).
- if (!this.handshakeLimiter.allow(clientIp)) {
+ if (!this.handshakeLimiter.allow(limiterKeyForIp(clientIp))) {
this.logger.warn(`Client ${client.id} rejected: handshake rate limit exceeded (ip: ${clientIp})`);
this.noteRateLimitViolation('handshake', { ipAddress: clientIp });
client.emit('message', this.createError('RATE_LIMITED', 'Too many connection attempts, retry later'));
@@ -435,7 +435,8 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
// Over-budget frames get an error frame back and are NOT dispatched to a handler — in
// particular they never reach the per-subscribe DB re-validation.
const frameSubject =
- (client.data as { apiKey?: Pick<ApiKey, 'id'> } | undefined)?.apiKey?.id ?? this.resolveClientIp(client);
+ (client.data as { apiKey?: Pick<ApiKey, 'id'> } | undefined)?.apiKey?.id ??
+ limiterKeyForIp(this.resolveClientIp(client));
if (!this.frameLimiter.allow(frameSubject)) {
const requestId = (message as { requestId?: string } | undefined)?.requestId;
this.noteRateLimitViolation('frame', {
@@ -608,7 +609,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate
kind: 'handshake' | 'frame' | 'sockets',
subject: { apiKeyId?: string; ipAddress?: string },
): void {
- const mapKey = `${kind}:${subject.apiKeyId ?? subject.ipAddress ?? 'unknown'}`;
+ const mapKey = `${kind}:${subject.apiKeyId ?? (subject.ipAddress ? limiterKeyForIp(subject.ipAddress) : 'unknown')}`;
const now = Date.now();
const prior = this.violations.get(mapKey);
if (prior && now - prior.since < EventsGateway.VIOLATION_AUDIT_WINDOW_MS) {
diff --git a/src/modules/health/health.controller.spec.ts b/src/modules/health/health.controller.spec.ts
index b5a3e403c..41861f4a2 100644
--- a/src/modules/health/health.controller.spec.ts
+++ b/src/modules/health/health.controller.spec.ts
@@ -17,8 +17,8 @@ describe('HealthController', () => {
const validateApiKey = jest.fn();
const logWarn = jest.fn().mockResolvedValue(null);
- const reqWith = (headers: Record<string, string> = {}): Request =>
- ({ headers, socket: { remoteAddress: '127.0.0.1' } }) as unknown as Request;
+ const reqWith = (headers: Record<string, string> = {}, ip = '127.0.0.1'): Request =>
+ ({ headers, socket: { remoteAddress: ip } }) as unknown as Request;
beforeEach(async () => {
mainQuery.mockResolvedValue([{ '1': 1 }]);
@@ -132,6 +132,24 @@ describe('HealthController', () => {
});
});
+ describe('key-probe audit bound for IPv6', () => {
+ it('shares one audit budget across a /64 and records the full address', async () => {
+ validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));
+
+ for (let i = 0; i < 15; i++) {
+ await controller.check(reqWith({ 'x-api-key': 'owa_k1_probe' }, `2001:db8:1:2::${(i + 1).toString(16)}`));
+ }
+ expect(logWarn).toHaveBeenCalledTimes(10);
+ expect(logWarn).toHaveBeenLastCalledWith(
+ AuditAction.API_KEY_AUTH_FAILED,
+ expect.objectContaining({ ipAddress: '2001:db8:1:2::a' }),
+ );
+
+ await controller.check(reqWith({ 'x-api-key': 'owa_k1_probe' }, '2001:db8:1:3::1'));
+ expect(logWarn).toHaveBeenCalledTimes(11);
+ });
+ });
+
describe('liveness', () => {
it('returns ok (static — does not probe dependencies)', () => {
expect(controller.liveness().status).toBe('ok');
diff --git a/src/modules/health/health.controller.ts b/src/modules/health/health.controller.ts
index abeaaf1a4..6e0832ee0 100644
--- a/src/modules/health/health.controller.ts
+++ b/src/modules/health/health.controller.ts
@@ -12,7 +12,7 @@ import { AuthService } from '../auth/auth.service';
import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { SlidingWindowLimiter } from '../events/ws-rate-limit';
-import { resolveClientIp } from '../../common/utils/ip';
+import { limiterKeyForIp, resolveClientIp } from '../../common/utils/ip';
interface DependencyStatus {
status: 'up' | 'down';
@@ -91,7 +91,7 @@ export class HealthController {
// route was the one blind spot: the failure only withheld the version, invisibly. Fire-and-
// forget and rate-bounded per IP (constructor): audit logging must never fail the probe.
const failureIp = resolveClientIp(req, this.configService.get<string[]>('security.trustedProxies') ?? []);
- if (this.authFailureAuditLimiter.allow(failureIp)) {
+ if (this.authFailureAuditLimiter.allow(limiterKeyForIp(failureIp))) {
void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {
ipAddress: failureIp,
method: req.method,
diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.ts
index d84d4cf8e..2a60eebd8 100644
--- a/src/modules/mcp/mcp.server.spec.ts
+++ b/src/modules/mcp/mcp.server.spec.ts
@@ -117,6 +117,19 @@ describe('createIpThrottle (pre-auth per-IP MCP throttle)', () => {
expect(next).toHaveBeenCalledWith();
});
+ it('buckets an IPv6 client on its /64, so rotating addresses inside it shares one bucket', () => {
+ const throttle = createIpThrottle(new KeyRateLimiter(1, 60_000));
+ throttle(makeReq('2001:db8:1:2::a'), makeRes() as unknown as Response, jest.fn());
+
+ const sameSubnet = jest.fn();
+ throttle(makeReq('2001:db8:1:2::b'), makeRes() as unknown as Response, sameSubnet);
+ expect(sameSubnet).not.toHaveBeenCalled();
+
+ const otherSubnet = jest.fn();
+ throttle(makeReq('2001:db8:1:3::a'), makeRes() as unknown as Response, otherSubnet);
+ expect(otherSubnet).toHaveBeenCalledWith();
+ });
+
// Every element of a JSON-RPC batch is dispatched (and each tools/call runs its own key lookup and
// auth-failure audit), so the budget is charged per message, not per HTTP request.
const call = { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'SessionFindAll', arguments: {} } };
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index 01a224536..66a1a482e 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -13,7 +13,7 @@ import type { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { handleToolError, jsonToolResult, smartToolResult } from './tool-result';
import type { KeyRateLimiter } from './mcp-rate-limit';
-import { resolveClientIp } from '../../common/utils/ip';
+import { limiterKeyForIp, resolveClientIp } from '../../common/utils/ip';
import { resolveBodyLimit } from '../../config/bootstrap-security';
const logger = new Logger('McpServer');
@@ -171,7 +171,7 @@ export interface MountMcpServerOptions {
*/
export function createIpThrottle(ipRateLimiter: KeyRateLimiter): RequestHandler {
return (req, res, next) => {
- const ip = resolveClientIp(req, readTrustedProxies());
+ const ip = limiterKeyForIp(resolveClientIp(req, readTrustedProxies()));
// The unit of work is the JSON-RPC message, not the HTTP request: the transport dispatches every
// element of a batch, and each tools/call element runs its own key lookup and auth-failure audit.
// An over-budget batch throws on the first check past the cap, so a huge array costs at most