Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

test(auth): make the query-param session-scope guard see every handler

Yudhi Armyndharis678cdb7564b3
diff --git a/src/modules/auth/query-session-scope-coverage.spec.ts b/src/modules/auth/query-session-scope-coverage.spec.ts
index a008e96ea..c8b48820c 100644
--- a/src/modules/auth/query-session-scope-coverage.spec.ts
+++ b/src/modules/auth/query-session-scope-coverage.spec.ts
@@ -10,15 +10,30 @@
import { readdirSync, readFileSync } from 'fs';
import { join } from 'path';
+/**
+ * Match a 2-space-indented method declaration and capture its parameter list: `name( <params> )`
+ * followed by either a return type (`:`) or the body (`{`). Decorators (`@Get(...)`) start with `@`,
+ * so they are not matched as method names.
+ *
+ * The `{` alternative is load-bearing rather than cosmetic. Requiring a return type made the checker
+ * skip every handler declared without one — 83 of 181 at the time it was widened, so a clean result
+ * described less than half the surface it appeared to cover. The coverage test below now fails if
+ * that ever becomes true again.
+ *
+ * Returned fresh on each call: the `g` flag makes `lastIndex` stateful, so a shared instance would
+ * resume mid-source for the second caller.
+ */
+export function methodPattern(): RegExp {
+ return /^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)\s*[:{]/gm;
+}
+
/**
* 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.
*/
export function handlersMissingSessionScope(source: string): string[] {
const offenders: string[] = [];
- // Match a 2-space-indented method declaration and capture its parameter list: `name( <params> ):`.
- // Decorators (`@Get(...)`) start with `@`, so they are not matched as method names.
- const methodRe = /^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(([\s\S]*?)\)\s*:/gm;
+ 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);
@@ -52,6 +67,19 @@ describe('query-param sessionId endpoints are session-scoped', () => {
expect(handlersMissingSessionScope(vulnerable)).toEqual(['findAll']);
});
+ it('flags a vulnerable handler that declares no return type', () => {
+ // The guard is only worth what it can see. A handler written without an explicit return type is
+ // just as exposed, and for most of this file's life the checker skipped every one of them.
+ const vulnerable = `
+ async findAll(
+ @Query('sessionId') sessionId?: string,
+ ) {
+ return this.svc.findAll(sessionId);
+ }
+`;
+ expect(handlersMissingSessionScope(vulnerable)).toEqual(['findAll']);
+ });
+
it('clears a handler that injects @CurrentApiKey alongside the query param', () => {
const fixed = `
async findAll(
@@ -64,6 +92,36 @@ describe('query-param sessionId endpoints are session-scoped', () => {
expect(handlersMissingSessionScope(fixed)).toEqual([]);
});
+ // A structural guard that silently stops covering things is worse than no guard, because the green
+ // result reads as "no endpoint leaks" rather than "no endpoint I looked at leaks". This pairs every
+ // HTTP-verb decorator with the method the checker would examine for it, and fails if any decorator
+ // has none — which is what a matcher that cannot parse a handler's shape looks like from outside.
+ it('examines every decorated handler, so a clean result means the whole surface', () => {
+ const modulesDir = join(__dirname, '..');
+ const blind: string[] = [];
+ let decorated = 0;
+ for (const file of listControllerFiles(modulesDir)) {
+ const source = readFileSync(file, 'utf8');
+ const decorators = [...source.matchAll(/^ {2}@(?:Get|Post|Put|Patch|Delete|All|Head|Options)\(/gm)];
+ const methods = [...source.matchAll(methodPattern())].map(m => m.index ?? 0);
+ for (let i = 0; i < decorators.length; i++) {
+ decorated++;
+ const from = decorators[i].index ?? 0;
+ const until = decorators[i + 1]?.index ?? Number.MAX_SAFE_INTEGER;
+ // The handler a decorator belongs to is the first method starting before the next decorator.
+ if (methods.some(at => at > from && at < until)) continue;
+ blind.push(
+ `${file.replace(/.*\/src\//, 'src/')} :: ${source
+ .slice(from, from + 40)
+ .split('\n')[0]
+ .trim()}`,
+ );
+ }
+ }
+ expect(decorated).toBeGreaterThan(100); // the count itself must not silently collapse to zero
+ expect(blind).toEqual([]);
+ });
+
it('no real controller takes @Query(sessionId) without scoping to the calling key', () => {
const modulesDir = join(__dirname, '..');
const offenders: string[] = [];