Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): require unrestricted key for plugin session replacement
Yudhi Armyndharisaa8171b8d819
diff --git a/src/common/security/session-scope.ts b/src/common/security/session-scope.tsindex c03327f22..364577aa4 100644--- a/src/common/security/session-scope.ts+++ b/src/common/security/session-scope.ts@@ -28,7 +28,8 @@ export function resolveSessionScope(* sees every scope; a scoped key only sees resources bound to one of its own sessions, so a null* scope (and the '*' wildcard) is never inside its fence. Use this on surfaces whose session* binding travels in the request body or in persisted rows, which the ApiKeyGuard's route-param- * fence cannot reach (mirrors how plugins.controller threads allowedSessions into its service).+ * fence cannot reach (the same body/persisted-scope pattern the integration-instance controller+ * uses to confine a scoped key to instances bound inside its allowedSessions).*/export function sessionScopeVisible(allowedSessions: string[] | null | undefined,diff --git a/src/modules/auth/global-route-fence-coverage.spec.ts b/src/modules/auth/global-route-fence-coverage.spec.tsindex 5c201e2f5..11a7a8bf5 100644--- a/src/modules/auth/global-route-fence-coverage.spec.ts+++ b/src/modules/auth/global-route-fence-coverage.spec.ts@@ -17,7 +17,6 @@ import { join } from 'path';* 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'],diff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.tsindex 1da6272f3..1977f561e 100644--- a/src/modules/integration/integration-instance.controller.spec.ts+++ b/src/modules/integration/integration-instance.controller.spec.ts@@ -410,7 +410,8 @@ describe('IntegrationInstanceController provisioning bridge', () => {// sessionScope travels in the request body, which the ApiKeyGuard's route-param fence never sees —// so the controller itself confines a session-scoped key to instances bound inside its-// allowedSessions (the same pattern plugins.controller uses for updateSessions).+// allowedSessions (the body-scoping pattern; the plugin updateSessions route is NOT scoped this way+// — it is a full active-set replacement and is fenced with @RequireUnscopedKey).describe('IntegrationInstanceController session-scope fence', () => {const scopedKey = { allowedSessions: ['sess-1'] } as ApiKey;const unrestrictedKey = { allowedSessions: null } as unknown as ApiKey;diff --git a/src/modules/plugins/plugins.controller.spec.ts b/src/modules/plugins/plugins.controller.spec.tsindex ffb1bf6ae..2bb5d6111 100644--- a/src/modules/plugins/plugins.controller.spec.ts+++ b/src/modules/plugins/plugins.controller.spec.ts@@ -1,6 +1,6 @@import { Reflector } from '@nestjs/core';import { PluginsController } from './plugins.controller';-import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';+import { REQUIRED_ROLE_KEY, UNSCOPED_KEY } from '../auth/decorators/auth.decorators';import { ApiKeyRole } from '../auth/entities/api-key.entity';describe('PluginsController authorization', () => {@@ -18,6 +18,7 @@ describe('PluginsController authorization', () => {'updateConfig','getConfigUi','updateSessionConfig',+ 'updateSessions',] as const;it.each(adminOnly)('%s requires the ADMIN role', method => {@@ -27,4 +28,10 @@ describe('PluginsController authorization', () => {const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);expect(role).toBe(ApiKeyRole.ADMIN);});++ it('updateSessions requires an unrestricted key because updateSessions replaces the complete active set', () => {+ // eslint-disable-next-line @typescript-eslint/unbound-method+ const handler = PluginsController.prototype.updateSessions;+ expect(reflector.get<boolean>(UNSCOPED_KEY, handler)).toBe(true);+ });});diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex 29000f9ce..3ec8d2440 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -17,8 +17,8 @@ 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, RequireUnscopedKey } from '../auth/decorators/auth.decorators';-import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';+import { RequireRole, RequireUnscopedKey } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';/** Max accepted upload size for a plugin package (compressed). */const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024;@@ -28,8 +28,9 @@ const MAX_PLUGIN_UPLOAD_BYTES = 5 * 1024 * 1024;// 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.+// `updateSessions` is fenced too (it overwrites the ENTIRE active set, so a scoped key could delete+// another tenant's activation by sending its own session or []), and `updateSessionConfig` is+// already covered by the guard through its own :sessionId route param.export class PluginsController {constructor(private readonly pluginsService: PluginsService) {}@@ -148,14 +149,21 @@ export class PluginsController {@Put(':id/sessions')@RequireRole(ApiKeyRole.ADMIN)+ @RequireUnscopedKey()@ApiOperation({ summary: "Set which sessions a session-scoped plugin is activated for (['*'] = all)" })@ApiResponse({ status: 200, description: 'Plugin session activation updated', type: PluginDto })@ApiResponse({ status: 400, description: 'Plugin is global (not session-scoped)' })+ @ApiResponse({+ status: 403,+ description:+ 'A session-restricted key may not replace the full active set — full activation replacement requires an unrestricted key',+ })@ApiResponse({ status: 404, description: 'Plugin not found' })- updateSessions(@Param('id') id: string, @Body() dto: PluginSessionsDto, @CurrentApiKey() apiKey?: ApiKey): PluginDto {- // The target sessions live in the body, which the ApiKeyGuard (keyed off route params) never- // inspects — so a session-restricted key's allowedSessions scope must be enforced here.- return this.pluginsService.updateSessions(id, dto.sessions, apiKey?.allowedSessions);+ updateSessions(@Param('id') id: string, @Body() dto: PluginSessionsDto): PluginDto {+ // This is a full-replacement PUT (setPluginSessions overwrites the entire activeSessions array),+ // so a scoped key must never reach it: sending [] or its own session would delete every other+ // tenant's activation. The @RequireUnscopedKey fence above enforces that before the handler runs.+ return this.pluginsService.updateSessions(id, dto.sessions);}@Post(':id/update')diff --git a/src/modules/plugins/plugins.service.spec.ts b/src/modules/plugins/plugins.service.spec.tsindex f97fd9314..5edbd4782 100644--- a/src/modules/plugins/plugins.service.spec.ts+++ b/src/modules/plugins/plugins.service.spec.ts@@ -489,20 +489,17 @@ describe('PluginsService — per-session config', () => {expect(plugin?.sessionConfig?.['sess-A']).toEqual({ apiKey: 'A-secret', lang: 'he' });});- // A session-restricted API key must not activate the plugin for sessions outside its allowedSessions- // scope (the target sessions are in the request body the guard never inspects).- it('rejects activating for a session outside a restricted key scope', () => {- expect(() => service.updateSessions('sess-cfg', ['sess-B'], ['sess-A'])).toThrow(/not authorized/i);- expect(() => service.updateSessions('sess-cfg', ['*'], ['sess-A'])).toThrow(/not authorized/i);- });-- it('allows a restricted key to activate only within its scope', () => {- expect(service.updateSessions('sess-cfg', ['sess-A'], ['sess-A']).activeSessions).toEqual(['sess-A']);+ // The route is fenced with @RequireUnscopedKey, so the service signature no longer carries a+ // scope argument. updateSessions is a FULL replacement: each write overwrites the entire active+ // set, so the exact array survives each call (setPluginSessions assigns plugin.activeSessions).+ it('fully replaces the active set on each write (single, wildcard, then cleared)', () => {+ expect(service.updateSessions('sess-cfg', ['sess-A']).activeSessions).toEqual(['sess-A']);+ expect(service.updateSessions('sess-cfg', ['*']).activeSessions).toEqual(['*']);+ expect(service.updateSessions('sess-cfg', []).activeSessions).toEqual([]);});it('lets an unrestricted key activate for all sessions', () => {- expect(service.updateSessions('sess-cfg', ['*'], undefined).activeSessions).toEqual(['*']);- expect(service.updateSessions('sess-cfg', ['*'], []).activeSessions).toEqual(['*']);+ expect(service.updateSessions('sess-cfg', ['*']).activeSessions).toEqual(['*']);});it('clears the override when an empty slice is written', () => {diff --git a/src/modules/plugins/plugins.service.ts b/src/modules/plugins/plugins.service.tsindex 9ab3cf5c2..1f15ff50f 100644--- a/src/modules/plugins/plugins.service.ts+++ b/src/modules/plugins/plugins.service.ts@@ -1,11 +1,4 @@-import {- Injectable,- NotFoundException,- BadRequestException,- ConflictException,- ForbiddenException,- HttpException,-} from '@nestjs/common';+import { Injectable, NotFoundException, BadRequestException, ConflictException, HttpException } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import * as fs from 'fs';import * as path from 'path';@@ -180,20 +173,14 @@ export class PluginsService {}}- updateSessions(id: string, sessions: string[], allowedSessions?: string[] | null): PluginDto {+ updateSessions(id: string, sessions: string[]): PluginDto {const plugin = this.pluginLoader.getPlugin(id);if (!plugin) {throw new NotFoundException(`Plugin ${id} not found`);}- // A session-restricted key (non-empty allowedSessions) may only activate the plugin for sessions- // in its own scope — never '*' (all) or another tenant's session. An unrestricted key (null/empty)- // is the normal dashboard/admin path and may activate for any session, including '*'.- if (allowedSessions && allowedSessions.length > 0) {- const outOfScope = sessions.filter(s => s === '*' || !allowedSessions.includes(s));- if (outOfScope.length > 0) {- throw new ForbiddenException(`API key not authorized for session(s): ${outOfScope.join(', ')}`);- }- }+ // Full-replacement PUT: setPluginSessions overwrites the ENTIRE activeSessions array. The route+ // is fenced with @RequireUnscopedKey, so only an unrestricted key can reach this — a scoped key+ // must never be allowed to delete another tenant's activation by sending [] or its own session.try {this.pluginLoader.setPluginSessions(id, sessions);} catch (error) {diff --git a/test/plugins-session-scope.e2e-spec.ts b/test/plugins-session-scope.e2e-spec.tsindex 3522bce33..119acbe54 100644--- a/test/plugins-session-scope.e2e-spec.ts+++ b/test/plugins-session-scope.e2e-spec.ts@@ -15,9 +15,12 @@ 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.+ * OpenWA process user, so a session-restricted key must not reach them. The full session+ * activation replacement (PUT /:id/sessions) is fenced too: it overwrites the ENTIRE active set,+ * so a scoped key could otherwise delete another tenant's activation by sending [] or its own+ * session. The per-session config route (PUT /:id/config/:sessionId) stays reachable for a scoped+ * key — the guard scopes against its :sessionId route param, so it is the only session-dimensioned+ * plugin route and the reason this fence is per-route, not class-level.*/describe('Plugin routes reject session-scoped keys (e2e)', () => {let app: INestApplication<App>;@@ -94,25 +97,27 @@ describe('Plugin routes reject session-scoped keys (e2e)', () => {.expect(403);});+ it('rejects a scoped ADMIN on PUT /api/plugins/:id/sessions (full replacement can delete other tenants)', async () => {+ await request(app.getHttpServer())+ .put('/api/plugins/any-plugin/sessions')+ .set('X-API-Key', scopedKey)+ .send({ sessions: [sessA] })+ .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.+ * Regression guard for the deliberate carve-out. The per-session config route is the only+ * session-dimensioned plugin route: the guard scopes against its :sessionId param, so a scoped+ * key must still reach the handler (a 404 for the absent fixture plugin proves it passed the guard).+ * The full session-replacement route is NOT here — it overwrites the whole active set and now+ * carries @RequireUnscopedKey (see fenced routes above).*/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}`)@@ -122,6 +127,14 @@ describe('Plugin routes reject session-scoped keys (e2e)', () => {});});+ it('lets an unrestricted ADMIN reach the PUT /api/plugins/:id/sessions handler (404 for an absent plugin)', async () => {+ await request(app.getHttpServer())+ .put('/api/plugins/any-plugin/sessions')+ .set('X-API-Key', adminKey)+ .send({ sessions: [sessA] })+ .expect(404);+ });+it('leaves an unrestricted ADMIN able to list plugins', async () => {await request(app.getHttpServer()).get('/api/plugins').set('X-API-Key', adminKey).expect(200);});