Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(events): bound the session id and room count a WS subscribe keeps
Yudhi Armyndharis7522cbd15a5b
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex da6b2a414..ccad33fef 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -234,6 +234,39 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(sessionRoomJoins(sock)).toEqual([]);});+ // The session id becomes part of every room name the socket keeps until it disconnects, so an+ // oversized or malformed one must be refused before it costs a key lookup or a room.+ it.each([+ ['oversized', 'a'.repeat(129)],+ ['malformed', 'sess:1'],+ ])('refuses a %s sessionId with INVALID_SESSION', async (_label, sessionId) => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ authService.validateApiKey.mockClear();++ const res = (await gateway.handleMessage(asSocket(sock), subscribeMsg(sessionId, ['*']))) as WSErrorResponse;++ expect(res.code).toBe('INVALID_SESSION');+ expect(authService.validateApiKey).not.toHaveBeenCalled();+ expect(sessionRoomJoins(sock)).toEqual([]);+ });++ it('refuses a subscribe that would take the socket past its room cap', async () => {+ authService.validateApiKey.mockResolvedValue({ name: 'k', allowedSessions: null });+ const sock = makeSocket({ apiKey: 'good' });+ await gateway.handleConnection(asSocket(sock));+ for (let i = 0; i < 4096; i++) sock.rooms.add(buildRoomName(`s${i}`, '*'));++ const res = (await gateway.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['*']))) as WSErrorResponse;+ expect(res.code).toBe('TOO_MANY_SUBSCRIPTIONS');+ expect(sessionRoomJoins(sock)).toEqual([]);++ // Re-subscribing a room the socket already holds adds nothing, so it is still granted.+ const again = (await gateway.handleMessage(asSocket(sock), subscribeMsg('s1', ['*']))) as WSSubscribedResponse;+ expect(again.type).toBe('subscribed');+ });+it('pushes a command reply on the message event, not only through the ack callback', async () => {// The Socket.IO adapter delivers a handler's return value through the ack callback and nothing// else, so a client that emits without one (the dashboard, and the documented example client)diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex 39938e7ad..2345e0242 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -17,6 +17,7 @@ import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveCorsPolicy } from '../../config/bootstrap-security';import { limiterKeyForIp, resolveClientIp as resolveRequestClientIp, type RequestLike } from '../../common/utils/ip';import { DEFAULT_WEBHOOK_MEDIA_INLINE_MAX_BYTES, shedInlineMedia } from '../../common/utils/inline-media';+import { isSafeSessionName } from '../../common/utils/path-safety';import { ApiKeyRole, type ApiKey } from '../auth/entities/api-key.entity';import { apiKeyAuthorizationFingerprint, apiKeyExpiryTime } from '../auth/api-key-authorization';import {@@ -88,6 +89,14 @@ export const QR_DENIED_ROOM = 'role:qr-denied';/** Roles allowed to receive `session.qr`. Anything else, including an unknown role, is denied. */const QR_ALLOWED_ROLES: ReadonlySet<string> = new Set([ApiKeyRole.OPERATOR, ApiKeyRole.ADMIN]);+/**+ * Subscription rooms live until the socket disconnects, so their names and count are bounded: a session+ * id is a uuid (any id the engines accept is isSafeSessionName), and one socket holds at most this many+ * rooms, far above every event of every session a client would follow.+ */+const MAX_SUBSCRIBE_SESSION_ID_LENGTH = 128;+const MAX_ROOMS_PER_SOCKET = 4096;+/** Why an API key's live WebSocket sockets are being torn down — drives the client-facing message. */export type ApiKeyEvictionReason = 'revoked' | 'deleted' | 'authorization_changed' | 'expired';@@ -487,6 +496,9 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateif (!sessionId || typeof sessionId !== 'string') {return this.createError('INVALID_SESSION', 'sessionId is required', requestId);}+ if (sessionId !== '*' && !(sessionId.length <= MAX_SUBSCRIBE_SESSION_ID_LENGTH && isSafeSessionName(sessionId))) {+ return this.createError('INVALID_SESSION', 'sessionId must be "*" or a session id', requestId);+ }// Re-validate the API key on every subscribe: a long-lived socket whose key was// revoked/expired after connect must not be able to keep opening new subscriptions.@@ -559,6 +571,15 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGate);}+ const newRooms = validEvents.filter(event => !client.rooms.has(buildRoomName(sessionId, event))).length;+ if (client.rooms.size + newRooms > MAX_ROOMS_PER_SOCKET) {+ return this.createError(+ 'TOO_MANY_SUBSCRIPTIONS',+ `A connection may hold at most ${MAX_ROOMS_PER_SOCKET} subscriptions; unsubscribe first`,+ requestId,+ );+ }+// Join rooms for each session/event combinationconst rooms: string[] = [];for (const event of validEvents) {