Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(audit): record failed API-key authentication attempts (#535)

Yudhi Armyndharisc53cb0a3dc77
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0d9449805..45354d313 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Hook re-entrancy is now blocked for sandboxed plugins too.** A plugin running in the worker-thread sandbox could re-fire the hook it was handling by issuing a capability call (for example, sending a message from within a `message:sending` handler), because the re-entrancy guard did not span the worker boundary — looping the event back into the plugin without bound. The host now runs each worker-initiated capability call inside the in-flight hook context, so such a re-fire is short-circuited exactly as it already was for in-process plugins. (#532)
- **Docker container teardown is constrained to OpenWA-managed services.** The `POST /infra/restart` endpoint passed its `profilesToRemove` list straight to container removal, which resolved containers by a name substring — so an unrecognized or empty profile could stop and remove an unrelated container. Teardown is now restricted to the managed allowlist (`postgres`, `redis`, `minio`) and container resolution requires an exact `openwa-<service>` name match. (#534)
+- **Failed API-key authentication attempts are now recorded in the audit log.** Rejected or denied keys (invalid, disabled/expired, IP- or session-scope-denied, or insufficient role) previously left no audit entry; the gateway now logs an `api_key_auth_failed` event with the client IP, method, path, and reason, giving administrators a forensic trail for credential probing. Audit logging stays best-effort and never affects the request outcome. (#535)
## [0.7.12] - 2026-06-29
diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.ts
index 5badba8e1..2f50f4b9e 100644
--- a/src/modules/auth/guards/api-key.guard.spec.ts
+++ b/src/modules/auth/guards/api-key.guard.spec.ts
@@ -4,6 +4,8 @@ import { ConfigService } from '@nestjs/config';
import { ApiKeyGuard } from './api-key.guard';
import { AuthService } from '../auth.service';
import { ApiKey, ApiKeyRole } from '../entities/api-key.entity';
+import { AuditService } from '../../audit/audit.service';
+import { AuditAction } from '../../audit/entities/audit-log.entity';
function createMockApiKey(overrides: Partial<ApiKey> = {}): ApiKey {
return {
@@ -50,12 +52,18 @@ describe('ApiKeyGuard', () => {
let authService: jest.Mocked<Partial<AuthService>>;
let reflector: jest.Mocked<Reflector>;
let configService: jest.Mocked<Partial<ConfigService>>;
+ let auditService: jest.Mocked<Partial<AuditService>>;
function buildGuard(trustedProxies: string[] = []): ApiKeyGuard {
configService = {
get: jest.fn().mockReturnValue(trustedProxies),
};
- return new ApiKeyGuard(authService as AuthService, reflector, configService as ConfigService);
+ return new ApiKeyGuard(
+ authService as AuthService,
+ reflector,
+ configService as ConfigService,
+ auditService as AuditService,
+ );
}
beforeEach(() => {
@@ -68,6 +76,10 @@ describe('ApiKeyGuard', () => {
getAllAndOverride: jest.fn(),
} as unknown as jest.Mocked<Reflector>;
+ auditService = {
+ logWarn: jest.fn().mockResolvedValue(null),
+ };
+
guard = buildGuard();
});
@@ -128,6 +140,41 @@ describe('ApiKeyGuard', () => {
await expect(guard.canActivate(context)).rejects.toThrow('Invalid API key');
});
+ it('records an API_KEY_AUTH_FAILED audit event when a key is rejected (with ip + reason)', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false); // not public
+ (authService.validateApiKey as jest.Mock).mockRejectedValue(new UnauthorizedException('Invalid API key'));
+
+ const context = createMockContext({ 'x-api-key': 'bad-key' }, {}, '203.0.113.9');
+ await expect(guard.canActivate(context)).rejects.toThrow('Invalid API key');
+ await new Promise(resolve => setImmediate(resolve)); // let the fire-and-forget audit write settle
+
+ expect(auditService.logWarn).toHaveBeenCalledWith(
+ AuditAction.API_KEY_AUTH_FAILED,
+ expect.objectContaining({ ipAddress: '203.0.113.9', errorMessage: 'Invalid API key' }),
+ );
+ });
+
+ it('records an audit event when a missing key is rejected', async () => {
+ reflector.getAllAndOverride.mockReturnValueOnce(false);
+
+ const context = createMockContext({}); // no key
+ await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(auditService.logWarn).toHaveBeenCalledWith(AuditAction.API_KEY_AUTH_FAILED, expect.any(Object));
+ });
+
+ 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());
+
+ const context = createMockContext({ 'x-api-key': 'good-key' });
+ await guard.canActivate(context);
+ await new Promise(resolve => setImmediate(resolve));
+
+ expect(auditService.logWarn).not.toHaveBeenCalled();
+ });
+
it('should reject when role permission is insufficient', async () => {
reflector.getAllAndOverride
.mockReturnValueOnce(false) // not public
diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.ts
index 57b8c7b2f..b5eec09f1 100644
--- a/src/modules/auth/guards/api-key.guard.ts
+++ b/src/modules/auth/guards/api-key.guard.ts
@@ -6,6 +6,8 @@ import { AuthService } from '../auth.service';
import { ApiKeyRole } from '../entities/api-key.entity';
import { REQUIRED_ROLE_KEY, PUBLIC_KEY, SESSION_SCOPED_KEY } from '../decorators/auth.decorators';
import { resolveClientIp } from '../../../common/utils/ip';
+import { AuditService } from '../../audit/audit.service';
+import { AuditAction } from '../../audit/entities/audit-log.entity';
@Injectable()
export class ApiKeyGuard implements CanActivate {
@@ -13,6 +15,7 @@ export class ApiKeyGuard implements CanActivate {
private readonly authService: AuthService,
private readonly reflector: Reflector,
private readonly configService: ConfigService,
+ private readonly auditService: AuditService,
) {}
async canActivate(context: ExecutionContext): Promise<boolean> {
@@ -24,6 +27,25 @@ export class ApiKeyGuard implements CanActivate {
}
const request = context.switchToHttp().getRequest<Request>();
+ try {
+ return await this.authorize(request, context);
+ } catch (err) {
+ // Record rejected/denied authentication attempts so the audit log has a forensic trail for
+ // credential probing. Fire-and-forget: audit logging is best-effort and must never turn a
+ // 401/403 into a failure of the guard itself.
+ if (err instanceof UnauthorizedException || err instanceof ForbiddenException) {
+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {
+ ipAddress: this.getClientIp(request),
+ method: request.method,
+ path: request.path,
+ errorMessage: err.message,
+ });
+ }
+ throw err;
+ }
+ }
+
+ private async authorize(request: Request, context: ExecutionContext): Promise<boolean> {
const apiKeyHeader = this.extractApiKey(request);
if (!apiKeyHeader) {