Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): reject session-restricted API keys on deployment-global surfaces (#1005)
Yudhi Armyndharis203b0a5883fd
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a9562e48c..241ea3dda 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -186,6 +186,43 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0variant of the same message — a browser profile left stale by a Chromium-binary change (#663/#708) —is raised inside `initialize()`, caught by the adapter, and keeps its existing advisory.+- Service start during Docker orchestration now applies the same managed-profile allowlist as+ teardown. Non-managed profile names are dropped before reaching `DockerService` in both directions,+ so the start path cannot select an unrelated host container any more than teardown can.++### Security++- Infrastructure routes (`/api/infra/*`) now reject API keys restricted to specific sessions.+ These routes act on the whole deployment, so a key confined to a subset of sessions must not+ reach them regardless of its role. Unrestricted ADMIN keys are unaffected.++- Plugin installation and lifecycle routes (`/api/plugins/*`) now reject API keys restricted to+ specific sessions. Installing or enabling a plugin runs its code in the gateway process, which is+ a deployment-wide action. Per-session plugin activation (`PUT /api/plugins/:id/sessions`) and+ per-session config (`PUT /api/plugins/:id/config/:sessionId`) continue to accept restricted keys+ and remain scoped to the sessions the key allows.++- The queue dashboard (`/admin/queues`, available when `QUEUE_ENABLED=true`) now refuses API keys+ restricted to specific sessions. The dashboard exposes and mutates every queue in the deployment+ and has no session dimension to scope against.++- Cross-session statistics (`GET /api/stats/overview`, `GET /api/stats/messages`), application+ settings (`GET /api/settings`), and session creation (`POST /api/sessions`) now require an API key+ that is not restricted to specific sessions. Per-session statistics remain available to restricted+ keys for the sessions they allow.++- Redriving a dead-lettered integration delivery now fails closed for session-restricted keys when+ the integration instance no longer exists. Previously the scope check was skipped for a missing+ instance, so retained dead-letter rows could be re-dispatched for sessions outside the key's scope.++- Outbound downloads that follow redirects (plugin packages and the plugin catalog) now validate+ every redirect hop before connecting. Previously a redirect whose target was a bare IP address+ bypassed the destination check, because the platform skips name resolution for address literals.+ Redirect chains are also capped.++- Added a build-time check that fails when a route acting on the whole deployment is added without+ refusing session-restricted API keys, so this class of gap cannot be reintroduced silently.+## [0.11.1] - 2026-07-28### Addeddiff --git a/SECURITY.md b/SECURITY.mdindex ed74724dc..b88b884fc 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -71,7 +71,8 @@ it as one:Mitigations in place: the proxy is unreachable except from `openwa-api` (dedicated`internal: true` network), the orchestration endpoints require an ADMIN-role API key,-teardown is allowlisted to the three managed profiles (`postgres`, `redis`, `minio`),+both teardown and start are constrained to the three managed profiles (`postgres`,+`redis`, `minio`) — non-managed names are dropped before reaching `DockerService` —and OpenWA itself never issues deletes (profile teardown is stop-only). If you do notuse the built-in datastore orchestration (Dashboard → Infrastructure built-intoggles), disable the proxy entirely — see the `docker-proxy` comments indiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 91344765c..e5a91b393 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -375,7 +375,7 @@ Get session statistics for multi-session monitoring.Create a new WhatsApp session.-**Auth:** API key (OPERATOR)+**Auth:** API key (OPERATOR) that is not restricted to specific sessions. Creating a session is a deployment-level act: the new session is outside the caller's `allowedSessions` by construction, so a session-scoped key is rejected with `403` (`@RequireUnscopedKey`). An unscoped OPERATOR/ADMIN key may create a session.**Request body** — `CreateSessionDto`@@ -3844,7 +3844,7 @@ Values come from `StatsService.getOverview()` plus `process.memoryUsage()`/`procGet overall cross-session aggregate statistics (sessions by status + message totals + today's counts).-**Auth:** API key (ADMIN) — deliberately ADMIN-only (global cross-tenant aggregate).+**Auth:** API key (ADMIN) that is not restricted to specific sessions — a global cross-tenant aggregate, so a session-scoped key has no claim on it and is rejected with `403` (`@RequireUnscopedKey`).**Response** `200`@@ -3866,13 +3866,13 @@ Get overall cross-session aggregate statistics (sessions by status + message totNotes: raw handler return (no envelope). `sessions.byStatus` is keyed by the stored `SessionStatus` values — lowercase, per §6.4.1 — with per-status counts; `sessions.active` counts only `ready`. `messages.sent`/`received` are all-time outgoing/incoming COUNTs; `failed` is the `FAILED`-status COUNT; `today.*` are the same counts since local midnight. Side effect: caches the `sessions` block via `CacheService`.-**Errors:** `401` — missing/invalid `X-API-Key` · `403` — key role below `ADMIN`.+**Errors:** `401` — missing/invalid `X-API-Key` · `403` — key role below `ADMIN`, or the key is session-restricted.#### GET /api/stats/messagesGet message statistics over a period: time series, counts by type, by session, and top chats.-**Auth:** API key (ADMIN) — cross-session aggregate.+**Auth:** API key (ADMIN) that is not restricted to specific sessions — a cross-session aggregate, so a session-scoped key is rejected with `403` (`@RequireUnscopedKey`).**Query parameters**@@ -3900,7 +3900,7 @@ Get message statistics over a period: time series, counts by type, by session, aNotes: raw handler return. `timeSeries.timestamp` is a DB-formatted bucket string — hourly `YYYY-MM-DD HH:00:00` for `24h`, daily `YYYY-MM-DD` for `7d`/`30d` — sorted ascending. `byType` keys are message-type strings (a null type becomes `unknown`). `bySession.name` is `Unknown` when the session is not found. `topChats` is the top 10 by `messageCount` DESC. All counts are numbers.-**Errors:** `400` — `period` not in the enum, or any non-whitelisted query field (strict `whitelist` + `forbidNonWhitelisted`) · `401` — missing/invalid API key · `403` — role below `ADMIN`.+**Errors:** `400` — `period` not in the enum, or any non-whitelisted query field (strict `whitelist` + `forbidNonWhitelisted`) · `401` — missing/invalid API key · `403` — role below `ADMIN`, or the key is session-restricted.#### GET /api/stats/sessions/:sessionId@@ -3938,7 +3938,7 @@ Notes: raw handler return. `session.status` is the `SessionStatus` enum value. `Get application settings (environment-derived; `general`/`api`/`notifications` groups).-**Auth:** API key (ADMIN). Settings expose server configuration, so a key below `ADMIN` is rejected with `403`. The route carries no session dimension and is not fenced with `@RequireUnscopedKey`, so a session-scoped ADMIN key is accepted.+**Auth:** API key (ADMIN) that is not restricted to specific sessions. Settings describe the whole deployment, so the route requires an unrestricted key (`@RequireUnscopedKey`): the role check alone does not exclude a key confined to a subset of sessions, which has no claim on deployment-wide configuration, so a session-scoped ADMIN key is rejected with `403`. A key below `ADMIN` is also rejected with `403`.**Response** `200`@@ -3964,7 +3964,7 @@ Get application settings (environment-derived; `general`/`api`/`notifications` gNotes: raw return of an in-memory `Settings` object built once in the controller constructor from `ConfigService` (snapshotted at construction, not re-read per request). `api.rateLimitWindow` is in ms. `enableDocs` reflects the `ENABLE_SWAGGER` gate (enabled by default outside production; disabled by default in production unless explicitly enabled). Only `notifications.*` is currently hardcoded (`emailEnabled: false`, `notificationEmail: ''`, `webhookAlerts: true`).-**Errors:** `401` — missing/invalid `X-API-Key` · `403` — API key lacks the ADMIN role.+**Errors:** `401` — missing/invalid `X-API-Key` · `403` — API key lacks the ADMIN role, or the key is session-restricted.#### PUT /api/settingsdiff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.tsindex 58916a243..da0de2cf4 100644--- a/src/common/security/bull-board-auth.middleware.spec.ts+++ b/src/common/security/bull-board-auth.middleware.spec.ts@@ -58,6 +58,56 @@ describe('BullBoardAuthMiddleware', () => {expect(authService.validateApiKey).toHaveBeenCalledWith('admin', '127.0.0.1');});+ it('rejects an ADMIN key that is restricted to specific sessions', async () => {+ authService.validateApiKey.mockResolvedValue({+ id: 'key-1',+ name: 'scoped-admin',+ role: ApiKeyRole.ADMIN,+ allowedSessions: ['session-a'],+ });+ authService.hasPermission.mockReturnValue(true);++ const req = reqWith({ 'x-api-key': 'raw-key' });+ const next = jest.fn();++ await mw.use(req, res, next);++ expect(next).toHaveBeenCalledTimes(1);+ const forwarded = (next.mock.calls as Array<Array<unknown>>)[0]?.[0];+ expect(forwarded).toBeInstanceOf(ForbiddenException);+ expect((forwarded as ForbiddenException).message).toContain('restricted');+ });++ it('admits an ADMIN key with an empty allowedSessions list', async () => {+ authService.validateApiKey.mockResolvedValue({+ id: 'key-2',+ name: 'unscoped-admin',+ role: ApiKeyRole.ADMIN,+ allowedSessions: [],+ });+ authService.hasPermission.mockReturnValue(true);++ const next = jest.fn();+ await mw.use(reqWith({ 'x-api-key': 'raw-key' }), res, next);++ expect(next).toHaveBeenCalledWith();+ });++ it('admits an ADMIN key with a null allowedSessions list', async () => {+ authService.validateApiKey.mockResolvedValue({+ id: 'key-3',+ name: 'null-scope-admin',+ role: ApiKeyRole.ADMIN,+ allowedSessions: null,+ });+ authService.hasPermission.mockReturnValue(true);++ const next = jest.fn();+ await mw.use(reqWith({ 'x-api-key': 'raw-key' }), res, next);++ expect(next).toHaveBeenCalledWith();+ });+it('accepts a Bearer token', async () => {authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.ADMIN });authService.hasPermission.mockReturnValue(true);diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.tsindex 8251f3f50..5d88b7193 100644--- a/src/common/security/bull-board-auth.middleware.ts+++ b/src/common/security/bull-board-auth.middleware.ts@@ -31,6 +31,8 @@ import { resolveClientIp } from '../utils/ip';* This is a boundary trace of queue-mutation attempts reaching the Bull Board router (the UI's* retry/remove/pause actions are POSTs); it deliberately does NOT model Bull Board's internal* per-action outcomes, which are invisible from middleware.+ * Session-restricted keys are refused outright: the board is deployment-global, so a key confined to+ * a subset of sessions has no scope to enforce against it.* Both are fire-and-forget: audit logging is best-effort and must never affect the auth decision.*/@Injectable()@@ -71,6 +73,14 @@ export class BullBoardAuthMiddleware implements NestMiddleware {throw new ForbiddenException('Admin role required to access the queue dashboard');}+ // The board shows and mutates every queue in the deployment, and carries no session dimension+ // to scope against. validateApiKey above is called without a session id, so a key restricted to+ // specific sessions passes its scope check by default — reject it here instead. This mirrors+ // @RequireUnscopedKey on the REST surface, which cannot reach this raw-Express mount.+ if ((apiKey.allowedSessions?.length ?? 0) > 0) {+ throw new ForbiddenException('API keys restricted to specific sessions cannot access the queue dashboard');+ }+// Boundary trace of queue-mutation attempts. GET/HEAD are the UI's read/poll traffic; every// other method reaching the Bull Board router mutates queue state, so record it with the// authenticated key, the resolved client IP, and the method + full path (no query string).diff --git a/src/common/security/ssrf-guard.spec.ts b/src/common/security/ssrf-guard.spec.tsindex e7b63f4a7..68ead6227 100644--- a/src/common/security/ssrf-guard.spec.ts+++ b/src/common/security/ssrf-guard.spec.ts@@ -11,6 +11,8 @@ import {} from './ssrf-guard';import * as dnsPromises from 'dns/promises';import { fetch as undiciFetch, Agent } from 'undici';+import { createServer } from 'node:http';+import type { AddressInfo } from 'node:net';// Default to the real resolver (so the localhost/real-DNS cases below behave normally); individual// tests override a single call with mockResolvedValueOnce to simulate a specific resolution.@@ -284,23 +286,38 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {expect(init.dispatcher).toBeUndefined();});- it('follows redirects through a validating dispatcher when followRedirects is set (download path)', async () => {- // GitHub Releases 302 to a CDN; the download path must follow (not refuse) redirects — but via a- // per-host validating lookup so every hop is still checked. Here the original host validates and a- // 302 is delivered to `use` (proving assertNoRedirect is NOT applied on this path).- (dnsPromises.lookup as jest.Mock).mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]);- (undiciFetch as jest.Mock).mockResolvedValue({ status: 302, type: 'basic' });- const use = jest.fn(() => 'followed');+ it('follows redirects hop-by-hop, re-validating each target and delivering the final 200 (download path)', async () => {+ // GitHub Releases 302 to a CDN; the download path must follow (not refuse) redirects — but by+ // fetching each hop with `redirect: 'manual'` and re-running resolveSafeFetchTarget on the+ // Location, so every hop is checked BEFORE its socket opens. Here hop 0 is a 302 to a second+ // hostname, and hop 1 is the final 200 delivered to `use`.+ (dnsPromises.lookup as jest.Mock)+ .mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }]) // github.com+ .mockResolvedValueOnce([{ address: '185.199.108.153', family: 4 }]); // objects.githubusercontent.com+ (undiciFetch as jest.Mock)+ .mockResolvedValueOnce({+ status: 302,+ type: 'basic',+ headers: new Map([['location', 'https://objects.githubusercontent.com/cdn/p.zip']]),+ })+ .mockResolvedValueOnce({ status: 200, type: 'basic' });+ const use = jest.fn(() => 'downloaded');const result = await withSafeFetch('https://github.com/x/releases/download/v1/p.zip', {}, use, {followRedirects: true,});- expect(result).toBe('followed');+ expect(result).toBe('downloaded');expect(use).toHaveBeenCalledTimes(1);- const [, init] = (undiciFetch as jest.Mock).mock.calls[0] as [string, { redirect: string; dispatcher: unknown }];- expect(init.redirect).toBe('follow'); // not 'manual' — undici follows, our lookup guards each hop- expect(init.dispatcher).toBeDefined();+ // Both hops are fetched manually (undici never follows on its own) and each carries a dispatcher.+ const calls = (undiciFetch as jest.Mock).mock.calls as Array<[string, { redirect: string; dispatcher: unknown }]>;+ expect(calls).toHaveLength(2);+ expect(calls[0][0]).toBe('https://github.com/x/releases/download/v1/p.zip');+ expect(calls[1][0]).toBe('https://objects.githubusercontent.com/cdn/p.zip');+ for (const [, init] of calls) {+ expect(init.redirect).toBe('manual');+ expect(init.dispatcher).toBeDefined();+ }});it('still rejects an internal ORIGINAL url even with followRedirects (scheme/host validated first)', async () => {@@ -469,7 +486,7 @@ describe('withSafeFetch (guarded + pinned fetch)', () => {});});-describe('validatingLookup (per-hop redirect guard)', () => {+describe('validatingLookup (standalone validating resolver)', () => {const run = (hostname: string): Promise<{ err: unknown; rest: unknown[] }> =>new Promise(resolve => {const lookup = validatingLookup() as unknown as (@@ -547,3 +564,104 @@ describe('isSsrfProtectionEnabled', () => {expect(isSsrfProtectionEnabled()).toBe(false);});});++// Real-server proof that the followRedirects download path validates EVERY hop. The per-hop guard+// runs resolveSafeFetchTarget on the Location before any socket opens to it, so a 302 whose target+// is a blocked IP literal (which Node never sends through DNS, defeating a connect.lookup guard)+// is refused before connecting.+describe('withSafeFetch followRedirects validates every hop over real sockets', () => {+ const realFetch = jest.requireActual<typeof import('undici')>('undici').fetch;+ let savedAllowedHosts: string | undefined;++ beforeEach(() => {+ // Restore the real fetch so the redirect chain actually connects to the local test servers.+ (undiciFetch as unknown as jest.Mock).mockImplementation(realFetch);+ savedAllowedHosts = process.env.SSRF_ALLOWED_HOSTS;+ process.env.SSRF_ALLOWED_HOSTS = 'localhost'; // the redirector host is reached over an allowed host+ });++ afterEach(() => {+ process.env.SSRF_ALLOWED_HOSTS = savedAllowedHosts;+ (undiciFetch as unknown as jest.Mock).mockReset();+ });++ it('refuses a redirect to a blocked IP literal before opening a socket to it', async () => {+ const internal = createServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'text/plain' });+ res.end('INTERNAL-SECRET-DATA');+ });+ await new Promise<void>(resolve => internal.listen(0, '127.0.0.1', resolve));+ const internalPort = (internal.address() as AddressInfo).port;++ const redirector = createServer((_req, res) => {+ res.writeHead(302, { location: `http://127.0.0.1:${internalPort}/` });+ res.end();+ });+ await new Promise<void>(resolve => redirector.listen(0, '127.0.0.1', resolve));+ const redirectorPort = (redirector.address() as AddressInfo).port;++ try {+ // The redirector is reached over an allowlisted host so the FIRST hop passes; the second hop+ // is a blocked literal and must be refused before any socket is opened to it.+ await expect(+ withSafeFetch(`http://localhost:${redirectorPort}/`, {}, async response => await response.text(), {+ followRedirects: true,+ }),+ ).rejects.toBeInstanceOf(SsrfBlockedError);+ } finally {+ await new Promise<void>(resolve => internal.close(() => resolve()));+ await new Promise<void>(resolve => redirector.close(() => resolve()));+ }+ });++ it('still follows a redirect to an allowed destination', async () => {+ const target = createServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'text/plain' });+ res.end('OK-PAYLOAD');+ });+ await new Promise<void>(resolve => target.listen(0, '127.0.0.1', resolve));+ const targetPort = (target.address() as AddressInfo).port;++ const redirector = createServer((_req, res) => {+ res.writeHead(302, { location: `http://localhost:${targetPort}/` });+ res.end();+ });+ await new Promise<void>(resolve => redirector.listen(0, '127.0.0.1', resolve));+ const redirectorPort = (redirector.address() as AddressInfo).port;++ try {+ const body = await withSafeFetch(+ `http://localhost:${redirectorPort}/`,+ {},+ async response => await response.text(),+ {+ followRedirects: true,+ },+ );+ expect(body).toBe('OK-PAYLOAD');+ } finally {+ await new Promise<void>(resolve => target.close(() => resolve()));+ await new Promise<void>(resolve => redirector.close(() => resolve()));+ }+ });++ it('refuses a redirect chain longer than the hop cap', async () => {+ const server = createServer((_req, res) => {+ const port = (server.address() as AddressInfo).port;+ res.writeHead(302, { location: `http://localhost:${port}/next` });+ res.end();+ });+ await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve));+ const port = (server.address() as AddressInfo).port;++ try {+ await expect(+ withSafeFetch(`http://localhost:${port}/`, {}, async response => await response.text(), {+ followRedirects: true,+ }),+ ).rejects.toBeInstanceOf(SsrfBlockedError);+ } finally {+ await new Promise<void>(resolve => server.close(() => resolve()));+ }+ });+});diff --git a/src/common/security/ssrf-guard.ts b/src/common/security/ssrf-guard.tsindex 546ebc576..d888dd01d 100644--- a/src/common/security/ssrf-guard.ts+++ b/src/common/security/ssrf-guard.ts@@ -231,6 +231,12 @@ function resolveDnsTimeoutMs(): number {return Number.isInteger(n) && n > 0 ? n : DEFAULT_DNS_TIMEOUT_MS;}+/** Redirect hops followed on the guarded download path before the chain is refused. */+const MAX_REDIRECT_HOPS = 5;++/** Status codes undici surfaces as a redirect when `redirect: 'manual'` is set. */+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);+/*** Resolve a host with `{ all: true }`, bounded by a deadline so a hanging/slow DNS resolver cannot* pin a worker indefinitely (the lookup is otherwise unbounded). The default deadline is generous@@ -437,16 +443,33 @@ export async function withSafeFetch<T>(if (opts.followRedirects) {// Download path (plugin .zip / catalog JSON): public release hosts legitimately 302 to a CDN, so- // refusing every redirect breaks them. Follow redirects, but SECURELY — instead of pinning one- // host's IPs, route the connection through a lookup that resolves+validates EVERY host on demand,- // so each hop (original + every redirect target) is checked at connect time and a 3xx to an- // internal host is blocked at the socket. The scheme/host of the original URL is validated first.- await resolveSafeFetchTarget(rawUrl);- const dispatcher = new Agent({ connect: { lookup: validatingLookup() } });- try {- return await useAndSettleBody(await undiciFetch(rawUrl, { ...init, redirect: 'follow', dispatcher }), use);- } finally {- await dispatcher.destroy().catch(() => undefined);+ // refusing every redirect breaks them. Follow them manually and re-validate EVERY hop with+ // resolveSafeFetchTarget, which rejects blocked IP literals directly.+ //+ // Do NOT delegate hop checking to an Agent's `connect.lookup`: Node skips DNS entirely for an+ // IP-literal host, so a custom lookup is never invoked for `Location: http://127.0.0.1/` and the+ // hop goes unchecked. Each hop below is validated BEFORE its socket is opened.+ let currentUrl = rawUrl;+ for (let hop = 0; ; hop++) {+ const target = await resolveSafeFetchTarget(currentUrl);+ const dispatcher = target ? new Agent({ connect: { lookup: pinnedLookup(target) } }) : undefined;+ try {+ const response = await undiciFetch(currentUrl, { ...init, redirect: 'manual', dispatcher });+ if (!REDIRECT_STATUSES.has(response.status)) {+ return await useAndSettleBody(response, use);+ }+ const location = response.headers.get('location');+ await settleUnreadResponseBody(response);+ if (!location) {+ throw new SsrfBlockedError(`Redirect from ${currentUrl} carried no Location header`);+ }+ if (hop >= MAX_REDIRECT_HOPS) {+ throw new SsrfBlockedError(`Too many redirects while fetching ${rawUrl}`);+ }+ currentUrl = new URL(location, currentUrl).toString();+ } finally {+ if (dispatcher) await dispatcher.destroy().catch(() => undefined);+ }}}diff --git a/src/config/swagger.config.spec.ts b/src/config/swagger.config.spec.tsindex 9f973e4c5..b4bab6cd7 100644--- a/src/config/swagger.config.spec.ts+++ b/src/config/swagger.config.spec.ts@@ -99,8 +99,11 @@ describe('PUBLIC_PATHS drift guard', () => {it('every controller using @Public() is accounted for in EXPECTED_PUBLIC_CONTROLLERS', () => {const srcRoot = path.resolve(__dirname, '..').replace(/\\/g, '/');// Match only a line that is exactly `@Public()` — ignores the decorator's doc comment- // (`@example @Public()`) and test/string occurrences.+ // (`@example @Public()`) and test/string occurrences. *.spec.ts files are excluded: a real+ // @Public() decorator only attaches to a controller class, while a spec may legitimately spell+ // the decorator out as a string fixture (e.g. the global-route-fence structural guard).const usingPublic = listTsFiles(srcRoot)+ .filter(f => !f.endsWith('.spec.ts')).filter(f => /^\s*@Public\(\)\s*$/m.test(fs.readFileSync(f, 'utf8'))).map(f => f.replace(/^.*\/src\//, 'src/')).sort();diff --git a/src/modules/auth/global-route-fence-coverage.spec.ts b/src/modules/auth/global-route-fence-coverage.spec.tsnew file mode 100644index 000000000..4594f6e55--- /dev/null+++ b/src/modules/auth/global-route-fence-coverage.spec.ts@@ -0,0 +1,169 @@+// Structural guard for the global-route authorization class of bug.+//+// The ApiKeyGuard resolves the scoped sessionId from ROUTE PARAMS only (api-key.guard.ts), and+// auth.service.ts short-circuits its allowedSessions check when no session id is present. So a route+// with NO session dimension admits a session-restricted key by default — the model is fail-open.+// The fence for those routes is @RequireUnscopedKey (auth.decorators.ts).+//+// This test fails when a controller handler is deployment-global (no :sessionId route param, not on+// a @SessionScoped controller) and carries neither @RequireUnscopedKey, @Public, nor an entry in+// ALLOWLIST below — so a future endpoint cannot silently re-introduce the gap.+import { readdirSync, readFileSync } from 'fs';+import { join } from 'path';++/**+ * Handlers that are deliberately global AND deliberately reachable by a session-restricted key,+ * because they enforce the key's scope themselves in the handler or the service beneath it.+ * Key format: `<controller file basename> :: <handler name>`. Every entry needs a reason.+ */+const ALLOWLIST = new Map<string, string>([+ ['plugins.controller.ts :: updateSessions', 'threads apiKey.allowedSessions into the service'],+ ['audit.controller.ts :: findAll', 'scope-filters rows via resolveSessionScope'],+ ['webhooks-list.controller.ts :: findAll', 'scope-filters rows via the calling key'],+ ['webhooks-list.controller.ts :: deliveryFailures', 'scope-filters rows via the calling key'],+ ['search.controller.ts :: search', 'scope-filters results via the calling key'],+ ['session.controller.ts :: findAll', 'scope-filters sessions to the key allowlist'],+ ['session.controller.ts :: getStats', 'scope-filters the aggregate to apiKey.allowedSessions in the service'],+ // Integration instances live under :pluginId/:instanceId (not a session param), so the guard's+ // route-param fence cannot reach them. Every handler below re-scopes itself against the calling+ // key: reads resolve via sessionScopeVisible (out-of-scope ⇒ 404), writes via assertScopeWritable.+ ['integration-instance.controller.ts :: list', 'filters rows with sessionScopeVisible'],+ ['integration-instance.controller.ts :: getOne', 'resolveVisible() ⇒ 404 outside the key scope'],+ ['integration-instance.controller.ts :: create', 'assertScopeWritable(apiKey, sessionScope) before persisting'],+ ['integration-instance.controller.ts :: regenerate', 'resolveVisible() ⇒ 404 outside the key scope'],+ ['integration-instance.controller.ts :: patch', 'resolveVisible() + assertScopeWritable before any write'],+ ['integration-instance.controller.ts :: remove', 'resolveVisible() ⇒ 404 outside the key scope'],+ ['redrive.controller.ts :: redriveInstance', 'fails closed for scoped keys: missing/out-of-scope instance ⇒ 404'],+ // Self-validation only: the route returns {valid, role} for the calling key and reads/writes no+ // resource, so a session-restricted key validating itself is harmless (it cannot broaden scope).+ ['auth-validate.controller.ts :: validate', 'self-validation of the calling key; no resource access'],+]);++/**+ * Return the names of handlers in `source` that look deployment-global but carry no fence.+ * A handler is considered fenced when it (or its class) has @RequireUnscopedKey or @Public, and+ * session-dimensioned when it declares a `:sessionId` route param or the class is @SessionScoped.+ */+export function handlersMissingGlobalFence(source: string): string[] {+ const beforeClass = source.split('export class')[0] ?? '';+ const classIsSessionScoped = /@SessionScoped\(\)/.test(beforeClass);+ const classIsFenced = /@RequireUnscopedKey\(\)/.test(beforeClass);+ const classIsPublic = /@Public\(\)/.test(beforeClass);+ // A :sessionId in the class-level @Controller(...) prefix (e.g. @Controller('sessions/:sessionId/messages'))+ // gives EVERY handler on the controller a session dimension the guard scopes against — the per-session+ // resource controllers (messages, contacts, groups, …) all use this shape, not a per-handler param.+ const classHasSessionDimension = /@Controller\([^)]*:sessionId/.test(beforeClass);+ if (classIsFenced || classIsPublic || classHasSessionDimension) return [];++ const offenders: string[] = [];+ // Capture each handler's decorator block plus its method name. Decorators are the contiguous run of+ // `@...` lines immediately preceding a 2-space-indented method declaration.+ const handlerRe = /((?:^ {2}@[\s\S]*?)?)^ {2}(?:async\s+)?([a-zA-Z0-9_]+)\s*\(/gm;+ for (let m = handlerRe.exec(source); m !== null; m = handlerRe.exec(source)) {+ const [, decorators, name] = m;+ if (name === 'constructor') continue;+ // Only HTTP handlers matter; a private helper has no route decorator.+ if (!/@(Get|Post|Put|Patch|Delete)\(/.test(decorators)) continue;+ if (/@Public\(\)/.test(decorators)) continue;+ if (/@RequireUnscopedKey\(\)/.test(decorators)) continue;+ // A :sessionId route param gives the guard something to scope against.+ if (/@(Get|Post|Put|Patch|Delete)\([^)]*:sessionId/.test(decorators)) continue;+ // On a @SessionScoped controller the bare `:id` param is a session id, so it is scoped too.+ if (classIsSessionScoped && /@(Get|Post|Put|Patch|Delete)\([^)]*:id/.test(decorators)) continue;+ 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('deployment-global routes are fenced against session-restricted keys', () => {+ // The checker itself must actually detect the gap — a structural guard that cannot fail proves nothing.+ it('flags a global handler with no fence', () => {+ const vulnerable = `+export class ThingController {+ @Get('everything')+ @RequireRole(ApiKeyRole.ADMIN)+ findAll(): string[] {+ return [];+ }+}+`;+ expect(handlersMissingGlobalFence(vulnerable)).toEqual(['findAll']);+ });++ it('clears a handler carrying the fence', () => {+ const fixed = `+export class ThingController {+ @Get('everything')+ @RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()+ findAll(): string[] {+ return [];+ }+}+`;+ expect(handlersMissingGlobalFence(fixed)).toEqual([]);+ });++ it('clears a handler scoped by a :sessionId route param', () => {+ const scoped = `+export class ThingController {+ @Get('sessions/:sessionId/things')+ findForSession(): string[] {+ return [];+ }+}+`;+ expect(handlersMissingGlobalFence(scoped)).toEqual([]);+ });++ it('clears every handler on a class-level fenced controller', () => {+ const fenced = `+@Controller('infra')+@RequireUnscopedKey()+export class InfraController {+ @Get('everything')+ findAll(): string[] {+ return [];+ }+}+`;+ expect(handlersMissingGlobalFence(fenced)).toEqual([]);+ });++ it('clears a public handler', () => {+ const open = `+export class ThingController {+ @Get('health')+ @Public()+ health(): string {+ return 'ok';+ }+}+`;+ expect(handlersMissingGlobalFence(open)).toEqual([]);+ });++ it('no real controller exposes an unfenced deployment-global route', () => {+ const modulesDir = join(__dirname, '..');+ const offenders: string[] = [];+ for (const file of listControllerFiles(modulesDir)) {+ const basename = file.split('/').pop() as string;+ for (const handler of handlersMissingGlobalFence(readFileSync(file, 'utf8'))) {+ const key = `${basename} :: ${handler}`;+ if (ALLOWLIST.has(key)) continue;+ offenders.push(`${file.replace(/.*\/src\//, 'src/')} :: ${handler}`);+ }+ }+ expect(offenders).toEqual([]);+ });+});diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.tsindex 3c7f3dd38..687cdd47f 100644--- a/src/modules/infra/infra.controller.spec.ts+++ b/src/modules/infra/infra.controller.spec.ts@@ -2114,6 +2114,22 @@ describe('InfraController.requestRestart constrains teardown to managed profiles});expect(JSON.stringify(result.removal)).not.toContain('removed');});++ it('starts only allowlisted profiles, never an unknown entry (symmetry with teardown)', async () => {+ const orchestrateProfiles = jest.fn().mockResolvedValue({});+ const controller = buildController({+ isDockerAvailable: () => true,+ stopManagedService: jest.fn().mockResolvedValue(true),+ orchestrateProfiles,+ });++ // A non-managed name must be dropped before reaching orchestrateProfiles, exactly as teardown+ // drops it before reaching stopManagedService — so start cannot select an unrelated container.+ await controller.requestRestart({ profiles: ['postgres', 'not-managed'] });++ expect(orchestrateProfiles).toHaveBeenCalledTimes(1);+ expect(orchestrateProfiles).toHaveBeenCalledWith(['postgres']);+ });});// C002: the infra module exposed sensitive ADMIN operations (credential config write, restart/Dockerdiff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.tsindex 61da4ffeb..ce6a602cf 100644--- a/src/modules/infra/infra.controller.ts+++ b/src/modules/infra/infra.controller.ts@@ -20,7 +20,7 @@ import { QUEUE_NAMES } from '../queue/queue-names';import { ConfigService } from '@nestjs/config';import { DataSource } from 'typeorm';import { InjectDataSource } from '@nestjs/typeorm';-import { Public, RequireRole } from '../auth/decorators/auth.decorators';+import { Public, RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import { isPathWithin, isSafeSessionName } from '../../common/utils/path-safety';import { writeSecretFile } from '../../common/utils/secret-file';@@ -337,6 +337,11 @@ interface SavedConfigResponse {@ApiTags('infrastructure')@Controller('infra')+// Every route here is deployment-global (data export/import, infra config, service orchestration),+// so the guard's route-param session fence can never bite. Reject session-scoped keys outright at+// class level, which also covers routes added later. @Public routes are unaffected: the guard+// returns before it reads this metadata.+@RequireUnscopedKey()export class InfraController implements OnApplicationBootstrap {private readonly logger = createLogger('InfraController');@@ -1054,10 +1059,19 @@ export class InfraController implements OnApplicationBootstrap {this.logger.log('Teardown result', { removalResult });}- // Then, start containers for enabled services- if (profiles.length > 0) {+ // Then, start containers for enabled services. Start shares the SAME managed allowlist as+ // teardown above: a non-managed name reaching orchestrateProfiles could, via container-name+ // matching, select an unrelated host container, so constrain start to the managed profiles too+ // and drop anything else. (DockerService already hard-prefixes openwa-<service> and filters on+ // the com.openwa.service label, so this is defense-in-depth, not the sole control.)+ const toStart = profiles.filter(p => MANAGED_DOCKER_PROFILES.includes(p));+ const ignoredStart = profiles.filter(p => !MANAGED_DOCKER_PROFILES.includes(p));+ if (ignoredStart.length > 0) {+ this.logger.warn('Ignoring non-managed profiles in profiles', { ignoredStart });+ }+ if (toStart.length > 0) {this.logger.log('Orchestrating enabled profiles...');- orchestrationResult = await this.dockerService.orchestrateProfiles(profiles);+ orchestrationResult = await this.dockerService.orchestrateProfiles(toStart);this.logger.log('Orchestration result', { orchestrationResult });}} else {diff --git a/src/modules/integration/redrive.controller.spec.ts b/src/modules/integration/redrive.controller.spec.tsindex eff81115f..6dfac2c41 100644--- a/src/modules/integration/redrive.controller.spec.ts+++ b/src/modules/integration/redrive.controller.spec.ts@@ -22,7 +22,7 @@ describe('RedriveController authz', () => {describe('RedriveController session-scope fence', () => {const scopedKey = { allowedSessions: ['sess-1'] } as ApiKey;- function build(sessionScope: string | null) {+ function build(sessionScope: string | null | undefined) {const redrive = { redriveInstance: jest.fn().mockResolvedValue({ redriven: 0, remaining: 0, batchSize: 100 }) };const instances = {resolve: jest@@ -55,6 +55,24 @@ describe('RedriveController session-scope fence', () => {expect(redrive.redriveInstance).not.toHaveBeenCalled();});+ it('answers 404 when a scoped key redrives a missing instance (its retained DLQ rows still carry a sessionId that may be out of scope)', async () => {+ // build(undefined) makes resolve() return null (the instance row is gone). The old guard's+ // `inst && ...` short-circuit let a scoped key through to redriveInstance here, re-dispatching+ // the deleted instance's retained DLQ rows unscoped. It must fail closed instead.+ const { controller, redrive } = build(undefined);++ await expect(controller.redriveInstance('chatwoot', 'acct1', scopedKey)).rejects.toThrow(NotFoundException);+ expect(redrive.redriveInstance).not.toHaveBeenCalled();+ });++ it('lets an unrestricted key redrive a missing instance (drains retained DLQ rows for cleanup)', async () => {+ const { controller, redrive } = build(undefined);++ await controller.redriveInstance('chatwoot', 'acct1', { allowedSessions: null } as unknown as ApiKey);++ expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1');+ });+it('answers 404 when a scoped key redrives an all-sessions (null scope) instance', async () => {const { controller, redrive } = build(null);diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.tsindex 11eebd3e0..3f8a87151 100644--- a/src/modules/integration/redrive.controller.ts+++ b/src/modules/integration/redrive.controller.ts@@ -33,8 +33,11 @@ export class RedriveController {): Promise<{ redriven: number; remaining: number; batchSize: number }> {// Session-scoped keys may only redrive instances bound inside their own fence; an out-of-scope// instance answers 404 (same as a missing one) so redrive can't be used to probe other sessions.+ // A MISSING instance row is refused too: its retained DLQ rows still carry the deleted instance's+ // sessionId and would be re-dispatched unscoped. Only an unrestricted key may drain those.const inst = await this.instances.resolve(pluginId, instanceId);- if (inst && !sessionScopeVisible(apiKey?.allowedSessions, inst.sessionScope)) {+ const scoped = (apiKey?.allowedSessions?.length ?? 0) > 0;+ if (scoped && (!inst || !sessionScopeVisible(apiKey?.allowedSessions, inst.sessionScope))) {throw new NotFoundException('instance not found');}const result = await this.redrive.redriveInstance(pluginId, instanceId);diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex 11b278932..29000f9ce 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -17,7 +17,7 @@ import { ApiTags, ApiOperation, ApiResponse, ApiConsumes } from '@nestjs/swaggerimport { PluginsService } from './plugins.service';import { PluginDto, PluginConfigDto, PluginSessionsDto, InstallFromUrlDto } from './dto/plugin.dto';import type { CatalogPlugin } from './catalog';-import { RequireRole, CurrentApiKey } from '../auth/decorators/auth.decorators';+import { RequireRole, CurrentApiKey, RequireUnscopedKey } from '../auth/decorators/auth.decorators';import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';/** Max accepted upload size for a plugin package (compressed). */@@ -25,11 +25,17 @@ const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024;@ApiTags('plugins')@Controller('plugins')+// Plugin installation and lifecycle are deployment-global and execute plugin code as the OpenWA+// process user, so session-restricted keys are fenced off route by route below. The fence is NOT+// applied at class level because @RequireUnscopedKey takes no argument and cannot be opted out of:+// `updateSessions` enforces the key's allowedSessions itself, and `updateSessionConfig` is already+// covered by the guard through its own :sessionId route param.export class PluginsController {constructor(private readonly pluginsService: PluginsService) {}@Get()@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'List all plugins' })@ApiResponse({ status: 200, description: 'List of all plugins' })findAll(): PluginDto[] {@@ -38,6 +44,7 @@ export class PluginsController {@Post('install')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_PLUGIN_UPLOAD_BYTES } }))@ApiConsumes('multipart/form-data')@ApiOperation({ summary: 'Install a plugin from an uploaded .zip package' })@@ -50,6 +57,7 @@ export class PluginsController {@Post('install-url')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Install a plugin by downloading its .zip from a URL (SSRF-guarded)' })@ApiResponse({ status: 201, description: 'Plugin installed' })@ApiResponse({ status: 400, description: 'Invalid URL, download failed, or invalid package' })@@ -61,6 +69,7 @@ export class PluginsController {// Declared before `:id` so `GET /plugins/catalog` is not captured by the `:id` route.@Get('catalog')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'List the remote plugin catalog, annotated with install state' })@ApiResponse({ status: 200, description: 'Catalog entries' })@ApiResponse({ status: 400, description: 'Catalog could not be fetched or parsed' })@@ -70,6 +79,7 @@ export class PluginsController {@Get(':id')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Get plugin by ID' })@ApiResponse({ status: 200, description: 'Plugin details' })@ApiResponse({ status: 404, description: 'Plugin not found' })@@ -79,6 +89,7 @@ export class PluginsController {@Post(':id/enable')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Enable a plugin' })@ApiResponse({ status: 200, description: 'Plugin enabled successfully' })@@ -88,6 +99,7 @@ export class PluginsController {@Post(':id/disable')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@HttpCode(HttpStatus.OK)@ApiOperation({ summary: 'Disable a plugin' })@ApiResponse({ status: 200, description: 'Plugin disabled successfully' })@@ -97,6 +109,7 @@ export class PluginsController {@Put(':id/config')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Update plugin configuration' })@ApiResponse({ status: 200, description: 'Plugin configuration updated' })updateConfig(@Param('id') id: string, @Body() configDto: PluginConfigDto): { success: boolean; message: string } {@@ -108,6 +121,7 @@ export class PluginsController {// inherited CSP allows only the isolated editor bootstrap, without enabling parent unsafe-inline.@Get(':id/config-ui')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@Header('Content-Type', 'text/html; charset=utf-8')@Header('Content-Security-Policy', 'sandbox')@Header('X-Content-Type-Options', 'nosniff')@@ -146,6 +160,7 @@ export class PluginsController {@Post(':id/update')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Update an installed plugin in place from a URL (preserves config + enabled state)' })@ApiResponse({ status: 201, description: 'Plugin updated' })@ApiResponse({ status: 400, description: 'Invalid URL/package, id mismatch, or built-in' })@@ -156,6 +171,7 @@ export class PluginsController {@Delete(':id')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Uninstall a plugin (removes its files; built-ins are protected)' })@ApiResponse({ status: 200, description: 'Plugin uninstalled' })@ApiResponse({ status: 400, description: 'Cannot uninstall (e.g. built-in)' })@@ -166,6 +182,7 @@ export class PluginsController {@Get(':id/health')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Check plugin health' })@ApiResponse({ status: 200, description: 'Plugin health status' })async healthCheck(@Param('id') id: string): Promise<{ healthy: boolean; message?: string }> {diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex ef057dbd2..bc08a6da6 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -16,7 +16,7 @@ import { Session } from './entities/session.entity';import { ChatSummary } from '../../engine/interfaces/whatsapp-engine.interface';import { AuditService } from '../audit/audit.service';import { AuditAction } from '../audit/entities/audit-log.entity';-import { RequireRole, CurrentApiKey, SessionScoped } from '../auth/decorators/auth.decorators';+import { RequireRole, CurrentApiKey, SessionScoped, RequireUnscopedKey } from '../auth/decorators/auth.decorators';import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';@ApiTags('sessions')@@ -36,6 +36,10 @@ export class SessionController {@Post()@RequireRole(ApiKeyRole.OPERATOR)+ // Creating a session has no existing session id for the class-level @SessionScoped fence to check,+ // and the new session is outside the caller's allowlist by construction — so a key restricted to+ // specific sessions cannot create one. Different metadata key from @SessionScoped; they coexist.+ @RequireUnscopedKey()@ApiOperation({ summary: 'Create a new WhatsApp session' })@ApiResponse({status: 201,diff --git a/src/modules/settings/settings.controller.ts b/src/modules/settings/settings.controller.tsindex 0baba0b5d..86e6a9884 100644--- a/src/modules/settings/settings.controller.ts+++ b/src/modules/settings/settings.controller.ts@@ -1,7 +1,7 @@import { Controller, Get, Put, NotImplementedException } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { ConfigService } from '@nestjs/config';-import { RequireRole } from '../auth/decorators/auth.decorators';+import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';import { isSwaggerEnabled } from '../../config/bootstrap-security';@@ -60,17 +60,20 @@ export class SettingsController {@Get()@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Get application settings' })@ApiResponse({ status: 200, description: 'Current settings' })get(): Settings {// Settings expose environment-derived configuration (debug flag, reconnect policy, rate-limit- // thresholds, base URL). Gate the read at ADMIN, matching the PUT below and the rest of the- // admin-config surface — a VIEWER or session-scoped key has no business reading server config.+ // thresholds, base URL) that describes the deployment rather than any one session. Gate the read+ // at ADMIN and require an unrestricted key: the role check alone does not exclude a key confined+ // to specific sessions, which has no claim on deployment-wide configuration.return this.settings;}@Put()@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Settings are read-only at runtime (environment-derived)' })@ApiResponse({status: 501,diff --git a/src/modules/stats/stats.controller.ts b/src/modules/stats/stats.controller.tsindex 68a83df0e..7aa0a943f 100644--- a/src/modules/stats/stats.controller.ts+++ b/src/modules/stats/stats.controller.ts@@ -2,7 +2,7 @@ import { Controller, Get, Param, Query } from '@nestjs/common';import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import { StatsService } from './stats.service';import { StatsQueryDto } from './dto/stats-query.dto';-import { RequireRole } from '../auth/decorators/auth.decorators';+import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';@ApiTags('statistics')@@ -10,10 +10,12 @@ import { ApiKeyRole } from '../auth/entities/api-key.entity';export class StatsController {constructor(private readonly statsService: StatsService) {}- // Global, cross-session aggregates with no scope param — ADMIN-only so a VIEWER / session-- // restricted key can't read cross-tenant activity. (Per-session stats below stays scope-gated.)+ // Global, cross-session aggregates with no scope param. The ADMIN role gate alone does not keep a+ // session-restricted key out — role and session scope are independent — so these also require an+ // unrestricted key. (Per-session stats below stays scope-gated by its :sessionId route param.)@Get('overview')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Get overall statistics' })@ApiResponse({ status: 200, description: 'Cross-session aggregate statistics (sessions, messages, etc.).' })async getOverview() {@@ -22,6 +24,7 @@ export class StatsController {@Get('messages')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: 'Get message statistics with time series' })@ApiResponse({ status: 200, description: 'Message statistics with a time series for the requested period.' })async getMessageStats(@Query() query: StatsQueryDto) {diff --git a/test/global-routes-session-scope.e2e-spec.ts b/test/global-routes-session-scope.e2e-spec.tsnew file mode 100644index 000000000..1848280b2--- /dev/null+++ b/test/global-routes-session-scope.e2e-spec.ts@@ -0,0 +1,96 @@+// 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';++/**+ * Cross-session aggregates, environment-derived settings, and session creation all act outside any+ * single session, so the guard's route-param fence cannot scope them. A key restricted to specific+ * sessions must not read deployment-wide activity, read server configuration, or create sessions+ * outside its own allowlist.+ */+describe('Global read and create routes reject session-scoped keys (e2e)', () => {+ let app: INestApplication<App>;+ let scopedAdminKey: string; // ADMIN, allowedSessions: [sessA]+ let scopedOperatorKey: string; // OPERATOR, 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 a = await sessionRepo.save(sessionRepo.create({ name: `e2e-global-scope-${Date.now()}` }));++ const authService = app.get(AuthService);+ scopedAdminKey = (+ await authService.createApiKey({ name: 'e2e-global-scoped', role: ApiKeyRole.ADMIN, allowedSessions: [a.id] })+ ).rawKey;+ scopedOperatorKey = (+ await authService.createApiKey({ name: 'e2e-global-op', role: ApiKeyRole.OPERATOR, allowedSessions: [a.id] })+ ).rawKey;+ adminKey = (await authService.createApiKey({ name: 'e2e-global-admin', role: ApiKeyRole.ADMIN })).rawKey;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ it('rejects a scoped ADMIN on GET /api/stats/overview', async () => {+ await request(app.getHttpServer()).get('/api/stats/overview').set('X-API-Key', scopedAdminKey).expect(403);+ });++ it('rejects a scoped ADMIN on GET /api/stats/messages', async () => {+ await request(app.getHttpServer()).get('/api/stats/messages').set('X-API-Key', scopedAdminKey).expect(403);+ });++ it('rejects a scoped ADMIN on GET /api/settings', async () => {+ await request(app.getHttpServer()).get('/api/settings').set('X-API-Key', scopedAdminKey).expect(403);+ });++ it('rejects a scoped ADMIN on POST /api/sessions', async () => {+ await request(app.getHttpServer())+ .post('/api/sessions')+ .set('X-API-Key', scopedAdminKey)+ .send({ name: `e2e-escape-admin-${Date.now()}` })+ .expect(403);+ });++ it('rejects a scoped OPERATOR on POST /api/sessions (cannot create outside its allowlist)', async () => {+ await request(app.getHttpServer())+ .post('/api/sessions')+ .set('X-API-Key', scopedOperatorKey)+ .send({ name: `e2e-escape-operator-${Date.now()}` })+ .expect(403);+ });++ it('leaves per-session stats reachable for an in-scope session', async () => {+ // Sanity: the fence must not spill onto the session-scoped route next door.+ const res = await request(app.getHttpServer()).get('/api/stats/overview').set('X-API-Key', adminKey);+ expect(res.status).toBe(200);+ });++ it('leaves an unrestricted ADMIN able to create a session', async () => {+ await request(app.getHttpServer())+ .post('/api/sessions')+ .set('X-API-Key', adminKey)+ .send({ name: `e2e-global-ok-${Date.now()}` })+ .expect(201);+ });+});diff --git a/test/infra-session-scope.e2e-spec.ts b/test/infra-session-scope.e2e-spec.tsnew file mode 100644index 000000000..7b566d5ff--- /dev/null+++ b/test/infra-session-scope.e2e-spec.ts@@ -0,0 +1,74 @@+// 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';++/**+ * The infrastructure routes carry no session dimension, so the ApiKeyGuard's route-param fence can+ * never bite on them: a session-restricted ADMIN key would otherwise export or replace the whole+ * deployment database, rewrite global engine configuration, or stop deployment services. They must+ * reject scoped keys outright, while leaving unrestricted ADMIN keys fully functional.+ */+describe('Infrastructure routes reject session-scoped keys (e2e)', () => {+ let app: INestApplication<App>;+ 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 sessA = await sessionRepo.save(sessionRepo.create({ name: `e2e-infra-scope-${Date.now()}` }));++ const authService = app.get(AuthService);+ scopedKey = (+ await authService.createApiKey({ name: 'e2e-infra-scoped', role: ApiKeyRole.ADMIN, allowedSessions: [sessA.id] })+ ).rawKey;+ adminKey = (await authService.createApiKey({ name: 'e2e-infra-admin', role: ApiKeyRole.ADMIN })).rawKey;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ it('rejects a scoped ADMIN on GET /api/infra/export-data', async () => {+ await request(app.getHttpServer()).get('/api/infra/export-data').set('X-API-Key', scopedKey).expect(403);+ });++ it('rejects a scoped ADMIN on POST /api/infra/import-data', async () => {+ await request(app.getHttpServer())+ .post('/api/infra/import-data')+ .set('X-API-Key', scopedKey)+ .send({ tables: {} })+ .expect(403);+ });++ it('rejects a scoped ADMIN on GET /api/infra/config', async () => {+ await request(app.getHttpServer()).get('/api/infra/config').set('X-API-Key', scopedKey).expect(403);+ });++ it('leaves the public health route reachable without a key', async () => {+ await request(app.getHttpServer()).get('/api/infra/health').expect(200);+ });++ it('leaves an unrestricted ADMIN able to read the export', async () => {+ await request(app.getHttpServer()).get('/api/infra/export-data').set('X-API-Key', adminKey).expect(200);+ });+});diff --git a/test/plugins-session-scope.e2e-spec.ts b/test/plugins-session-scope.e2e-spec.tsnew file mode 100644index 000000000..3522bce33--- /dev/null+++ b/test/plugins-session-scope.e2e-spec.ts@@ -0,0 +1,128 @@+// 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';++/**+ * Plugin install/lifecycle routes are deployment-global and their sink is code execution as the+ * OpenWA process user, so a session-restricted key must not reach them. The two session-aware+ * routes (per-session activation and per-session config) must keep working for a scoped key —+ * they enforce scope themselves and are the reason this fence is per-route, not class-level.+ */+describe('Plugin routes reject session-scoped keys (e2e)', () => {+ let app: INestApplication<App>;+ let scopedKey: string; // ADMIN, allowedSessions: [sessA]+ let adminKey: string; // ADMIN, unrestricted+ let sessA: string;++ 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 a = await sessionRepo.save(sessionRepo.create({ name: `e2e-plugin-scope-${Date.now()}` }));+ sessA = a.id;++ const authService = app.get(AuthService);+ scopedKey = (+ await authService.createApiKey({ name: 'e2e-plugin-scoped', role: ApiKeyRole.ADMIN, allowedSessions: [sessA] })+ ).rawKey;+ adminKey = (await authService.createApiKey({ name: 'e2e-plugin-admin', role: ApiKeyRole.ADMIN })).rawKey;+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ describe('fenced routes', () => {+ it('rejects a scoped ADMIN on GET /api/plugins (cannot enumerate deployment plugins)', async () => {+ await request(app.getHttpServer()).get('/api/plugins').set('X-API-Key', scopedKey).expect(403);+ });++ it('rejects a scoped ADMIN on POST /api/plugins/install-url (cannot install remote code)', async () => {+ await request(app.getHttpServer())+ .post('/api/plugins/install-url')+ .set('X-API-Key', scopedKey)+ .send({ url: 'https://example.invalid/plugin.zip' })+ .expect(403);+ });++ it('rejects a scoped ADMIN on GET /api/plugins/catalog', async () => {+ await request(app.getHttpServer()).get('/api/plugins/catalog').set('X-API-Key', scopedKey).expect(403);+ });++ it('rejects a scoped ADMIN on POST /api/plugins/:id/enable', async () => {+ await request(app.getHttpServer()).post('/api/plugins/any-plugin/enable').set('X-API-Key', scopedKey).expect(403);+ });++ it('rejects a scoped ADMIN on POST /api/plugins/:id/disable', async () => {+ await request(app.getHttpServer())+ .post('/api/plugins/any-plugin/disable')+ .set('X-API-Key', scopedKey)+ .expect(403);+ });++ it('rejects a scoped ADMIN on PUT /api/plugins/:id/config', async () => {+ await request(app.getHttpServer())+ .put('/api/plugins/any-plugin/config')+ .set('X-API-Key', scopedKey)+ .send({ config: {} })+ .expect(403);+ });++ it('rejects a scoped ADMIN on POST /api/plugins/:id/update', async () => {+ await request(app.getHttpServer())+ .post('/api/plugins/any-plugin/update')+ .set('X-API-Key', scopedKey)+ .send({ url: 'https://example.invalid/plugin.zip' })+ .expect(403);+ });++ it('rejects a scoped ADMIN on DELETE /api/plugins/:id', async () => {+ await request(app.getHttpServer()).delete('/api/plugins/any-plugin').set('X-API-Key', scopedKey).expect(403);+ });+ });++ /**+ * Regression guard for the deliberate carve-out. These two routes enforce the key's scope+ * themselves; fencing them would break session-scoped plugin administration. They must NOT+ * return 403 for a scoped key — a 404 (plugin does not exist) proves the request passed the guard.+ */+ describe('deliberate carve-outs stay reachable for a scoped key', () => {+ it('does not 403 a scoped ADMIN on PUT /api/plugins/:id/sessions', async () => {+ const res = await request(app.getHttpServer())+ .put('/api/plugins/any-plugin/sessions')+ .set('X-API-Key', scopedKey)+ .send({ sessions: [sessA] });+ expect(res.status).not.toBe(403);+ });++ it('does not 403 a scoped ADMIN on PUT /api/plugins/:id/config/:sessionId for an in-scope session', async () => {+ const res = await request(app.getHttpServer())+ .put(`/api/plugins/any-plugin/config/${sessA}`)+ .set('X-API-Key', scopedKey)+ .send({ config: {} });+ expect(res.status).not.toBe(403);+ });+ });++ it('leaves an unrestricted ADMIN able to list plugins', async () => {+ await request(app.getHttpServer()).get('/api/plugins').set('X-API-Key', adminKey).expect(200);+ });+});