Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(audit): bound auth-failure audit volume and field lengths
Yudhi Armyndharis468424327c2e
diff --git a/docs/04-security-design.md b/docs/04-security-design.mdindex 0e34a448e..3ed1f68ab 100644--- a/docs/04-security-design.md+++ b/docs/04-security-design.md@@ -272,7 +272,7 @@ Each window is counted **per route handler per client IP** (the IP resolved throTTL 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.+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.### Response on limit@@ -494,7 +494,7 @@ flowchart TB### Security Alerts-> **Not implemented.** There is no alerting or automatic temp-block subsystem; the table below is a design target, not shipped behavior. The signals do get recorded — rejected authentication and WebSocket rate-limit violations write persisted audit rows (the latter sampled), and an IP-restricted key used from a disallowed IP also emits a `logger.warn` — but nothing acts on them. Forward the audit log / application log to your SIEM to build these alerts.+> **Not implemented.** There is no alerting or automatic temp-block subsystem; the table below is a design target, not shipped behavior. The signals do get recorded: rejected authentication and WebSocket rate-limit violations write persisted audit rows, and an IP-restricted key used from a disallowed IP also emits a `logger.warn`; but nothing acts on them. A REST or queue-dashboard rejection that names no stored key (missing or unknown) is capped at 10 rows per client IP per minute; a rejection of a stored key (revoked, expired, IP or session refused, insufficient role) is recorded every time. Rate-limit violations are sampled. Forward the audit log / application log to your SIEM to build these alerts.| Event | Severity | Intended action (roadmap) || -------------------- | -------- | ------------------------- |diff --git a/docs/05-database-design.md b/docs/05-database-design.mdindex ebd68d960..d2813f3b5 100644--- a/docs/05-database-design.md+++ b/docs/05-database-design.md@@ -597,7 +597,9 @@ CREATE INDEX "IDX_c69efb19bf127c97e6740ad530" ON audit_logs("createdAt");```**Audit actions** are an enum (`AuditAction`) spanning API-key lifecycle (`api_key_created`,-`api_key_updated`, `api_key_used`, `api_key_revoked`, `api_key_deleted`, `api_key_auth_failed`), session+`api_key_updated`, `api_key_used`, `api_key_revoked`, `api_key_deleted`, `api_key_auth_failed`, capped+at 10 rows per client IP per minute for a REST or queue-dashboard rejection that names no stored key;+a rejection of a stored key is never capped), sessionlifecycle (`session_created`, `session_started`, `session_stopped`, `session_force_killed`,`session_logged_out`, `session_deleted`, `session_qr_generated`, `session_connected`,`session_disconnected`, `session_config_updated`), WhatsApp-imposed account restrictions (`session_restricted`,diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.tsindex d681ad6ff..b37b7212a 100644--- a/src/common/security/bull-board-auth.middleware.spec.ts+++ b/src/common/security/bull-board-auth.middleware.spec.ts@@ -2,11 +2,12 @@ import { HttpException, UnauthorizedException, ForbiddenException } from '@nestjimport { ConfigService } from '@nestjs/config';import { Request, Response } from 'express';import { BullBoardAuthMiddleware } from './bull-board-auth.middleware';-import { AuthService } from '../../modules/auth/auth.service';+import { AuthService, UnresolvedApiKeyException } from '../../modules/auth/auth.service';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 } from '../../modules/mcp/mcp-rate-limit';+import { allowUnauthenticatedAuditRow } from '../../modules/audit/auth-failure-audit-limiter';import * as fs from 'fs';import * as path from 'path';import { runWithRequestId, getRequestActor } from '../services/request-context';@@ -428,6 +429,70 @@ describe('BullBoardAuthMiddleware audit trail', () => {expect(auditService.logInfo).not.toHaveBeenCalled();});+ // Unauthenticated rows are bounded per client IP, on a budget shared with the REST guard. These+ // tests use IPs no other test in this file uses, since the budget is a module-level singleton.+ it('writes at most 10 unauthenticated rows a minute for one IP, while every request still gets its 401', async () => {+ const fromIp = (ip: string): Request =>+ ({ ...reqFor('GET', {}, '/api/admin/queues/'), ip, socket: { remoteAddress: ip } }) as unknown as Request;+ const next = jest.fn();+ for (let i = 0; i < 50; i++) await mw.use(fromIp('198.51.100.81'), res, next);++ expect(next).toHaveBeenCalledTimes(50);+ for (const [err] of next.mock.calls as Array<[unknown]>) expect(err).toBeInstanceOf(UnauthorizedException);+ expect(auditService.logWarn).toHaveBeenCalledTimes(10);++ await mw.use(fromIp('198.51.100.82'), res, jest.fn());+ expect(auditService.logWarn).toHaveBeenCalledTimes(11);+ expect(auditService.logWarn).toHaveBeenLastCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ ipAddress: '198.51.100.82' }),+ );+ });++ it('shares the unauthenticated budget with the REST guard and still records a 403', async () => {+ // Ten rows already written for this IP by the REST guard.+ for (let i = 0; i < 10; i++) expect(allowUnauthenticatedAuditRow('198.51.100.83')).toBe(true);+ const fromIp = (headers: Record<string, unknown>): Request =>+ ({+ ...reqFor('GET', headers, '/api/admin/queues/'),+ ip: '198.51.100.83',+ socket: { remoteAddress: '198.51.100.83' },+ }) as unknown as Request;++ await mw.use(fromIp({}), res, jest.fn());+ expect(auditService.logWarn).not.toHaveBeenCalled();++ authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.OPERATOR });+ authService.hasPermission.mockReturnValue(false);+ const next = jest.fn();+ await mw.use(fromIp({ 'x-api-key': 'op' }), res, next);+ expect(next).toHaveBeenCalledWith(expect.any(ForbiddenException));+ expect(auditService.logWarn).toHaveBeenCalledTimes(1);+ });++ it('still records a rejected stored key from an IP whose budget is spent, but not an unknown one', async () => {+ for (let i = 0; i < 10; i++) expect(allowUnauthenticatedAuditRow('198.51.100.84')).toBe(true);+ const fromIp = (): Request =>+ ({+ ...reqFor('GET', { 'x-api-key': 'k' }, '/api/admin/queues/'),+ ip: '198.51.100.84',+ socket: { remoteAddress: '198.51.100.84' },+ }) as unknown as Request;++ authService.validateApiKey.mockRejectedValue(new UnresolvedApiKeyException('Invalid API key'));+ await mw.use(fromIp(), res, jest.fn());+ expect(auditService.logWarn).not.toHaveBeenCalled();++ authService.validateApiKey.mockRejectedValue(new UnauthorizedException('API key is revoked'));+ const next = jest.fn();+ await mw.use(fromIp(), res, next);+ expect(next).toHaveBeenCalledWith(expect.any(UnauthorizedException));+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ ipAddress: '198.51.100.84', errorMessage: 'API key is revoked' }),+ );+ });+it('degrades gracefully when no audit service is provided (rejections still work)', async () => {const noAuditMw = new BullBoardAuthMiddleware(authService as unknown as AuthService,diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.tsindex 5d63b29bc..1fe7ab3bd 100644--- a/src/common/security/bull-board-auth.middleware.ts+++ b/src/common/security/bull-board-auth.middleware.ts@@ -1,10 +1,11 @@import { Injectable, NestMiddleware, UnauthorizedException, ForbiddenException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { Request, Response, NextFunction } from 'express';-import { AuthService } from '../../modules/auth/auth.service';+import { AuthService, UnresolvedApiKeyException } from '../../modules/auth/auth.service';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 { allowUnauthenticatedAuditRow } from '../../modules/audit/auth-failure-audit-limiter';import { KeyRateLimiter, readIpRateLimitConfig } from '../../modules/mcp/mcp-rate-limit';import { limiterKeyForIp, resolveClientIp } from '../utils/ip';import { bearerToken } from './bearer-token';@@ -29,6 +30,7 @@ import { setRequestActor } from '../services/request-context';* - 401/403 rejections are recorded as WARN API_KEY_AUTH_FAILED, mirroring the REST guard and the* MCP mount. The pre-auth IP throttle above is the flood bound — a throttled 429 is NOT audited,* so a probing flood cannot drown the audit table either.+ * A 401 row also draws on a per-IP budget shared with the REST guard (auth-failure-audit-limiter).* - An authenticated non-GET/HEAD request is recorded as INFO QUEUE_BOARD_MUTATED with method+path.* This is a boundary trace of queue-mutation attempts reaching the Bull Board router (the UI's* retry/remove/pause actions are POSTs); it deliberately does NOT model Bull Board's internal@@ -67,7 +69,7 @@ export class BullBoardAuthMiddleware implements NestMiddleware {const rawKey = this.extractKey(req);if (!rawKey) {- throw new UnauthorizedException('API key is required to access the queue dashboard');+ throw new UnresolvedApiKeyException('API key is required to access the queue dashboard');}const apiKey = await this.authService.validateApiKey(rawKey, clientIp);@@ -118,13 +120,18 @@ export class BullBoardAuthMiddleware implements NestMiddleware {// Audit the rejected/denied attempt for a forensic trail, like the REST guard and the MCP// mount do. A throttle overrun (HttpException 429) is deliberately NOT audited: the limiter// already rejected it, and logging each throttled hit would let a flood write unbounded rows.- if (err instanceof UnauthorizedException || err instanceof ForbiddenException) {- void this.auditService?.logWarn(AuditAction.API_KEY_AUTH_FAILED, {- ipAddress: this.getClientIp(req),- method: req.method,- path: this.auditPath(req),- errorMessage: err instanceof Error ? err.message : String(err),- });+ // A 401 that resolved no key draws on the per-IP budget it shares with the REST guard; any+ // rejection of a stored key, 401 or 403, is always recorded.+ if (this.auditService && (err instanceof UnauthorizedException || err instanceof ForbiddenException)) {+ const clientIp = this.getClientIp(req);+ if (!(err instanceof UnresolvedApiKeyException) || allowUnauthenticatedAuditRow(clientIp)) {+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: clientIp,+ method: req.method,+ path: this.auditPath(req),+ errorMessage: err.message,+ });+ }}// Forward to Nest's exception layer so the response uses the standard format. A throttle overrun// surfaces here as an HttpException(429) → rendered as a standard 429 by the global exception filter.diff --git a/src/modules/audit/audit.service.spec.ts b/src/modules/audit/audit.service.spec.tsindex fe0912451..c169db91d 100644--- a/src/modules/audit/audit.service.spec.ts+++ b/src/modules/audit/audit.service.spec.ts@@ -32,6 +32,30 @@ describe('AuditService', () => {expect(repo.save).toHaveBeenCalledTimes(1);});+ it('log() clamps caller-supplied text to the column bounds before storing it', async () => {+ await service.log(AuditAction.API_KEY_AUTH_FAILED, {+ path: `/api/sessions/${'a'.repeat(16 * 1024)}`,+ userAgent: 'u'.repeat(2000),+ method: 'M'.repeat(50),+ errorMessage: 'e'.repeat(5000),+ });++ const row = (repo.create.mock.calls as unknown[][])[0][0] as Partial<AuditLog>;+ expect(row.path).toHaveLength(500);+ expect(row.path?.startsWith('/api/sessions/aaa')).toBe(true);+ expect(row.userAgent).toHaveLength(500);+ expect(row.method).toHaveLength(10);+ expect(row.errorMessage).toHaveLength(1000);+ });++ it('log() stores short text unchanged', async () => {+ await service.log(AuditAction.API_KEY_AUTH_FAILED, { path: '/api/sessions', method: 'GET', userAgent: 'curl/8' });+ const row = (repo.create.mock.calls as unknown[][])[0][0] as Partial<AuditLog>;+ expect(row).toEqual(+ expect.objectContaining({ path: '/api/sessions', method: 'GET', userAgent: 'curl/8', errorMessage: null }),+ );+ });+it('logInfo/logWarn/logError map to the right severity', async () => {await service.logInfo(AuditAction.API_KEY_USED);await service.logWarn(AuditAction.API_KEY_AUTH_FAILED);diff --git a/src/modules/audit/audit.service.ts b/src/modules/audit/audit.service.tsindex 0cfbf2f6d..1e2a3c77d 100644--- a/src/modules/audit/audit.service.ts+++ b/src/modules/audit/audit.service.ts@@ -10,6 +10,18 @@ import { resolveSessionScope } from '../../common/security/session-scope';/** Upper bound on a single audit-log page, so a large `limit` can't load the whole table at once. */export const MAX_AUDIT_PAGE_SIZE = 200;+/**+ * Caller-supplied text is cut to these lengths before it is stored. The first three match the+ * entity's varchar lengths, which SQLite does not enforce; errorMessage is a text column with no+ * declared bound. Without the clamp one row could carry a request path of many kilobytes.+ */+const MAX_USER_AGENT_LENGTH = 500;+const MAX_METHOD_LENGTH = 10;+const MAX_PATH_LENGTH = 500;+const MAX_ERROR_MESSAGE_LENGTH = 1000;++const clampText = (value: string | undefined, max: number): string | null => (value ? value.slice(0, max) : null);+interface AuditContext {apiKey?: ApiKey;sessionId?: string;@@ -101,12 +113,12 @@ export class AuditService implements OnModuleInit, OnModuleDestroy {sessionId: context.sessionId || null,sessionName: context.sessionName || null,ipAddress: ipAddress || null,- userAgent: context.userAgent || null,- method: context.method || null,- path: context.path || null,+ userAgent: clampText(context.userAgent, MAX_USER_AGENT_LENGTH),+ method: clampText(context.method, MAX_METHOD_LENGTH),+ path: clampText(context.path, MAX_PATH_LENGTH),statusCode: context.statusCode || null,metadata,- errorMessage: context.errorMessage || null,+ errorMessage: clampText(context.errorMessage, MAX_ERROR_MESSAGE_LENGTH),});// Audit logging is best-effort: a failed insert must never turn a succeeded operation into a 500diff --git a/src/modules/audit/auth-failure-audit-limiter.ts b/src/modules/audit/auth-failure-audit-limiter.tsnew file mode 100644index 000000000..6b6e80340--- /dev/null+++ b/src/modules/audit/auth-failure-audit-limiter.ts@@ -0,0 +1,18 @@+import { SlidingWindowLimiter } from '../events/ws-rate-limit';+import { limiterKeyForIp } from '../../common/utils/ip';++/**+ * Per-IP budget for API_KEY_AUTH_FAILED rows written by the REST guard and the Bull Board mount for a+ * rejection that resolved no key (UnresolvedApiKeyException: no key, or a key that matches no row).+ * Such a rejection costs the caller nothing, and the throttler counts per route handler, so without+ * this bound one source could write audit rows as fast as it can send requests. One module-level+ * instance so both surfaces draw on a single budget per client: 10 rows a minute, the same bound the+ * health route applies to its own probes. A rejection of a stored key (revoked, expired, IP or+ * session refused, or a 403) is not charged here; it is always audited.+ */+const limiter = new SlidingWindowLimiter(10, 60_000);++/** True while `clientIp` still has budget for an unauthenticated auth-failure audit row. */+export function allowUnauthenticatedAuditRow(clientIp: string): boolean {+ return limiter.allow(limiterKeyForIp(clientIp));+}diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.tsindex 6bd5768f4..bbfc7b4e2 100644--- a/src/modules/auth/auth.service.spec.ts+++ b/src/modules/auth/auth.service.spec.ts@@ -8,7 +8,7 @@ import { Repository } from 'typeorm';import { UnauthorizedException, NotFoundException, ConflictException } from '@nestjs/common';import { createHash, createHmac } from 'crypto';import * as fs from 'fs';-import { AuthService, resolveSeedApiKey, bannerKeyLine } from './auth.service';+import { AuthService, resolveSeedApiKey, bannerKeyLine, UnresolvedApiKeyException } from './auth.service';import { ApiKeyUsageTracker } from './api-key-usage-tracker.service';import { ApiKey, ApiKeyRole } from './entities/api-key.entity';@@ -753,6 +753,20 @@ describe('AuthService', () => {await expect(service.validateApiKey('revoked')).rejects.toThrow('API key is revoked');});+ // Only a key that matches no row is marked unresolved, so its audit row may be sampled per IP; a+ // rejection of a stored key must stay a plain 401 so every attempt is audited.+ it('marks only an unknown key as unresolved, keeping the UnauthorizedException name', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(null);+ const unknown = await service.validateApiKey('wrong-key').catch((err: unknown) => err);+ expect(unknown).toBeInstanceOf(UnresolvedApiKeyException);+ expect((unknown as Error).name).toBe('UnauthorizedException');++ (repository.findOne as jest.Mock).mockResolvedValue(createMockApiKey({ isActive: false }));+ const revoked = await service.validateApiKey('revoked').catch((err: unknown) => err);+ expect(revoked).toBeInstanceOf(UnauthorizedException);+ expect(revoked).not.toBeInstanceOf(UnresolvedApiKeyException);+ });+it('should throw UnauthorizedException for expired key', async () => {const expired = new Date();expired.setDate(expired.getDate() - 1);diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.tsindex 32a42bec3..2975cd31b 100644--- a/src/modules/auth/auth.service.ts+++ b/src/modules/auth/auth.service.ts@@ -21,6 +21,19 @@ import { apiKeyAuthorizationFingerprint, normalizeScopeList } from './api-key-auimport { normalizeChatAllowList } from '../../common/security/chat-scope';import { EventsGateway, type ApiKeyEvictionReason } from '../events/events.gateway';+/**+ * A 401 that names no stored key: the credential was missing or matched no row. Producing one costs+ * the caller nothing, so its audit row is bounded per client IP. Every other 401 (revoked, expired,+ * IP or session refused) required a real key and is audited on every attempt. The name stays+ * `UnauthorizedException` because MCP tool errors carry it on the wire.+ */+export class UnresolvedApiKeyException extends UnauthorizedException {+ constructor(message: string) {+ super(message);+ this.name = UnauthorizedException.name;+ }+}+/*** Resolves the API key to seed on first boot (when no keys exist yet).* Precedence: an explicit `API_MASTER_KEY` always wins; otherwise a@@ -449,7 +462,7 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {const apiKey = await this.apiKeyRepository.findOne({ where: { keyHash } });if (!apiKey) {- throw new UnauthorizedException('Invalid API key');+ throw new UnresolvedApiKeyException('Invalid API key');}if (!apiKey.isActive) {diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex b2a8e623a..6afda9801 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -3,12 +3,12 @@ import { runWithRequestId, getRequestActor } from '../../../common/services/requimport { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';import { ApiKeyGuard } from './api-key.guard';-import { AuthService } from '../auth.service';+import { AuthService, UnresolvedApiKeyException } from '../auth.service';import { ChatScopeService } from '../chat-scope.service';import { ApiKey, ApiKeyRole } from '../entities/api-key.entity';import { AuditService } from '../../audit/audit.service';import { AuditAction } from '../../audit/entities/audit-log.entity';-import { CHAT_QUOTED_ALLOWED_KEY, CHAT_SCOPED_KEY } from '../decorators/auth.decorators';+import { CHAT_QUOTED_ALLOWED_KEY, CHAT_SCOPED_KEY, REQUIRED_ROLE_KEY } from '../decorators/auth.decorators';function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {return {@@ -187,6 +187,87 @@ describe('ApiKeyGuard', () => {expect(auditService.logWarn).toHaveBeenCalledWith(AuditAction.API_KEY_AUTH_FAILED, expect.any(Object));});+ // A request with no key costs the caller nothing, and the throttler counts per route handler, so+ // the unauthenticated audit rows are bounded per client IP. These tests use IPs no other test in+ // this file uses: the budget is a module-level singleton shared with the Bull Board mount.+ describe('unauthenticated audit rows are bounded per client IP', () => {+ const settle = () => new Promise(resolve => setImmediate(resolve));++ it('writes at most 10 rows a minute for one IP, while every request still gets its 401', async () => {+ let rejected = 0;+ for (let i = 0; i < 50; i++) {+ await guard.canActivate(createMockContext({}, {}, '198.51.100.71')).catch(err => {+ if (err instanceof UnauthorizedException) rejected++;+ });+ }+ await settle();++ expect(rejected).toBe(50);+ expect(auditService.logWarn).toHaveBeenCalledTimes(10);++ // A different client keeps its own budget.+ await expect(guard.canActivate(createMockContext({}, {}, '198.51.100.72'))).rejects.toThrow(+ UnauthorizedException,+ );+ await settle();+ expect(auditService.logWarn).toHaveBeenCalledTimes(11);+ expect(auditService.logWarn).toHaveBeenLastCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ ipAddress: '198.51.100.72' }),+ );+ });++ it('still records every 403 from an IP whose 401 budget is spent', async () => {+ for (let i = 0; i < 11; i++) {+ await guard.canActivate(createMockContext({}, {}, '198.51.100.73')).catch(() => undefined);+ }+ await settle();+ expect(auditService.logWarn).toHaveBeenCalledTimes(10);++ metadata[REQUIRED_ROLE_KEY] = ApiKeyRole.ADMIN;+ (authService.validateApiKey as jest.Mock).mockResolvedValue(createMockApiKey({ role: ApiKeyRole.VIEWER }));+ (authService.hasPermission as jest.Mock).mockReturnValue(false);+ for (let i = 0; i < 3; i++) {+ await expect(+ guard.canActivate(createMockContext({ 'x-api-key': 'viewer-key' }, {}, '198.51.100.73')),+ ).rejects.toThrow(ForbiddenException);+ }+ await settle();+ expect(auditService.logWarn).toHaveBeenCalledTimes(13);+ });++ it('still records a rejected stored key from an IP whose budget is spent, but not an unknown one', async () => {+ for (let i = 0; i < 11; i++) {+ await guard.canActivate(createMockContext({}, {}, '198.51.100.74')).catch(() => undefined);+ }+ await settle();+ expect(auditService.logWarn).toHaveBeenCalledTimes(10);++ (authService.validateApiKey as jest.Mock).mockRejectedValue(new UnresolvedApiKeyException('Invalid API key'));+ await expect(+ guard.canActivate(createMockContext({ 'x-api-key': 'unknown' }, {}, '198.51.100.74')),+ ).rejects.toThrow(UnauthorizedException);+ await settle();+ expect(auditService.logWarn).toHaveBeenCalledTimes(10);++ for (const message of ['API key is revoked', 'API key has expired', 'API key not authorized for this session']) {+ (authService.validateApiKey as jest.Mock).mockRejectedValue(new UnauthorizedException(message));+ await expect(+ guard.canActivate(createMockContext({ 'x-api-key': 'stored' }, {}, '198.51.100.74')),+ ).rejects.toThrow(message);+ }+ await settle();+ expect(auditService.logWarn).toHaveBeenCalledTimes(13);+ expect(auditService.logWarn).toHaveBeenLastCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({+ ipAddress: '198.51.100.74',+ errorMessage: 'API key not authorized for this session',+ }),+ );+ });+ });+it('does not record an audit event on a successful authorization', async () => {reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);(authService.validateApiKey as jest.Mock).mockResolvedValue(createMockApiKey());diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex b95f69389..391984b88 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -9,7 +9,7 @@ import {import { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';import { Request } from 'express';-import { AuthService } from '../auth.service';+import { AuthService, UnresolvedApiKeyException } from '../auth.service';import { ChatScopeService } from '../chat-scope.service';import { BULK_MESSAGES_MAX } from '../../message/dto/bulk-message.dto';import { ApiKey, ApiKeyRole } from '../entities/api-key.entity';@@ -27,6 +27,7 @@ import { bearerToken } from '../../../common/security/bearer-token';import { setRequestActor } from '../../../common/services/request-context';import { AuditService } from '../../audit/audit.service';import { AuditAction } from '../../audit/entities/audit-log.entity';+import { allowUnauthenticatedAuditRow } from '../../audit/auth-failure-audit-limiter';@Injectable()export class ApiKeyGuard implements CanActivate {@@ -56,13 +57,18 @@ export class ApiKeyGuard implements CanActivate {if (err instanceof UnauthorizedException || err instanceof ForbiddenException) {// Stamp at least the IP so the failed-auth audit row below is attributable even though the// key was never resolved. setRequestActor is a no-op outside a request scope.- setRequestActor({ ipAddress: this.getClientIp(request) });- void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {- ipAddress: this.getClientIp(request),- method: request.method,- path: request.path,- errorMessage: err.message,- });+ const clientIp = this.getClientIp(request);+ setRequestActor({ ipAddress: clientIp });+ // A 401 that resolved no key is bounded per client IP (see UnresolvedApiKeyException); any+ // rejection of a stored key, 401 or 403, is always recorded.+ if (!(err instanceof UnresolvedApiKeyException) || allowUnauthenticatedAuditRow(clientIp)) {+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: clientIp,+ method: request.method,+ path: request.path,+ errorMessage: err.message,+ });+ }}throw err;}@@ -72,7 +78,7 @@ export class ApiKeyGuard implements CanActivate {const apiKeyHeader = this.extractApiKey(request);if (!apiKeyHeader) {- throw new UnauthorizedException('API key is required');+ throw new UnresolvedApiKeyException('API key is required');}const requiredRole = this.reflector.getAllAndOverride<ApiKeyRole>(REQUIRED_ROLE_KEY, [