Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(health): bound API key lookups on the health route per client
Yudhi Armyndharisef95cc5b8730
diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex 1d20eaa41..2c8f248f2 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -278,9 +278,9 @@ Each window is counted **per route handler per client IP** (the IP resolved thro| `medium` | 100 requests | 60 s | `RATE_LIMIT_MEDIUM_TTL` / `RATE_LIMIT_MEDIUM_LIMIT` || `long` | 1000 requests | 3600 s | `RATE_LIMIT_LONG_TTL` / `RATE_LIMIT_LONG_LIMIT` |-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.+TTL values are in milliseconds. The `/api/metrics` and `/api/health*` routes are exempt (`@SkipThrottle`); `/api/health` still looks up at most 30 failed key presentations per client per minute, and past that answers without `version` and without a key lookup. 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, the health route's auth-failure audit bound, and the REST and queue-dashboard auth-failure audit bound. `allowedIps` matching and audit rows still see the full address.+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, the health route's key-lookup budget and auth-failure audit bound, and the REST and queue-dashboard auth-failure audit bound. `allowedIps` matching and audit rows still see the full address.### Response on limitdiff --git a/src/modules/health/health.controller.spec.ts b/src/modules/health/health.controller.spec.tsindex b7a3397b3..de14676bf 100644--- a/src/modules/health/health.controller.spec.ts+++ b/src/modules/health/health.controller.spec.ts@@ -161,6 +161,54 @@ describe('HealthController', () => {});});+ describe('key-validation budget', () => {+ const presented = (ip?: string) => reqWith({ 'x-api-key': 'owa_k1_probe' }, ip);++ it('stops looking up keys for a client after 30 failed presentations a minute', async () => {+ validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));++ for (let i = 0; i < 35; i++) {+ const result = await controller.check(presented());+ expect(result.status).toBe('ok');+ expect(result).not.toHaveProperty('version');+ }++ expect(validateApiKey).toHaveBeenCalledTimes(30);+ });++ it('keeps a separate budget per client, shared across one IPv6 /64', async () => {+ validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));+ for (let i = 0; i < 35; i++) await controller.check(presented());+ await controller.check(presented('192.0.2.9'));+ expect(validateApiKey).toHaveBeenCalledTimes(31);++ validateApiKey.mockClear();+ for (let i = 0; i < 35; i++) await controller.check(presented(`2001:db8:1:2::${(i + 1).toString(16)}`));+ expect(validateApiKey).toHaveBeenCalledTimes(30);+ await controller.check(presented('2001:db8:1:3::1'));+ expect(validateApiKey).toHaveBeenCalledTimes(31);+ });++ it('never spends the budget on a key that validates', async () => {+ validateApiKey.mockResolvedValue({ id: 'k1' });++ for (let i = 0; i < 40; i++) {+ expect((await controller.check(presented())).version).toBeDefined();+ }++ expect(validateApiKey).toHaveBeenCalledTimes(40);+ });++ it('does not charge keyless probes', async () => {+ for (let i = 0; i < 40; i++) await controller.check(reqWith());+ validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));++ await controller.check(presented());++ expect(validateApiKey).toHaveBeenCalledTimes(1);+ });+ });+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.tsindex c4f868c4f..9f04ce309 100644--- a/src/modules/health/health.controller.ts+++ b/src/modules/health/health.controller.ts@@ -54,6 +54,11 @@ export class HealthController {private readonly authFailureAuditLimiter: SlidingWindowLimiter;+ // Bounds the key lookups one client can drive through this unthrottled route. Charged before the+ // lookup and refunded when the key validates, so only failed presentations spend it: past the+ // budget the probe still answers 200, without `version` and without touching the key table.+ private readonly keyValidationLimiter = new SlidingWindowLimiter(30, 60_000);+@Get()@ApiOperation({ summary: 'Basic health check' })@ApiResponse({ status: 200, description: 'Application is healthy', type: HealthCheckResponseDto })@@ -80,19 +85,21 @@ export class HealthController {const xApiKey = req.headers['x-api-key'];const rawKey = (typeof xApiKey === 'string' && xApiKey) || bearerToken(req.headers['authorization']);if (!rawKey) return false;+ const clientIp = resolveClientIp(req, this.configService.get<string[]>('security.trustedProxies') ?? []);+ const subject = limiterKeyForIp(clientIp);+ if (!this.keyValidationLimiter.allow(subject)) return false;try {- const clientIp = resolveClientIp(req, this.configService.get<string[]>('security.trustedProxies') ?? []);await this.authService.validateApiKey(rawKey, clientIp);+ this.keyValidationLimiter.refund(subject);return true;} catch (err) {// A PRESENTED key that failed validation is a credential probe against an endpoint every// other key-validation surface audits (REST guard, WebSocket, MCP mount, Bull Board). This// 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(limiterKeyForIp(failureIp))) {+ if (this.authFailureAuditLimiter.allow(subject)) {void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {- ipAddress: failureIp,+ ipAddress: clientIp,method: req.method,path: req.path,errorMessage: err instanceof Error ? err.message : String(err),