Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(security): audit failed key probes on the health route

Yudhi Armyndharisc0cba05b8c9e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2c46339f9..3c0f68119 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- `GET /api/health` audits a presented-but-invalid API key (`API_KEY_AUTH_FAILED`) like every other key-validation surface, rate-bounded per IP; probing through the unthrottled health route was invisible to the audit log.
- Both bundled Compose files forward every documented runtime knob; `WEBHOOK_SSRF_REDIRECTS`, `PLUGIN_INSTALL_REQUIRE_PIN` and ~75 other `.env` settings were unreachable in the container. A spec now derives the required list from `.env.example`.
- Ingress delivery ids BullMQ refuses at enqueue (numeric, `redrive:<uuid>`, `0:`-led) are hashed to a legal job id, namespaced by plugin/instance; the old refusal read as a Redis failure and silently degraded the delivery to inline dispatch with no retry.
- One precise unique-violation predicate (`23505`, `SQLITE_CONSTRAINT_UNIQUE`/`_PRIMARYKEY`): the old prefix match treated every SQLite constraint failure (FK/NOT NULL/CHECK) as a duplicate, swallowing genuine persistence failures and answering misleading 409s.
diff --git a/src/modules/health/health.controller.spec.ts b/src/modules/health/health.controller.spec.ts
index 30cfd588f..b5a3e403c 100644
--- a/src/modules/health/health.controller.spec.ts
+++ b/src/modules/health/health.controller.spec.ts
@@ -6,6 +6,8 @@ import { Request } from 'express';
import { HealthController } from './health.controller';
import { ShutdownService } from '../../common/services/shutdown.service';
import { AuthService } from '../auth/auth.service';
+import { AuditService } from '../audit/audit.service';
+import { AuditAction } from '../audit/entities/audit-log.entity';
describe('HealthController', () => {
let controller: HealthController;
@@ -13,6 +15,7 @@ describe('HealthController', () => {
const dataQuery = jest.fn();
const isShuttingDown = jest.fn();
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;
@@ -29,6 +32,7 @@ describe('HealthController', () => {
{ provide: getDataSourceToken('data'), useValue: { query: dataQuery } },
{ provide: ShutdownService, useValue: { isShuttingDown } },
{ provide: AuthService, useValue: { validateApiKey } },
+ { provide: AuditService, useValue: { logWarn } },
{ provide: ConfigService, useValue: { get: () => undefined } },
],
}).compile();
@@ -41,6 +45,7 @@ describe('HealthController', () => {
dataQuery.mockReset();
isShuttingDown.mockReset();
validateApiKey.mockReset();
+ logWarn.mockClear(); // keep the resolved value, drop cross-test call history
});
describe('check', () => {
@@ -86,6 +91,47 @@ describe('HealthController', () => {
});
});
+ describe('key-probe auditing', () => {
+ it('audits a presented-but-invalid key like every other key-validation surface', async () => {
+ validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));
+
+ const result = await controller.check(reqWith({ 'x-api-key': 'owa_k1_probe' }));
+
+ expect(result.status).toBe('ok'); // the probe itself never fails
+ expect(result).not.toHaveProperty('version');
+ expect(logWarn).toHaveBeenCalledWith(AuditAction.API_KEY_AUTH_FAILED, {
+ ipAddress: '127.0.0.1',
+ method: undefined,
+ path: undefined,
+ errorMessage: 'Invalid API key',
+ });
+ });
+
+ it('does not audit an absent key (uptime probes stay free of audit noise)', async () => {
+ await controller.check(reqWith());
+
+ expect(logWarn).not.toHaveBeenCalled();
+ });
+
+ it('does not audit a valid key', async () => {
+ validateApiKey.mockResolvedValue({ id: 'k1' });
+
+ await controller.check(reqWith({ 'x-api-key': 'owa_k1_valid' }));
+
+ expect(logWarn).not.toHaveBeenCalled();
+ });
+
+ it('bounds the audit writes per source IP so a probe flood cannot fill the audit log', 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_${i}` }));
+ }
+
+ expect(logWarn).toHaveBeenCalledTimes(10);
+ });
+ });
+
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 7348c5d4b..abeaaf1a4 100644
--- a/src/modules/health/health.controller.ts
+++ b/src/modules/health/health.controller.ts
@@ -9,6 +9,9 @@ import { Public } from '../auth/decorators/auth.decorators';
import { SkipThrottle } from '@nestjs/throttler';
import { ShutdownService } from '../../common/services/shutdown.service';
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';
interface DependencyStatus {
@@ -40,7 +43,15 @@ export class HealthController {
private readonly shutdownService: ShutdownService,
private readonly authService: AuthService,
private readonly configService: ConfigService,
- ) {}
+ private readonly auditService: AuditService,
+ ) {
+ // Bounds the audit rows one source IP can write per minute through this deliberately
+ // unthrottled route: the health probes themselves must never be rate-limited, but without a
+ // cap a key-probing flood would turn the audit trail into the flood's storage.
+ this.authFailureAuditLimiter = new SlidingWindowLimiter(10, 60_000);
+ }
+
+ private readonly authFailureAuditLimiter: SlidingWindowLimiter;
@Get()
@ApiOperation({ summary: 'Basic health check' })
@@ -71,10 +82,23 @@ export class HealthController {
(typeof xApiKey === 'string' && xApiKey) || (authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : undefined);
if (!rawKey) return false;
try {
- const trustedProxies = this.configService.get<string[]>('security.trustedProxies') ?? [];
- await this.authService.validateApiKey(rawKey, resolveClientIp(req, trustedProxies));
+ const clientIp = resolveClientIp(req, this.configService.get<string[]>('security.trustedProxies') ?? []);
+ await this.authService.validateApiKey(rawKey, clientIp);
return true;
- } catch {
+ } 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(failureIp)) {
+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {
+ ipAddress: failureIp,
+ method: req.method,
+ path: req.path,
+ errorMessage: err instanceof Error ? err.message : String(err),
+ });
+ }
return false;
}
}