Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(auth): cover DTO-borne session ids and chat scope end to end
Yudhi Armyndharis2f81234c22ab
diff --git a/docs/09-testing-strategy.md b/docs/09-testing-strategy.mdindex 37e7d1eec..c9817bd78 100644--- a/docs/09-testing-strategy.md+++ b/docs/09-testing-strategy.md@@ -154,6 +154,7 @@ test/├── fixtures/├── app.e2e-spec.ts├── baileys-engine.e2e-spec.ts+├── chat-scope.e2e-spec.ts├── ingress-instance-throttle.e2e-spec.ts├── integration-fabric.e2e-spec.ts├── integration-instance.e2e-spec.tsdiff --git a/src/modules/auth/query-session-scope-coverage.spec.ts b/src/modules/auth/query-session-scope-coverage.spec.tsindex c8b48820c..5ac0b07e2 100644--- a/src/modules/auth/query-session-scope-coverage.spec.ts+++ b/src/modules/auth/query-session-scope-coverage.spec.ts@@ -5,8 +5,8 @@// scoped by the guard, and must derive scope from the calling key itself — the established pattern is// to inject `@CurrentApiKey()` and pass `apiKey.allowedSessions` to the service (see// search.controller / webhooks-list findAll / audit). This test fails if a controller handler takes-// `@Query('sessionId')` without also injecting `@CurrentApiKey`, so a future endpoint cannot silently-// re-introduce the leak.+// `@Query('sessionId')`, or a whole `@Query()` / `@Body()` DTO declaring `sessionId` or `sessionIds`,+// without also injecting `@CurrentApiKey`, so a future endpoint cannot silently re-introduce the leak.import { readdirSync, readFileSync } from 'fs';import { join } from 'path';@@ -28,21 +28,65 @@ export function methodPattern(): RegExp {}/**- * Return the names of handlers in `source` that take a `sessionId` query param but do NOT inject- * `@CurrentApiKey` in the same parameter list — i.e. that bypass the guard fence without re-scoping.+ * Return the names of handlers in `source` that take a `sessionId` query param, or a whole `@Query()` /+ * `@Body()` DTO named in `sessionDtos`, but do NOT inject `@CurrentApiKey` in the same parameter list:+ * i.e. that bypass the guard fence without re-scoping.*/-export function handlersMissingSessionScope(source: string): string[] {+export function handlersMissingSessionScope(source: string, sessionDtos: ReadonlySet<string> = new Set()): string[] {const offenders: string[] = [];const methodRe = methodPattern();for (let m = methodRe.exec(source); m !== null; m = methodRe.exec(source)) {const [, name, params] = m;const takesSessionIdQuery = /@Query\(\s*['"]sessionId['"]\s*\)/.test(params);+ const takesSessionDto = [...params.matchAll(/@(?:Query|Body)\(\s*\)\s*\w+\??\s*:\s*(\w+)/g)].some(p =>+ sessionDtos.has(p[1]),+ );const injectsCurrentApiKey = /@CurrentApiKey\(/.test(params);- if (takesSessionIdQuery && !injectsCurrentApiKey) offenders.push(name);+ if ((takesSessionIdQuery || takesSessionDto) && !injectsCurrentApiKey) offenders.push(name);}return offenders;}+/**+ * The classes in `sources` that declare `sessionId` or `sessionIds`, themselves or through a parent+ * (`extends Y`, or a mapped type such as `PartialType(Y)` / `IntersectionType(Y, Z)`).+ */+export function sessionScopedDtos(sources: readonly string[]): Set<string> {+ const own = new Set<string>();+ const parents = new Map<string, string[]>();+ for (const source of sources) {+ for (const chunk of source.split(/export\s+class\s+/).slice(1)) {+ const name = /^(\w+)/.exec(chunk)?.[1];+ if (!name) continue;+ if (/^\s+sessionIds?[?!]?\s*:/m.test(chunk)) own.add(name);+ const heritage = /^\w+\s+extends\s+([^{]*)\{/.exec(chunk)?.[1] ?? '';+ parents.set(+ name,+ [...heritage.matchAll(/\b([A-Z]\w*Dto|[A-Z]\w*)\b/g)].map(p => p[1]),+ );+ }+ }+ const out = new Set<string>();+ const carries = (name: string, seen: Set<string>): boolean => {+ if (own.has(name)) return true;+ if (seen.has(name)) return false;+ seen.add(name);+ return (parents.get(name) ?? []).some(parent => carries(parent, seen));+ };+ for (const name of parents.keys()) if (carries(name, new Set())) out.add(name);+ return out;+}++function listSourceFiles(dir: string): string[] {+ const out: string[] = [];+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const full = join(dir, entry.name);+ if (entry.isDirectory()) out.push(...listSourceFiles(full));+ else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.spec.ts')) out.push(full);+ }+ return out;+}+function listControllerFiles(dir: string): string[] {const out: string[] = [];for (const entry of readdirSync(dir, { withFileTypes: true })) {@@ -80,6 +124,48 @@ describe('query-param sessionId endpoints are session-scoped', () => {expect(handlersMissingSessionScope(vulnerable)).toEqual(['findAll']);});+ it('flags a whole @Query() or @Body() DTO carrying sessionId or sessionIds, inherited or declared', () => {+ const dtos = sessionScopedDtos([+ `+export class FilterDto {+ @IsOptional()+ sessionId?: string;+}+export class FanOutDto {+ sessionIds!: string[];+}+export class UpdateFilterDto extends PartialType(FilterDto) {}+export class PlainDto {+ name?: string;+}+`,+ ]);+ expect([...dtos].sort()).toEqual(['FanOutDto', 'FilterDto', 'UpdateFilterDto']);++ const handlers = `+ async list(@Query() dto: FilterDto) {+ return this.svc.list(dto);+ }++ async fanOut(@Body() dto: FanOutDto): Promise<unknown> {+ return this.svc.fanOut(dto);+ }++ async update(@Body() dto: UpdateFilterDto) {+ return this.svc.update(dto);+ }++ async plain(@Body() dto: PlainDto) {+ return this.svc.plain(dto);+ }++ async scoped(@Query() dto: FilterDto, @CurrentApiKey() apiKey?: ApiKey) {+ return this.svc.list(dto, apiKey?.allowedSessions);+ }+`;+ expect(handlersMissingSessionScope(handlers, dtos)).toEqual(['list', 'fanOut', 'update']);+ });+it('clears a handler that injects @CurrentApiKey alongside the query param', () => {const fixed = `async findAll(@@ -122,11 +208,14 @@ describe('query-param sessionId endpoints are session-scoped', () => {expect(blind).toEqual([]);});- it('no real controller takes @Query(sessionId) without scoping to the calling key', () => {+ it('no real controller takes a session id from its query or body without scoping to the calling key', () => {const modulesDir = join(__dirname, '..');+ const sessionDtos = sessionScopedDtos(listSourceFiles(modulesDir).map(f => readFileSync(f, 'utf8')));+ // The DTO scan must see the one real request DTO carrying sessionId, or it checks nothing.+ expect(sessionDtos.has('SearchQueryDto')).toBe(true);const offenders: string[] = [];for (const file of listControllerFiles(modulesDir)) {- for (const handler of handlersMissingSessionScope(readFileSync(file, 'utf8'))) {+ for (const handler of handlersMissingSessionScope(readFileSync(file, 'utf8'), sessionDtos)) {offenders.push(`${file.replace(/.*\/src\//, 'src/')} :: ${handler}`);}}diff --git a/test/chat-scope.e2e-spec.ts b/test/chat-scope.e2e-spec.tsnew file mode 100644index 000000000..42036479d--- /dev/null+++ b/test/chat-scope.e2e-spec.ts@@ -0,0 +1,90 @@+// archiver v8 is ESM-only (pulled in transitively via @Global StorageModule); stub for ts-jest CJS.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication } from '@nestjs/common';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import request from 'supertest';+import { App } from 'supertest/types';+import { AppModule } from './../src/app.module';+import { applyGlobalValidation } from './../src/config/app-validation';+import { AuthService } from './../src/modules/auth/auth.service';+import { ApiKeyRole } from './../src/modules/auth/entities/api-key.entity';+import { Session } from './../src/modules/session/entities/session.entity';++/**+ * End-to-end proof of the chat fence through the real HTTP stack (guard + reflector metadata + DI ++ * routing), which the unit specs mock away: a key restricted to one chat is refused on routes with no+ * chat dimension and on any other chat, and admitted where its chat is named or the list is filtered.+ * No engine runs here, so an admitted request is asserted only as "not refused by the fence".+ */+describe('Chat-restricted API keys (e2e)', () => {+ const ALLOWED = '[email protected]';+ const OTHER = '[email protected]';+ let app: INestApplication<App>;+ let sessionId: string;+ let chatKey: string; // OPERATOR, allowedChats: [ALLOWED]+ let openKey: string; // OPERATOR, unrestricted++ const get = (path: string, key: string) => request(app.getHttpServer()).get(path).set('X-API-Key', key);++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();+ app = moduleFixture.createNestApplication();+ applyGlobalValidation(app);+ await app.init();++ const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));+ sessionId = (await sessionRepo.save(sessionRepo.create({ name: `e2e-chat-scope-${Date.now()}` }))).id;++ const authService = app.get(AuthService);+ chatKey = (await authService.createApiKey({ name: 'e2e-chat', role: ApiKeyRole.OPERATOR, allowedChats: [ALLOWED] }))+ .rawKey;+ openKey = (await authService.createApiKey({ name: 'e2e-open', role: ApiKeyRole.OPERATOR })).rawKey;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ it('refuses a route with no chat dimension, which an unrestricted key reaches', async () => {+ const res = await get(`/api/sessions/${sessionId}/webhooks`, chatKey).expect(403);+ expect((res.body as { message: string }).message).toBe('API key is restricted to selected chats');+ expect((await get(`/api/sessions/${sessionId}/webhooks`, openKey)).status).not.toBe(403);+ });++ it('refuses a chat outside the allowlist in a path param and in a send body', async () => {+ const res = await get(`/api/sessions/${sessionId}/contacts/${OTHER}`, chatKey).expect(403);+ expect((res.body as { message: string }).message).toBe('API key not authorized for this chat');++ await request(app.getHttpServer())+ .post(`/api/sessions/${sessionId}/messages/send-text`)+ .set('X-API-Key', chatKey)+ .send({ chatId: OTHER, text: 'hi' })+ .expect(403);+ });++ it('admits the allowed chat', async () => {+ expect((await get(`/api/sessions/${sessionId}/contacts/${ALLOWED}`, chatKey)).status).not.toBe(403);+ });++ it('reads stored messages only for a chat it names', async () => {+ const path = `/api/sessions/${sessionId}/messages`;+ const missing = await get(path, chatKey).expect(403);+ expect((missing.body as { message: string }).message).toBe(+ 'chatId is required for a key restricted to selected chats',+ );+ await get(`${path}?chatId=${OTHER}`, chatKey).expect(403);+ await get(`${path}?chatId=${ALLOWED}`, chatKey).expect(200);+ await get(path, openKey).expect(200);+ });++ it.each(['chats', 'groups', 'contacts', 'labels/1/chats'])('admits the filtered list route %s', async route => {+ expect((await get(`/api/sessions/${sessionId}/${route}`, chatKey)).status).not.toBe(403);+ });+});