Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
test(auth): accept a marked chat-agnostic handler in the coverage spec
Bhavya Chopra601b7216eae3
diff --git a/src/modules/auth/chat-scope-coverage.spec.ts b/src/modules/auth/chat-scope-coverage.spec.tsindex 16bd2a291..f6178de13 100644--- a/src/modules/auth/chat-scope-coverage.spec.ts+++ b/src/modules/auth/chat-scope-coverage.spec.ts@@ -4,13 +4,22 @@// The guard is DEFAULT DENY (api-key.guard.ts): a chat-restricted key is refused with 403 on every// handler that is not marked @ChatScoped, so surfaces with no chat dimension (webhooks, automation// rules, status, key management, channels) and every route added later stay closed without being-// enumerated. A marked handler must then be fenceable — the guard inspects the chat id it carries-// (a `:chatId` / `:groupId` / `:contactId` path param, `?chatId=`, or the `chatId` / `fromChatId` /-// `toChatId` / `messages[].chatId` body fields), OR the handler filters its list result through-// ChatScopeService.+// enumerated.//-// This spec fails when a marked handler is neither fenceable nor filters, so marking a handler can-// never quietly become a bypass.+// Marking a handler is the operator's assertion that it is safe for such a key, and it is safe in+// one of three ways:+//+// 1. fenced — it names a chat the guard inspects (a `:chatId` / `:groupId` / `:contactId` path+// param, `?chatId=`, or the `chatId` / `fromChatId` / `toChatId` / `messages[].chatId` body+// fields);+// 2. filtered — it lists chats and filters them through ChatScopeService;+// 3. chat-agnostic — it names no chat at all.+//+// This spec fails when a marked handler reaches chats by a field the guard does NOT read (a+// `recipients[]`, `participants[]`, `channelId`, …) while naming no guard-visible chat — the class of+// route the design calls out (status posts, group creation). A chat-agnostic handler is accepted: the+// mark is the assertion, and the spec cannot derive it, since a webhook with `events: ['*']` also+// names no chat.import { readdirSync, readFileSync } from 'fs';import { basename, join, sep } from 'path';@@ -18,10 +27,19 @@ import { basename, join, sep } from 'path';export const GUARD_CHAT_ROUTE_PARAMS = ['chatId', 'groupId', 'contactId'];/** Body fields the ApiKeyGuard treats as a chat id (bulk send nests `chatId` inside `messages[]`). */export const GUARD_BODY_CHAT_FIELDS = ['chatId', 'fromChatId', 'toChatId'];+/** Chat-targeting field names the guard does NOT read — reaching a chat through one is the hazard. */+const UNFENCED_CHAT_FIELDS = ['recipients', 'participants', 'channelId', 'chatIds', 'groupIds', 'contactIds'];-/** Request DTO classes carrying a guard-fenced chat field. */-function chatBearingDtoClasses(dir: string): Set<string> {- const out = new Set<string>();+const GUARD_FIELD_RE = new RegExp(`\\b(?:${GUARD_BODY_CHAT_FIELDS.join('|')})[!?]?\\s*:`);+const UNFENCED_FIELD_RE = new RegExp(`\\b(?:${UNFENCED_CHAT_FIELDS.join('|')})[!?]?\\s*:`);+const BULK_ARRAY_RE = /\bmessages[!?]?\s*:\s*[\w.]*\[\]/;++/**+ * Request DTO classes that carry a chat id, classified by whether the guard fences the field it+ * carries. `guard` wins over `other`: a DTO the guard can fence is safe to mark.+ */+export function chatBearingDtoClasses(dir: string): Map<string, 'guard' | 'other'> {+ const out = new Map<string, 'guard' | 'other'>();const walk = (current: string): void => {for (const entry of readdirSync(current, { withFileTypes: true })) {const full = join(current, entry.name);@@ -36,10 +54,8 @@ function chatBearingDtoClasses(dir: string): Set<string> {.slice(1)) {const name = /^([A-Za-z0-9_]+)/.exec(chunk)?.[1];if (!name) continue;- const field = GUARD_BODY_CHAT_FIELDS.some(f => new RegExp(`\\b${f}[!?]?\\s*:`).test(chunk));- // Bulk send carries its recipients in an array field; the guard iterates it.- const bulkArray = /\bmessages[!?]?\s*:\s*[\w.]*\[\]/.test(chunk);- if (field || bulkArray) out.add(name);+ if (GUARD_FIELD_RE.test(chunk) || BULK_ARRAY_RE.test(chunk)) out.set(name, 'guard');+ else if (UNFENCED_FIELD_RE.test(chunk)) out.set(name, 'other');}}};@@ -48,10 +64,15 @@ function chatBearingDtoClasses(dir: string): Set<string> {}/**- * Return @ChatScoped handlers in `source` that are neither fenceable by the guard nor filter through- * ChatScopeService — i.e. marked handlers a chat-restricted key could reach for any chat.+ * Return @ChatScoped handlers in `source` that reach chats through a field the guard does not read+ * while naming no guard-visible chat — marked handlers a chat-restricted key could use to reach any+ * chat. A marked handler that names a guard-visible chat is fenced by the guard; one that names no+ * chat at all is chat-agnostic and accepted (the mark is the assertion).*/-export function markedHandlersWithoutChatFence(source: string, chatDtos: Set<string>): string[] {+export function markedHandlersReachingUnfencedChats(+ source: string,+ chatDtos: Map<string, 'guard' | 'other'>,+): string[] {const offenders: string[] = [];const handlerRe = /((?:^ {2}@[\s\S]*?)?)^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)\s*[:{]/gm;const matches: { name: string; from: number; decorators: string }[] = [];@@ -65,10 +86,13 @@ export function markedHandlersWithoutChatFence(source: string, chatDtos: Set<strconst hasPathChat = new RegExp(`@Param\\(\\s*['"](?:${GUARD_CHAT_ROUTE_PARAMS.join('|')})['"]\\s*\\)`).test(body);const hasQueryChat = /@Query\(\s*['"]chatId['"]\s*\)/.test(body);const bodyDto = /@Body\(\)\s*[A-Za-z0-9_]+\s*:\s*([A-Za-z0-9_]+)/.exec(body)?.[1];- const hasBodyChat = bodyDto !== undefined && chatDtos.has(bodyDto);- // A list handler names no chat, so it must filter its result through ChatScopeService instead.+ const hasGuardBodyChat = bodyDto !== undefined && chatDtos.get(bodyDto) === 'guard';+ // A chat-agnostic handler names no chat: accepted, the mark is the assertion.+ const namesGuardChat = hasPathChat || hasQueryChat || hasGuardBodyChat;+ const unfencedQuery = new RegExp(`@Query\\(\\s*['"](?:${UNFENCED_CHAT_FIELDS.join('|')})['"]\\s*\\)`).test(body);+ const unfencedBody = bodyDto !== undefined && chatDtos.get(bodyDto) === 'other';const filtersChatScope = /\bchatScope\b/.test(body);- if (!hasPathChat && !hasQueryChat && !hasBodyChat && !filtersChatScope) offenders.push(name);+ if (!namesGuardChat && (unfencedQuery || unfencedBody) && !filtersChatScope) offenders.push(name);}return offenders;}@@ -96,18 +120,31 @@ describe('a chat-restricted key can only reach a handler fenced to its allowedChexpect(guard).toContain('messages');});- it('flags a marked handler with no chat id and no filtering', () => {+ it('flags a marked handler that reaches chats by a field the guard does not read', () => {const vulnerable = `@ChatScoped()- @Post('everything')- async sendThing(@Body() dto: ThingDto): Promise<unknown> {- return this.svc.send(dto);+ @Post('status')+ async postStatus(@Body() dto: SendStatusDto): Promise<unknown> {+ return this.svc.post(dto);+ }+`;+ expect(markedHandlersReachingUnfencedChats(vulnerable, new Map([['SendStatusDto', 'other']]))).toEqual([+ 'postStatus',+ ]);+ });++ it('clears a marked chat-agnostic handler (it names no chat — the mark is the assertion)', () => {+ const agnostic = `+ @ChatScoped()+ @Get('profile')+ async profile(@Param('sessionId') sessionId: string): Promise<unknown> {+ return this.svc.profile(sessionId);}`;- expect(markedHandlersWithoutChatFence(vulnerable, new Set())).toEqual(['sendThing']);+ expect(markedHandlersReachingUnfencedChats(agnostic, new Map())).toEqual([]);});- it('clears a marked handler with a path chat, a query chat, a body chat, or a filter', () => {+ it('clears a marked handler fenced by a path chat, a query chat, a body chat, or a filter', () => {const fenced = `@ChatScoped()@Get(':chatId')@@ -133,10 +170,21 @@ describe('a chat-restricted key can only reach a handler fenced to its allowedChreturn this.chatScope.filter(apiKey, await this.svc.chats(), c => c.id);}`;- expect(markedHandlersWithoutChatFence(fenced, new Set(['SendThingDto']))).toEqual([]);+ expect(markedHandlersReachingUnfencedChats(fenced, new Map([['SendThingDto', 'guard']]))).toEqual([]);+ });++ it('clears a marked group route: the :groupId in the path fences the participants it carries', () => {+ const group = `+ @ChatScoped()+ @Post(':groupId/participants')+ async addParticipants(@Param('groupId') groupId: string, @Body() dto: AddParticipantsDto): Promise<unknown> {+ return this.svc.add(groupId, dto);+ }+`;+ expect(markedHandlersReachingUnfencedChats(group, new Map([['AddParticipantsDto', 'other']]))).toEqual([]);});- it('no marked controller handler is unfenced, and the scan is not vacuous', () => {+ it('no marked controller handler reaches an unfenced chat, and the scan is not vacuous', () => {const modulesDir = join(__dirname, '..');const chatDtos = chatBearingDtoClasses(modulesDir);expect(chatDtos.size).toBeGreaterThan(0); // the DTO scan must not silently collapse@@ -149,7 +197,7 @@ describe('a chat-restricted key can only reach a handler fenced to its allowedChmarked += [...source.matchAll(/^ {2}@ChatScoped\(\)$/gm)].length;const fileName = basename(file);const posixPath = file.split(sep).join('/');- for (const handler of markedHandlersWithoutChatFence(source, chatDtos)) {+ for (const handler of markedHandlersReachingUnfencedChats(source, chatDtos)) {offenders.push(`${posixPath.replace(/.*\/src\//, 'src/')} :: ${fileName} :: ${handler}`);}}diff --git a/src/modules/auth/decorators/auth.decorators.ts b/src/modules/auth/decorators/auth.decorators.tsindex 2d30bffee..c2e97c93b 100644--- a/src/modules/auth/decorators/auth.decorators.ts+++ b/src/modules/auth/decorators/auth.decorators.ts@@ -40,16 +40,22 @@ export const Public = () => SetMetadata(PUBLIC_KEY, true);export const RequireUnscopedKey = () => SetMetadata(UNSCOPED_KEY, true);/**- * Mark a handler (or controller) a chat-restricted key — one carrying `allowedChats` — may reach,- * when the handler's target chat is one the ApiKeyGuard can see: a `:chatId` / `:groupId` /- * `:contactId` path param, a `chatId` / `fromChatId` / `toChatId` body field, or a `messages[]`- * entry's `chatId`.+ * Mark a handler (or controller) a chat-restricted key — one carrying `allowedChats` — may reach.** This is an ALLOWLIST, not a restriction: a chat-restricted key is refused with 403 on every route* that is NOT marked, so surfaces with no chat dimension (webhooks, automation rules, status, key* management, channels) — and every route added later — stay closed without having to enumerate- * them. A marked handler that lists chats instead of naming one must filter its result through- * ChatScopeService; the structural coverage spec enforces both halves.+ * them. A handler is safe to mark in one of three ways:+ *+ * - **fenced by path, body or query** — it names a chat the ApiKeyGuard inspects (`:chatId` /+ * `:groupId` / `:contactId`, `?chatId=`, or the `chatId` / `fromChatId` / `toChatId` /+ * `messages[].chatId` body fields);+ * - **filtered** — it lists chats instead of naming one, and filters the result through+ * ChatScopeService;+ * - **chat-agnostic** — it names no chat at all, so the mark itself is the assertion that it cannot+ * reach one. This is the one category the structural coverage spec cannot derive (a webhook with+ * `events: ['*']` also names no chat), so the mark is a deliberate operator decision.+ ** @example @ChatScoped() @Get(':chatId')*/export const ChatScoped = () => SetMetadata(CHAT_SCOPED_KEY, true);