Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(events): cover the sweep timer and subscribe refusals

Yudhi Armyndharis185d326fec5c
diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.ts
index c5a16b817..4888b9eec 100644
--- a/src/modules/events/events.gateway.spec.ts
+++ b/src/modules/events/events.gateway.spec.ts
@@ -57,17 +57,25 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
let gateway: EventsGateway;
let authService: { validateApiKey: jest.Mock };
- const makeSocket = (auth: { apiKey?: string } = {}): MockSocket => ({
- id: 'sock-1',
- handshake: { headers: {}, query: {}, auth, address: '203.0.113.5' },
- data: {},
- emit: jest.fn(),
- disconnect: jest.fn(),
- join: jest.fn(),
- leave: jest.fn(),
- // Socket.IO puts every socket in a room named after its own id.
- rooms: new Set<string>(['sock-1']),
- });
+ const makeSocket = (auth: { apiKey?: string } = {}): MockSocket => {
+ const s: MockSocket = {
+ id: 'sock-1',
+ handshake: { headers: {}, query: {}, auth, address: '203.0.113.5' },
+ data: {},
+ emit: jest.fn(),
+ // Like socket.io, a server-side close marks the socket disconnected at once.
+ disconnect: jest.fn(() => {
+ s.disconnected = true;
+ }),
+ join: jest.fn(),
+ leave: jest.fn(),
+ // Socket.IO puts every socket in a room named after its own id.
+ rooms: new Set<string>(['sock-1']),
+ };
+ return s;
+ };
+ const unauthorizedEmits = (s: MockSocket): unknown[] =>
+ s.emit.mock.calls.filter(([, frame]) => (frame as WSErrorResponse | undefined)?.code === 'UNAUTHORIZED');
// Subscription rooms joined by the socket; the QR-denied role room is not a subscription.
const sessionRoomJoins = (s: MockSocket): string[] =>
s.join.mock.calls.map(([room]) => room as string).filter(room => room.startsWith('session:'));
@@ -147,6 +155,7 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
expect(res.code).toBe('UNAUTHORIZED');
expect(sock.disconnect).toHaveBeenCalled();
expect(sessionRoomJoins(sock)).toEqual([]);
+ expect(unauthorizedEmits(sock)).toHaveLength(1);
});
it('re-validates on subscribe and disconnects a key revoked after connect', async () => {
@@ -154,11 +163,13 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
const sock = makeSocket({ apiKey: 'good' });
await gateway.handleConnection(asSocket(sock));
- authService.validateApiKey.mockResolvedValueOnce(null); // revoked on the subscribe re-check
+ // validateApiKey throws on a revoked key; it never resolves to a falsy value.
+ authService.validateApiKey.mockRejectedValueOnce(new UnauthorizedException('API key revoked'));
const res = (await gateway.handleMessage(asSocket(sock), subscribeMsg('sess-1', ['*']))) as WSErrorResponse;
expect(sock.disconnect).toHaveBeenCalled();
expect(res.code).toBe('UNAUTHORIZED');
+ expect(unauthorizedEmits(sock)).toHaveLength(1);
});
it('allows subscribe when the key still re-validates', async () => {
@@ -508,6 +519,29 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {
// The periodic sweep (expiry, revocation, deletion, narrowing) reads the api_keys table, so it is
// exercised against a real one in events.gateway.authz-sweep.spec.ts rather than a stub here.
});
+
+ it('runs the authorization sweep every minute from afterInit until onModuleDestroy', async () => {
+ jest.useFakeTimers();
+ try {
+ const sweep = jest
+ .spyOn(gateway as unknown as { sweepApiKeyAuthorization: () => Promise<void> }, 'sweepApiKeyAuthorization')
+ .mockRejectedValueOnce(new Error('database is locked'))
+ .mockResolvedValue(undefined);
+ gateway.afterInit();
+
+ await jest.advanceTimersByTimeAsync(60_000);
+ expect(sweep).toHaveBeenCalledTimes(1);
+ // A failed tick is logged, and the next one still runs.
+ await jest.advanceTimersByTimeAsync(60_000);
+ expect(sweep).toHaveBeenCalledTimes(2);
+
+ gateway.onModuleDestroy();
+ await jest.advanceTimersByTimeAsync(120_000);
+ expect(sweep).toHaveBeenCalledTimes(2);
+ } finally {
+ jest.useRealTimers();
+ }
+ });
});
// A capturing, chainable Socket.IO server stub: server.to(r1).to(r2)...emit(...) all