Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): audit the refusal of a chat-scoped key
Yudhi Armyndharis626f777153a1
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 4888b9eec..f7bbe2f82 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -141,6 +141,14 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {await gateway.handleConnection(asSocket(sock));expect(sock.disconnect).toHaveBeenCalled();expect(sock.emit).toHaveBeenCalled();+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({+ apiKey: expect.objectContaining({ allowedChats: ['[email protected]'] }) as unknown,+ ipAddress: '203.0.113.5',+ metadata: { surface: 'websocket' },+ }),+ );});it('refuses a subscribe once the key has gained allowedChats after connect', async () => {@@ -156,6 +164,14 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sock.disconnect).toHaveBeenCalled();expect(sessionRoomJoins(sock)).toEqual([]);expect(unauthorizedEmits(sock)).toHaveLength(1);+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({+ apiKey: expect.objectContaining({ allowedChats: ['[email protected]'] }) as unknown,+ ipAddress: '203.0.113.5',+ metadata: { surface: 'websocket' },+ }),+ );});it('re-validates on subscribe and disconnects a key revoked after connect', async () => {@@ -170,6 +186,11 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sock.disconnect).toHaveBeenCalled();expect(res.code).toBe('UNAUTHORIZED');expect(unauthorizedEmits(sock)).toHaveLength(1);+ expect(auditService.logWarn).toHaveBeenCalledWith(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: '203.0.113.5',+ metadata: { surface: 'websocket' },+ errorMessage: 'API key revoked',+ });});it('allows subscribe when the key still re-validates', async () => {diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 65f10a3f0..49c52cbfb 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -372,6 +372,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate// chat's events to it. Mirrors the REST guard's default-deny for unmarked routes.if ((validKey.allowedChats?.length ?? 0) > 0) {this.logger.warn(`Client ${client.id} rejected: chat-scoped key ${validKey.id} cannot subscribe to events`);+ this.auditChatScopedRefusal(validKey, clientIp);client.emit('message',this.createError('UNAUTHORIZED', 'API keys restricted to selected chats cannot subscribe to events'),@@ -439,6 +440,19 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate}}+ /**+ * A refused chat-scoped key is a stored key turned away, which the REST guard, the MCP surface and+ * Bull Board all record; the socket refusal returns before the handshake's catch, so it audits here.+ */+ private auditChatScopedRefusal(apiKey: ApiKey, clientIp: string): void {+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ apiKey,+ ipAddress: clientIp,+ metadata: { surface: 'websocket' },+ errorMessage: 'API keys restricted to selected chats cannot subscribe to events',+ });+ }+handleDisconnect(client: Socket) {this.untrackSocket(client);this.logger.log(`Client disconnected: ${client.id}`);@@ -534,8 +548,15 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatelet subscriberKey: ApiKey | null;try {subscriberKey = rawApiKey ? await this.authService.validateApiKey(rawApiKey, clientIp) : null;- } catch {+ } catch (error) {subscriberKey = null;+ // A key refused here was valid at connect (revoked, expired, deleted or IP-refused since), so it+ // is audited like the handshake refusal; the socket is disconnected below, bounding the volume.+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: clientIp,+ metadata: { surface: 'websocket' },+ errorMessage: error instanceof Error ? error.message : String(error),+ });}if (!subscriberKey) {client.emit('message', this.createError('UNAUTHORIZED', 'API key is no longer valid', requestId));@@ -560,6 +581,7 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate'API keys restricted to selected chats cannot subscribe to events',requestId,);+ this.auditChatScopedRefusal(subscriberKey, clientIp);client.emit('message', refusal);client.disconnect();return refusal;