Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(api): scope audit-log and delivery-failure lists to the key's allowed sessions (#882)
Yudhi Armyndharis8c79170d3df8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7d4a6d9fb..2416df9fe 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,6 +15,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **Session scoping on the audit-log and webhook delivery-failure list endpoints.** `GET /api/audit`+ and `GET /api/webhooks/delivery-failures` now scope their results to the calling key's allowed+ sessions, matching the rest of the API (`GET /webhooks`, `GET /search`). These two endpoints take+ `sessionId` as a query parameter, which the API-key session fence — resolved only from route+ params — did not cover, so a key restricted to a subset of sessions saw rows for every session+ (and `GET /api/audit` with no `sessionId` returned every session's rows). A query `sessionId` may+ now only narrow within the key's allowed sessions; unrestricted keys are unaffected. A structural+ test now fails the build if any handler accepts a `sessionId` query param without scoping to the+ calling key, so the gap cannot reappear.+- **Chat list unread badge shape and overflow.** The unread-count badge in the chats sidebar rendered as an uneven oval and grew without bound as the count climbed. It now uses a fixed height with border-box sizing so a single digit is a true circle and larger counts form a rounded pill, and its label is capped at `99+`. The badge also exposes the exact unread count to assistive technology and as a hover tooltip.## [0.10.7] - 2026-07-23diff --git a/src/common/security/session-scope.spec.ts b/src/common/security/session-scope.spec.tsnew file mode 100644index 000000000..afc380c46--- /dev/null+++ b/src/common/security/session-scope.spec.ts@@ -0,0 +1,28 @@+import { resolveSessionScope } from './session-scope';++// The key's allowedSessions is authoritative: a query-supplied sessionId may only NARROW within it,+// never broaden it. null = "no filter (see all)"; [] = "requested session outside scope, see nothing".+describe('resolveSessionScope', () => {+ it('unrestricted key (null/empty/undefined allowlist) with no requested session => no filter', () => {+ expect(resolveSessionScope(null)).toBeNull();+ expect(resolveSessionScope([])).toBeNull();+ expect(resolveSessionScope(undefined)).toBeNull();+ });++ it('unrestricted key narrows to the requested session', () => {+ expect(resolveSessionScope(null, 'X')).toEqual(['X']);+ expect(resolveSessionScope([], 'X')).toEqual(['X']);+ });++ it('scoped key with no requested session => the whole allowlist', () => {+ expect(resolveSessionScope(['A', 'B'])).toEqual(['A', 'B']);+ });++ it('scoped key narrows to a requested session that is inside its allowlist', () => {+ expect(resolveSessionScope(['A', 'B'], 'A')).toEqual(['A']);+ });++ it('scoped key requesting a session OUTSIDE its allowlist => empty (match nothing), not the request', () => {+ expect(resolveSessionScope(['A', 'B'], 'C')).toEqual([]);+ });+});diff --git a/src/common/security/session-scope.ts b/src/common/security/session-scope.tsnew file mode 100644index 000000000..d200190d0--- /dev/null+++ b/src/common/security/session-scope.ts@@ -0,0 +1,23 @@+/**+ * Resolve the effective session filter for a scoped read. The calling key's `allowedSessions` is+ * authoritative: a request-supplied `sessionId` may only narrow WITHIN that scope, never broaden it.+ * This is the shared fix for endpoints that accept `sessionId` as a query param, which the+ * ApiKeyGuard's route-param-only fence does not cover (see audit + webhook delivery-failures).+ *+ * Returns:+ * - `null` → no filter; the caller queries all sessions (unrestricted key, no narrowing)+ * - `string[]` (non-empty) → filter `sessionId IN (...)` (the whole allowlist, or a single narrowed id)+ * - `[]` → the requested session is outside the key's scope; the caller must return nothing+ *+ * A null/empty `allowedSessions` means "unrestricted" (e.g. an ADMIN key), mirroring the guard model.+ */+export function resolveSessionScope(+ allowedSessions: string[] | null | undefined,+ requestedSessionId?: string,+): string[] | null {+ const scoped = allowedSessions != null && allowedSessions.length > 0;+ if (scoped) {+ return requestedSessionId ? allowedSessions.filter(s => s === requestedSessionId) : allowedSessions;+ }+ return requestedSessionId ? [requestedSessionId] : null;+}diff --git a/src/modules/audit/audit-session-scope.spec.ts b/src/modules/audit/audit-session-scope.spec.tsnew file mode 100644index 000000000..e84ba55a8--- /dev/null+++ b/src/modules/audit/audit-session-scope.spec.ts@@ -0,0 +1,58 @@+// A session-scoped ADMIN key (allowedSessions set) must not read another tenant's audit rows.+// The ApiKeyGuard fence only reads route params, so `GET /api/audit?sessionId=...` (a QUERY param)+// bypasses it — with no param at all, an unscoped findAll returns every tenant's rows. These run+// against a real in-memory DB so the scoping is exercised end-to-end, not asserted on a mock.+import { DataSource } from 'typeorm';+import { AuditService } from './audit.service';+import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entity';++describe('AuditService session-scoped findAll', () => {+ let ds: DataSource;+ let service: AuditService;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [AuditLog],+ synchronize: true,+ });+ await ds.initialize();+ const repo = ds.getRepository(AuditLog);+ service = new AuditService(repo);+ for (const sessionId of ['sessA', 'sessB']) {+ await repo.save(repo.create({ action: AuditAction.SESSION_CREATED, severity: AuditSeverity.INFO, sessionId }));+ }+ });++ afterEach(async () => {+ await ds.destroy();+ });++ it('a key scoped to sessA sees only sessA rows, never sessB', async () => {+ const { data, total } = await service.findAll({}, ['sessA']);+ expect(data.map(r => r.sessionId)).toEqual(['sessA']);+ expect(total).toBe(1);+ });++ it('a scoped key with NO sessionId param does not leak other tenants (the where={} leak)', async () => {+ const { data } = await service.findAll({}, ['sessA']);+ expect(data.every(r => r.sessionId === 'sessA')).toBe(true);+ });++ it('a scoped key requesting sessB (outside its scope) gets nothing, not sessB', async () => {+ const { data, total } = await service.findAll({ sessionId: 'sessB' }, ['sessA']);+ expect(data).toEqual([]);+ expect(total).toBe(0);+ });++ it('an unrestricted key (null allowlist) still sees all tenants', async () => {+ const { total } = await service.findAll({}, null);+ expect(total).toBe(2);+ });++ it('an unrestricted key can still narrow to a single session via the query param', async () => {+ const { data } = await service.findAll({ sessionId: 'sessB' }, null);+ expect(data.map(r => r.sessionId)).toEqual(['sessB']);+ });+});diff --git a/src/modules/audit/audit.controller.ts b/src/modules/audit/audit.controller.tsindex 5c1388673..6022e38e6 100644--- a/src/modules/audit/audit.controller.ts+++ b/src/modules/audit/audit.controller.ts@@ -2,8 +2,8 @@ import { Controller, Get, Query } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';import { AuditService, AuditQueryOptions } from './audit.service';import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entity';-import { RequireRole } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { RequireRole, CurrentApiKey } from '../auth/decorators/auth.decorators';+import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';@ApiTags('audit')@Controller('audit')@@ -24,6 +24,7 @@ export class AuditController {description: 'Paginated list of audit logs',})async findAll(+ @CurrentApiKey() apiKey?: ApiKey,@Query('action') action?: AuditAction,@Query('severity') severity?: AuditSeverity,@Query('sessionId') sessionId?: string,@@ -39,6 +40,8 @@ export class AuditController {if (limit) options.limit = parseInt(limit, 10);if (offset) options.offset = parseInt(offset, 10);- return this.auditService.findAll(options);+ // Scope to the calling key's allowedSessions so a session-restricted ADMIN key cannot read+ // another tenant's audit rows via the `sessionId` query param (which bypasses the guard fence).+ return this.auditService.findAll(options, apiKey?.allowedSessions);}}diff --git a/src/modules/audit/audit.service.ts b/src/modules/audit/audit.service.tsindex 7be66df4a..a18b8f5f9 100644--- a/src/modules/audit/audit.service.ts+++ b/src/modules/audit/audit.service.ts@@ -1,10 +1,11 @@import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';import { InjectRepository } from '@nestjs/typeorm';-import { Repository, Between, LessThan } from 'typeorm';+import { Repository, Between, LessThan, In } from 'typeorm';import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entity';import { ApiKey } from '../auth/entities/api-key.entity';import { createLogger } from '../../common/services/logger.service';import { getRequestId, getRequestActor } from '../../common/services/request-context';+import { resolveSessionScope } from '../../common/security/session-scope';/** Upper bound on a single audit-log page, so a large `limit` can't load the whole table at once. */export const MAX_AUDIT_PAGE_SIZE = 200;@@ -134,7 +135,10 @@ export class AuditService implements OnModuleInit, OnModuleDestroy {return this.log(action, context, AuditSeverity.ERROR);}- async findAll(options: AuditQueryOptions = {}): Promise<{+ async findAll(+ options: AuditQueryOptions = {},+ allowedSessions?: string[] | null,+ ): Promise<{data: AuditLog[];total: number;}> {@@ -142,7 +146,14 @@ export class AuditService implements OnModuleInit, OnModuleDestroy {if (options.action) where.action = options.action;if (options.apiKeyId) where.apiKeyId = options.apiKeyId;- if (options.sessionId) where.sessionId = options.sessionId;+ // The calling key's allowedSessions is authoritative; the query sessionId may only narrow within it.+ // Without this, a session-scoped ADMIN key reads every tenant's rows (no param => where.sessionId+ // unset => all), because the ApiKeyGuard fence only inspects route params, not the query string.+ const sessionScope = resolveSessionScope(allowedSessions, options.sessionId);+ if (sessionScope !== null) {+ if (sessionScope.length === 0) return { data: [], total: 0 }; // requested session outside the key's scope+ where.sessionId = In(sessionScope);+ }if (options.severity) where.severity = options.severity;if (options.startDate && options.endDate) {diff --git a/src/modules/auth/query-session-scope-coverage.spec.ts b/src/modules/auth/query-session-scope-coverage.spec.tsnew file mode 100644index 000000000..a008e96ea--- /dev/null+++ b/src/modules/auth/query-session-scope-coverage.spec.ts@@ -0,0 +1,77 @@+// Structural guard for the cross-tenant scoping class of bug (audit + webhook delivery-failures).+//+// The ApiKeyGuard session fence resolves the scoped sessionId from ROUTE PARAMS only+// (api-key.guard.ts). So any handler that instead accepts `sessionId` as a QUERY param is NOT+// 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.+import { readdirSync, readFileSync } from 'fs';+import { join } from 'path';++/**+ * 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;+ 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 injectsCurrentApiKey = /@CurrentApiKey\(/.test(params);+ if (takesSessionIdQuery && !injectsCurrentApiKey) offenders.push(name);+ }+ return offenders;+}++function listControllerFiles(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(...listControllerFiles(full));+ else if (entry.name.endsWith('.controller.ts') && !entry.name.endsWith('.spec.ts')) out.push(full);+ }+ return out;+}++describe('query-param sessionId endpoints are session-scoped', () => {+ // The checker itself must actually detect the leak — a structural guard that can't fail proves nothing.+ it('flags a handler that takes @Query(sessionId) without @CurrentApiKey', () => {+ const vulnerable = `+ async findAll(+ @Query('sessionId') sessionId?: string,+ @Query('limit') limit?: string,+ ): Promise<unknown> {+ 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(+ @CurrentApiKey() apiKey?: ApiKey,+ @Query('sessionId') sessionId?: string,+ ): Promise<unknown> {+ return this.svc.findAll(sessionId, apiKey?.allowedSessions);+ }+`;+ expect(handlersMissingSessionScope(fixed)).toEqual([]);+ });++ it('no real controller takes @Query(sessionId) without scoping to the calling key', () => {+ const modulesDir = join(__dirname, '..');+ const offenders: string[] = [];+ for (const file of listControllerFiles(modulesDir)) {+ for (const handler of handlersMissingSessionScope(readFileSync(file, 'utf8'))) {+ offenders.push(`${file.replace(/.*\/src\//, 'src/')} :: ${handler}`);+ }+ }+ expect(offenders).toEqual([]);+ });+});diff --git a/src/modules/webhook/delivery-failures-scope.spec.ts b/src/modules/webhook/delivery-failures-scope.spec.tsnew file mode 100644index 000000000..e4f086803--- /dev/null+++ b/src/modules/webhook/delivery-failures-scope.spec.ts@@ -0,0 +1,61 @@+// GET /webhooks/delivery-failures takes sessionId as a QUERY param, which the ApiKeyGuard fence+// (route-params only) does not scope. A session-restricted ADMIN key must not read another session's+// failed-delivery rows — which carry the webhook URL, event, idempotencyKey and lastError. Exercised+// end-to-end against a real in-memory DB, mirroring webhook-session-scope.spec.ts.+import { DataSource } from 'typeorm';+import { WebhookService } from './webhook.service';+import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entity';++describe('WebhookService.listDeliveryFailures session scoping', () => {+ let ds: DataSource;+ let service: WebhookService;++ beforeEach(async () => {+ ds = new DataSource({+ type: 'better-sqlite3',+ database: ':memory:',+ entities: [WebhookDeliveryFailure],+ synchronize: true,+ });+ await ds.initialize();+ const failureRepo = ds.getRepository(WebhookDeliveryFailure);+ const cfg = { get: () => false };+ service = new WebhookService({} as never, failureRepo, cfg as never, {} as never, undefined);+ for (const sessionId of ['sessA', 'sessB']) {+ await failureRepo.save(+ failureRepo.create({+ webhookId: `wh-${sessionId}`,+ sessionId,+ event: 'message.received',+ url: `https://${sessionId}.example/hook`,+ attempts: 3,+ lastError: 'ECONNREFUSED',+ }),+ );+ }+ });++ afterEach(async () => {+ await ds.destroy();+ });++ it('a key scoped to sessA sees only sessA failures, never sessB', async () => {+ const rows = await service.listDeliveryFailures({}, ['sessA']);+ expect(rows.map(r => r.sessionId)).toEqual(['sessA']);+ });++ it('a scoped key requesting sessB (outside its scope) gets nothing', async () => {+ const rows = await service.listDeliveryFailures({ sessionId: 'sessB' }, ['sessA']);+ expect(rows).toEqual([]);+ });++ it('an unrestricted key (null allowlist) sees all sessions', async () => {+ const rows = await service.listDeliveryFailures({}, null);+ expect(rows.map(r => r.sessionId).sort()).toEqual(['sessA', 'sessB']);+ });++ it('an unrestricted key can narrow to a single session via the query param', async () => {+ const rows = await service.listDeliveryFailures({ sessionId: 'sessB' }, null);+ expect(rows.map(r => r.sessionId)).toEqual(['sessB']);+ });+});diff --git a/src/modules/webhook/webhook.service.spec.ts b/src/modules/webhook/webhook.service.spec.tsindex 77ab336d5..4f61253a3 100644--- a/src/modules/webhook/webhook.service.spec.ts+++ b/src/modules/webhook/webhook.service.spec.ts@@ -1118,8 +1118,10 @@ describe('WebhookService', () => {const out = await service.listDeliveryFailures({ sessionId: 's1', limit: 10 });expect(out).toHaveLength(1);+ // sessionId resolves through resolveSessionScope, so the WHERE is an IN over the effective scope+ // ([s1] here for an unrestricted key narrowing to one session) — behaviourally the same rows.expect(failureRepository.find).toHaveBeenCalledWith(- expect.objectContaining({ where: { sessionId: 's1' }, order: { createdAt: 'DESC' } }),+ expect.objectContaining({ where: { sessionId: In(['s1']) }, order: { createdAt: 'DESC' } }),);});});diff --git a/src/modules/webhook/webhook.service.ts b/src/modules/webhook/webhook.service.tsindex 085312de6..98f456376 100644--- a/src/modules/webhook/webhook.service.ts+++ b/src/modules/webhook/webhook.service.ts@@ -17,6 +17,7 @@ import { WebhookDeliveryFailure } from './entities/webhook-delivery-failure.entiimport { recordWebhookDeliveryFailure, statusCodeFromError } from './utils/record-delivery-failure';import { CreateWebhookDto, UpdateWebhookDto } from './dto';import { createLogger } from '../../common/services/logger.service';+import { resolveSessionScope } from '../../common/security/session-scope';import { incrementWebhookDeliveryFailures } from '../../common/metrics/webhook-delivery-metrics';import { ListOptions, resolveListWindow } from '../../common/utils/paginate';import { QUEUE_NAMES } from '../queue/queue-names';@@ -182,12 +183,20 @@ export class WebhookService implements OnModuleInit, OnModuleDestroy {/*** Recently-failed webhook deliveries (most recent first), so an operator can see what was lost during* a receiver outage. ADMIN-only operational data; an optional sessionId narrows it. Bounded by the- * shared pagination window.+ * shared pagination window. The calling key's allowedSessions is authoritative — the sessionId query+ * param may only narrow within it — because this endpoint takes sessionId as a query param, which the+ * ApiKeyGuard fence (route params only) does not scope; otherwise a session-restricted key could read+ * every session's failed-delivery URLs and errors.*/- async listDeliveryFailures(opts: ListOptions & { sessionId?: string } = {}): Promise<WebhookDeliveryFailure[]> {+ async listDeliveryFailures(+ opts: ListOptions & { sessionId?: string } = {},+ allowedSessions?: string[] | null,+ ): Promise<WebhookDeliveryFailure[]> {const { limit, offset } = resolveListWindow(opts.limit, opts.offset);+ const sessionScope = resolveSessionScope(allowedSessions, opts.sessionId);+ if (sessionScope !== null && sessionScope.length === 0) return []; // requested session outside the key's scopereturn this.failureRepository.find({- where: opts.sessionId ? { sessionId: opts.sessionId } : {},+ where: sessionScope ? { sessionId: In(sessionScope) } : {},order: { createdAt: 'DESC' },take: limit,skip: offset,diff --git a/src/modules/webhook/webhooks-list.controller.ts b/src/modules/webhook/webhooks-list.controller.tsindex 6c1288041..0471f83cb 100644--- a/src/modules/webhook/webhooks-list.controller.ts+++ b/src/modules/webhook/webhooks-list.controller.ts@@ -19,15 +19,21 @@ export class WebhooksListController {@ApiQuery({ name: 'limit', required: false, description: 'Max records to return (1-1000, default 1000)' })@ApiQuery({ name: 'offset', required: false, description: 'Number of records to skip (for paging)' })async deliveryFailures(+ @CurrentApiKey() apiKey?: ApiKey,@Query('sessionId') sessionId?: string,@Query('limit') limit?: string,@Query('offset') offset?: string,): Promise<WebhookDeliveryFailure[]> {- return this.webhookService.listDeliveryFailures({- sessionId,- limit: limit ? parseInt(limit, 10) : undefined,- offset: offset ? parseInt(offset, 10) : undefined,- });+ // Scope to the calling key's allowedSessions so a session-restricted ADMIN key cannot read another+ // session's failed-delivery URLs/errors via the `sessionId` query param (which bypasses the guard).+ return this.webhookService.listDeliveryFailures(+ {+ sessionId,+ limit: limit ? parseInt(limit, 10) : undefined,+ offset: offset ? parseInt(offset, 10) : undefined,+ },+ apiKey?.allowedSessions,+ );}@Get()diff --git a/test/session-scope.e2e-spec.ts b/test/session-scope.e2e-spec.tsnew file mode 100644index 000000000..fc5474c36--- /dev/null+++ b/test/session-scope.e2e-spec.ts@@ -0,0 +1,137 @@+// 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';+import { AuditLog, AuditAction, AuditSeverity } from './../src/modules/audit/entities/audit-log.entity';+import { WebhookDeliveryFailure } from './../src/modules/webhook/entities/webhook-delivery-failure.entity';++/**+ * End-to-end proof that GET /api/audit and GET /api/webhooks/delivery-failures — which take sessionId+ * as a QUERY param, outside the ApiKeyGuard's route-param session fence — are scoped to the calling+ * key's allowedSessions. Exercised through the real HTTP stack (guard + @CurrentApiKey + DI + routing),+ * which the unit specs mock away: a session-restricted ADMIN key must never read another session's rows.+ */+describe('Session-scoped query endpoints (e2e)', () => {+ let app: INestApplication<App>;+ let sessA: string;+ let sessB: string;+ let scopedKey: string; // ADMIN, allowedSessions: [sessA]+ let adminKey: string; // ADMIN, unrestricted++ 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'));+ const auditRepo: Repository<AuditLog> = app.get(getRepositoryToken(AuditLog, 'main'));+ const failureRepo: Repository<WebhookDeliveryFailure> = app.get(getRepositoryToken(WebhookDeliveryFailure, 'data'));++ const a = await sessionRepo.save(sessionRepo.create({ name: `e2e-scope-a-${Date.now()}` }));+ const b = await sessionRepo.save(sessionRepo.create({ name: `e2e-scope-b-${Date.now()}` }));+ sessA = a.id;+ sessB = b.id;++ // One audit row and one delivery-failure row per session, so a cross-tenant read has something to leak.+ for (const sessionId of [sessA, sessB]) {+ await auditRepo.save(+ auditRepo.create({ action: AuditAction.SESSION_CREATED, severity: AuditSeverity.INFO, sessionId }),+ );+ await failureRepo.save(+ failureRepo.create({+ webhookId: `wh-${sessionId}`,+ sessionId,+ event: 'message.received',+ url: `https://${sessionId}.example/hook`,+ attempts: 3,+ lastError: 'ECONNREFUSED',+ }),+ );+ }++ const authService = app.get(AuthService);+ scopedKey = (+ await authService.createApiKey({ name: 'e2e-scoped', role: ApiKeyRole.ADMIN, allowedSessions: [sessA] })+ ).rawKey;+ adminKey = (await authService.createApiKey({ name: 'e2e-admin', role: ApiKeyRole.ADMIN })).rawKey;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ describe('GET /api/audit', () => {+ it('a key scoped to sessA sees sessA rows but never sessB (no sessionId param => no cross-tenant leak)', async () => {+ const res = await request(app.getHttpServer()).get('/api/audit').set('X-API-Key', scopedKey).expect(200);+ const body = res.body as { data: AuditLog[]; total: number };+ const sessions = body.data.map(r => r.sessionId);+ expect(sessions).toContain(sessA);+ expect(sessions).not.toContain(sessB);+ });++ it('a scoped key requesting sessB via query param gets nothing (cannot broaden its scope)', async () => {+ const res = await request(app.getHttpServer())+ .get('/api/audit')+ .query({ sessionId: sessB })+ .set('X-API-Key', scopedKey)+ .expect(200);+ const body = res.body as { data: AuditLog[]; total: number };+ expect(body.data).toEqual([]);+ expect(body.total).toBe(0);+ });++ it('an unrestricted ADMIN key still sees both sessions', async () => {+ const res = await request(app.getHttpServer()).get('/api/audit').set('X-API-Key', adminKey).expect(200);+ const body = res.body as { data: AuditLog[]; total: number };+ const sessions = body.data.map(r => r.sessionId);+ expect(sessions).toContain(sessA);+ expect(sessions).toContain(sessB);+ });+ });++ describe('GET /api/webhooks/delivery-failures', () => {+ it('a key scoped to sessA sees sessA failures but never sessB', async () => {+ const res = await request(app.getHttpServer())+ .get('/api/webhooks/delivery-failures')+ .set('X-API-Key', scopedKey)+ .expect(200);+ const sessions = (res.body as WebhookDeliveryFailure[]).map(r => r.sessionId);+ expect(sessions).toContain(sessA);+ expect(sessions).not.toContain(sessB);+ });++ it('a scoped key requesting sessB via query param gets nothing', async () => {+ const res = await request(app.getHttpServer())+ .get('/api/webhooks/delivery-failures')+ .query({ sessionId: sessB })+ .set('X-API-Key', scopedKey)+ .expect(200);+ expect(res.body).toEqual([]);+ });++ it('an unrestricted ADMIN key still sees both sessions', async () => {+ const res = await request(app.getHttpServer())+ .get('/api/webhooks/delivery-failures')+ .set('X-API-Key', adminKey)+ .expect(200);+ const sessions = (res.body as WebhookDeliveryFailure[]).map(r => r.sessionId);+ expect(sessions).toContain(sessA);+ expect(sessions).toContain(sessB);+ });+ });+});