Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth,integration): confine session-scoped keys on key-management and instance surfaces (#916)
Yudhi Armyndharis4a5412eedc81
diff --git a/src/common/security/session-scope.spec.ts b/src/common/security/session-scope.spec.tsindex afc380c46..16d6572f6 100644--- a/src/common/security/session-scope.spec.ts+++ b/src/common/security/session-scope.spec.ts@@ -1,4 +1,4 @@-import { resolveSessionScope } from './session-scope';+import { resolveSessionScope, sessionScopeVisible } 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".@@ -26,3 +26,26 @@ describe('resolveSessionScope', () => {expect(resolveSessionScope(['A', 'B'], 'C')).toEqual([]);});});++// sessionScopeVisible fences resources whose session binding travels in a body field or a persisted+// row (plugin instances), which the guard's route-param fence cannot reach. null/'*' = all sessions.+describe('sessionScopeVisible', () => {+ it('unrestricted key (null/empty/undefined allowlist) sees every scope', () => {+ expect(sessionScopeVisible(null, 'A')).toBe(true);+ expect(sessionScopeVisible([], 'A')).toBe(true);+ expect(sessionScopeVisible(undefined, null)).toBe(true);+ expect(sessionScopeVisible(null, null)).toBe(true);+ expect(sessionScopeVisible(null, '*')).toBe(true);+ });++ it('scoped key sees resources bound to one of its own sessions only', () => {+ expect(sessionScopeVisible(['A', 'B'], 'A')).toBe(true);+ expect(sessionScopeVisible(['A', 'B'], 'C')).toBe(false);+ });++ it('scoped key never sees the all-sessions scope (null/undefined/*)', () => {+ expect(sessionScopeVisible(['A'], null)).toBe(false);+ expect(sessionScopeVisible(['A'], undefined)).toBe(false);+ expect(sessionScopeVisible(['A'], '*')).toBe(false);+ });+});diff --git a/src/common/security/session-scope.ts b/src/common/security/session-scope.tsindex d200190d0..c03327f22 100644--- a/src/common/security/session-scope.ts+++ b/src/common/security/session-scope.ts@@ -21,3 +21,19 @@ export function resolveSessionScope(}return requestedSessionId ? [requestedSessionId] : null;}++/**+ * True when `sessionScope` — a resource's session binding, where null/undefined means "all+ * sessions" — falls inside the calling key's `allowedSessions`. An unrestricted key (no allowlist)+ * 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).+ */+export function sessionScopeVisible(+ allowedSessions: string[] | null | undefined,+ sessionScope: string | null | undefined,+): boolean {+ if (allowedSessions == null || allowedSessions.length === 0) return true;+ return sessionScope != null && sessionScope !== '*' && allowedSessions.includes(sessionScope);+}diff --git a/src/modules/auth/auth.controller.spec.ts b/src/modules/auth/auth.controller.spec.tsindex f3995f6e0..a44ad9936 100644--- a/src/modules/auth/auth.controller.spec.ts+++ b/src/modules/auth/auth.controller.spec.ts@@ -1,10 +1,21 @@+import 'reflect-metadata';import type { Request } from 'express';import { AuthController } from './auth.controller';+import { UNSCOPED_KEY } from './decorators/auth.decorators';import { AuditAction } from '../audit/entities/audit-log.entity';import type { ApiKey } from './entities/api-key.entity';import type { AuthService } from './auth.service';import type { AuditService } from '../audit/audit.service';+// Key-lifecycle routes carry no session dimension, so the guard's allowedSessions fence can never+// bite on them — the class-level @RequireUnscopedKey marker is what keeps a session-scoped ADMIN+// key from minting or widening credentials here. Lock that the marker stays on the controller.+describe('AuthController — scoped-key confinement marker', () => {+ it('requires unscoped keys at the class level', () => {+ expect(Reflect.getMetadata(UNSCOPED_KEY, AuthController)).toBe(true);+ });+});+// API-key lifecycle operations (create / delete / revoke) must leave an audit trail — they were// previously unrecorded. These assert the controller emits the matching audit action with the acting// admin key, the resolved client IP, and the target key in metadata.diff --git a/src/modules/auth/auth.controller.ts b/src/modules/auth/auth.controller.tsindex 414d50673..d0c327962 100644--- a/src/modules/auth/auth.controller.ts+++ b/src/modules/auth/auth.controller.ts@@ -3,13 +3,16 @@ import { ApiTags, ApiOperation, ApiResponse } from '@nestjs/swagger';import type { Request } from 'express';import { AuthService } from './auth.service';import { CreateApiKeyDto, UpdateApiKeyDto, ApiKeyResponseDto, ApiKeyCreatedResponseDto } from './dto';-import { RequireRole, CurrentApiKey } from './decorators/auth.decorators';+import { RequireRole, CurrentApiKey, RequireUnscopedKey } from './decorators/auth.decorators';import { type ApiKey, ApiKeyRole } from './entities/api-key.entity';import { AuditService } from '../audit/audit.service';import { AuditAction } from './../audit/entities/audit-log.entity';@ApiTags('auth')@Controller('auth/api-keys')+// Key lifecycle routes have no session dimension, so a session-scoped ADMIN key could otherwise+// escape its confinement here (mint an unrestricted key, or clear another key's allowedSessions).+@RequireUnscopedKey()export class AuthController {constructor(private readonly authService: AuthService,diff --git a/src/modules/auth/decorators/auth.decorators.ts b/src/modules/auth/decorators/auth.decorators.tsindex ff70e47e0..1a2e62fee 100644--- a/src/modules/auth/decorators/auth.decorators.ts+++ b/src/modules/auth/decorators/auth.decorators.ts@@ -6,6 +6,7 @@ import { ApiKey } from '../entities/api-key.entity';export const REQUIRED_ROLE_KEY = 'requiredRole';export const PUBLIC_KEY = 'isPublic';export const SESSION_SCOPED_KEY = 'sessionScoped';+export const UNSCOPED_KEY = 'requireUnscopedKey';/*** Mark a route as requiring a specific role@@ -28,6 +29,15 @@ export const SessionScoped = () => SetMetadata(SESSION_SCOPED_KEY, true);*/export const Public = () => SetMetadata(PUBLIC_KEY, true);+/**+ * Mark a controller (or route) as off-limits to session-scoped API keys, regardless of role. The+ * ApiKeyGuard session fence can only compare against a session id carried in the route params, so+ * surfaces with no session dimension at all (e.g. API-key lifecycle management) would otherwise be+ * fully reachable by a scoped key — letting it mint or widen credentials beyond its own confinement.+ * @example @RequireUnscopedKey() @Controller('auth/api-keys')+ */+export const RequireUnscopedKey = () => SetMetadata(UNSCOPED_KEY, true);+/*** Get the current API key from request* @example @CurrentApiKey() apiKey: ApiKeydiff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex 2f50f4b9e..ebb54cd84 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -189,6 +189,58 @@ describe('ApiKeyGuard', () => {await expect(guard.canActivate(context)).rejects.toThrow(ForbiddenException);});+ it('rejects a session-scoped key on a @RequireUnscopedKey route, whatever its role', async () => {+ reflector.getAllAndOverride+ .mockReturnValueOnce(false) // not public+ .mockReturnValueOnce(ApiKeyRole.ADMIN) // required role = ADMIN+ .mockReturnValueOnce(undefined) // not @SessionScoped+ .mockReturnValueOnce(true); // @RequireUnscopedKey++ const apiKey = createMockApiKey({ role: ApiKeyRole.ADMIN, allowedSessions: ['sess-A'] });+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);+ (authService.hasPermission as jest.Mock).mockReturnValue(true);++ const context = createMockContext({ 'x-api-key': 'scoped-admin-key' }, {}, '203.0.113.44');++ await expect(guard.canActivate(context)).rejects.toThrow('Session-scoped API keys are not permitted on this route');+ await new Promise(resolve => setImmediate(resolve)); // let the fire-and-forget audit write settle+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ ipAddress: '203.0.113.44' }),+ );+ });++ it('admits an unrestricted key on a @RequireUnscopedKey route', async () => {+ reflector.getAllAndOverride+ .mockReturnValueOnce(false) // not public+ .mockReturnValueOnce(ApiKeyRole.ADMIN) // required role = ADMIN+ .mockReturnValueOnce(undefined) // not @SessionScoped+ .mockReturnValueOnce(true); // @RequireUnscopedKey++ const apiKey = createMockApiKey({ role: ApiKeyRole.ADMIN, allowedSessions: null });+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);+ (authService.hasPermission as jest.Mock).mockReturnValue(true);++ const context = createMockContext({ 'x-api-key': 'admin-key' });++ await expect(guard.canActivate(context)).resolves.toBe(true);+ });++ it('admits a session-scoped key on routes WITHOUT the @RequireUnscopedKey marker', async () => {+ reflector.getAllAndOverride+ .mockReturnValueOnce(false) // not public+ .mockReturnValueOnce(undefined) // no required role+ .mockReturnValueOnce(undefined) // not @SessionScoped+ .mockReturnValueOnce(undefined); // not @RequireUnscopedKey++ const apiKey = createMockApiKey({ allowedSessions: ['sess-A'] });+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ const context = createMockContext({ 'x-api-key': 'scoped-key' });++ await expect(guard.canActivate(context)).resolves.toBe(true);+ });+it('should pass session ID from route params to validateApiKey', async () => {reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex 475e55aef..115f798b7 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -4,7 +4,7 @@ import { ConfigService } from '@nestjs/config';import { Request } from 'express';import { AuthService } from '../auth.service';import { ApiKeyRole } from '../entities/api-key.entity';-import { REQUIRED_ROLE_KEY, PUBLIC_KEY, SESSION_SCOPED_KEY } from '../decorators/auth.decorators';+import { REQUIRED_ROLE_KEY, PUBLIC_KEY, SESSION_SCOPED_KEY, UNSCOPED_KEY } from '../decorators/auth.decorators';import { resolveClientIp } from '../../../common/utils/ip';import { setRequestActor } from '../../../common/services/request-context';import { AuditService } from '../../audit/audit.service';@@ -80,6 +80,18 @@ export class ApiKeyGuard implements CanActivate {throw new ForbiddenException(`Insufficient permissions. Required: ${requiredRole}`);}+ // Routes marked @RequireUnscopedKey carry no session dimension, so the allowedSessions check+ // above can never bite on them. A session-scoped key reaching such a surface (e.g. API-key+ // lifecycle management) could mint or widen credentials beyond its own confinement — reject it+ // outright, whatever its role. The denial is audited by the caller's catch block.+ const requireUnscoped = this.reflector.getAllAndOverride<boolean>(UNSCOPED_KEY, [+ context.getHandler(),+ context.getClass(),+ ]);+ if (requireUnscoped && (apiKey.allowedSessions?.length ?? 0) > 0) {+ throw new ForbiddenException('Session-scoped API keys are not permitted on this route');+ }+// Attach API key to request for use in controllers(request as Request & { apiKey: typeof apiKey }).apiKey = apiKey;// Expose the trusted-proxy-aware client IP so controllers (e.g. the audit trail on key lifecyclediff --git a/src/modules/integration/integration-instance.controller.spec.ts b/src/modules/integration/integration-instance.controller.spec.tsindex a4914253e..eef1a5350 100644--- a/src/modules/integration/integration-instance.controller.spec.ts+++ b/src/modules/integration/integration-instance.controller.spec.ts@@ -1,8 +1,10 @@+import { ForbiddenException, NotFoundException } from '@nestjs/common';import { IntegrationInstanceController } from './integration-instance.controller';import { PluginInstanceService } from './plugin-instance.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';import { AuditService } from '../audit/audit.service';import { ScopeBindingService } from './scope-binding.service';+import { ApiKey } from '../auth/entities/api-key.entity';// The provisioning bridge is what makes a minted instance's config reach the ingress worker: on// create/patch it mirrors the instance config into the plugin's per-session config and activates the@@ -184,3 +186,140 @@ describe('IntegrationInstanceController provisioning bridge', () => {expect(setPluginSessionConfig).toHaveBeenCalledWith('chatwoot-adapter', 'sess-2', { baseUrl: 'https://y' }); // new bound});});++// 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).+describe('IntegrationInstanceController session-scope fence', () => {+ const scopedKey = { allowedSessions: ['sess-1'] } as ApiKey;+ const unrestrictedKey = { allowedSessions: null } as unknown as ApiKey;++ function build(instances: Partial<PluginInstanceService>) {+ const loader = {+ getPlugin: jest.fn().mockReturnValue({+ manifest: { id: 'chatwoot-adapter', ingress: [{ route: 'chatwoot' }], permissions: ['webhook:ingress'] },+ activeSessions: [],+ }),+ setPluginSessionConfig: jest.fn(),+ setPluginSessions: jest.fn(),+ updatePluginConfig: jest.fn(),+ } as unknown as PluginLoaderService;+ const audit = { logInfo: jest.fn() } as unknown as AuditService;+ const svc = { maskedView: (i: unknown) => i, ...instances } as unknown as PluginInstanceService;+ const controller = new IntegrationInstanceController(+ svc,+ loader,+ audit,+ new ScopeBindingService(svc, loader, audit),+ );+ return { controller, svc };+ }++ const baseInstance = {+ id: 'chatwoot-adapter:acct1',+ pluginId: 'chatwoot-adapter',+ instanceId: 'acct1',+ sessionScope: 'sess-2',+ secret: 's',+ verifyToken: null,+ config: null,+ enabled: true,+ createdAt: new Date(0),+ updatedAt: new Date(0),+ };++ it('lets a scoped key create an instance bound to one of its own sessions', async () => {+ const create = jest.fn().mockResolvedValue({ ...baseInstance, sessionScope: 'sess-1' });+ const { controller } = build({ create });++ await controller.create('chatwoot-adapter', { instanceId: 'acct1', sessionScope: 'sess-1' }, scopedKey);++ expect(create).toHaveBeenCalled();+ });++ it('rejects create when sessionScope is outside the key fence — or omitted (all sessions)', async () => {+ const create = jest.fn();+ const { controller } = build({ create });++ await expect(+ controller.create('chatwoot-adapter', { instanceId: 'acct1', sessionScope: 'sess-2' }, scopedKey),+ ).rejects.toThrow(ForbiddenException);+ await expect(controller.create('chatwoot-adapter', { instanceId: 'acct1' }, scopedKey)).rejects.toThrow(+ ForbiddenException,+ );+ expect(create).not.toHaveBeenCalled();+ });++ it('lets an unrestricted key create an all-sessions instance', async () => {+ const create = jest.fn().mockResolvedValue({ ...baseInstance, sessionScope: null });+ const { controller } = build({ create });++ await controller.create('chatwoot-adapter', { instanceId: 'acct1' }, unrestrictedKey);++ expect(create).toHaveBeenCalled();+ });++ it('filters the list to instances inside the key fence', async () => {+ const { controller } = build({+ list: jest.fn().mockResolvedValue([+ { ...baseInstance, instanceId: 'own', sessionScope: 'sess-1' },+ { ...baseInstance, instanceId: 'other', sessionScope: 'sess-2' },+ { ...baseInstance, instanceId: 'global', sessionScope: null },+ ]),+ });++ const views = await controller.list('chatwoot-adapter', scopedKey);++ expect(views.map(v => v.instanceId)).toEqual(['own']);+ });++ it('answers 404 for getOne/regenerate/delete on an out-of-scope instance', async () => {+ const resolve = jest.fn().mockResolvedValue(baseInstance); // sessionScope: 'sess-2'+ const regenerateSecret = jest.fn();+ const remove = jest.fn();+ const { controller } = build({ resolve, regenerateSecret, remove });++ await expect(controller.getOne('chatwoot-adapter', 'acct1', scopedKey)).rejects.toThrow(NotFoundException);+ await expect(controller.regenerate('chatwoot-adapter', 'acct1', scopedKey)).rejects.toThrow(NotFoundException);+ await expect(controller.remove('chatwoot-adapter', 'acct1', scopedKey)).rejects.toThrow(NotFoundException);+ expect(regenerateSecret).not.toHaveBeenCalled();+ expect(remove).not.toHaveBeenCalled();+ });++ it('answers 404 when patching an out-of-scope instance', async () => {+ const update = jest.fn();+ const { controller } = build({ resolve: jest.fn().mockResolvedValue(baseInstance), update });++ await expect(controller.patch('chatwoot-adapter', 'acct1', { enabled: false }, scopedKey)).rejects.toThrow(+ NotFoundException,+ );+ expect(update).not.toHaveBeenCalled();+ });++ it('rejects moving an in-scope instance to a session outside the fence', async () => {+ const update = jest.fn();+ const { controller } = build({+ resolve: jest.fn().mockResolvedValue({ ...baseInstance, sessionScope: 'sess-1' }),+ update,+ });++ await expect(controller.patch('chatwoot-adapter', 'acct1', { sessionScope: 'sess-2' }, scopedKey)).rejects.toThrow(+ ForbiddenException,+ );+ // An explicit null (all sessions) is likewise outside a scoped key's fence.+ await expect(+ controller.patch('chatwoot-adapter', 'acct1', { sessionScope: null as unknown as string }, scopedKey),+ ).rejects.toThrow(ForbiddenException);+ expect(update).not.toHaveBeenCalled();+ });++ it('lets a scoped key patch an in-scope instance without touching sessionScope', async () => {+ const inst = { ...baseInstance, sessionScope: 'sess-1' };+ const setEnabled = jest.fn().mockResolvedValue({ ...inst, enabled: false });+ const { controller } = build({ resolve: jest.fn().mockResolvedValue(inst), setEnabled, update: jest.fn() });++ await controller.patch('chatwoot-adapter', 'acct1', { enabled: false }, scopedKey);++ expect(setEnabled).toHaveBeenCalledWith('chatwoot-adapter', 'acct1', false);+ });+});diff --git a/src/modules/integration/integration-instance.controller.ts b/src/modules/integration/integration-instance.controller.tsindex 50928b408..96dbe8390 100644--- a/src/modules/integration/integration-instance.controller.ts+++ b/src/modules/integration/integration-instance.controller.ts@@ -4,6 +4,7 @@ import {ConflictException,Controller,Delete,+ ForbiddenException,Get,HttpCode,NotFoundException,@@ -11,8 +12,8 @@ import {Patch,Post,} from '@nestjs/common';-import { RequireRole } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { CurrentApiKey, RequireRole } from '../auth/decorators/auth.decorators';+import { type ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';import { AuditAction } from '../audit/entities/audit-log.entity';import { AuditService } from '../audit/audit.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';@@ -21,6 +22,7 @@ import { ScopeBindingService } from './scope-binding.service';import { PluginInstance } from './entities/plugin-instance.entity';import { buildIngressUrls } from './ingress-url';import { CreateInstanceDto, InstanceView, UpdateInstanceDto } from './dto/instance.dto';+import { sessionScopeVisible } from '../../common/security/session-scope';import { ApiTags, ApiResponse } from '@nestjs/swagger';// ADMIN-only provisioning surface for per-plugin instances (e.g. one Chatwoot account). Only plugins@@ -45,8 +47,13 @@ export class IntegrationInstanceController {'Instance created. The plaintext ingress secret and verifyToken are revealed once in this response — store them immediately (both masked on every later read).',type: InstanceView,})- async create(@Param('pluginId') pluginId: string, @Body() dto: CreateInstanceDto): Promise<InstanceView> {+ async create(+ @Param('pluginId') pluginId: string,+ @Body() dto: CreateInstanceDto,+ @CurrentApiKey() apiKey?: ApiKey,+ ): Promise<InstanceView> {const routes = this.assertIngressCapable(pluginId);+ this.assertScopeWritable(apiKey, dto.sessionScope);try {const inst = await this.instances.create(pluginId, dto.instanceId, {sessionScope: dto.sessionScope,@@ -67,17 +74,22 @@ export class IntegrationInstanceController {@Get()@ApiResponse({ status: 200, description: 'Instances for the plugin (secrets masked).', type: [InstanceView] })- async list(@Param('pluginId') pluginId: string): Promise<InstanceView[]> {+ async list(@Param('pluginId') pluginId: string, @CurrentApiKey() apiKey?: ApiKey): Promise<InstanceView[]> {const routes = this.pluginRoutes(pluginId);const rows = await this.instances.list(pluginId);- return rows.map(r => this.view(r, routes, false));+ return rows+ .filter(r => sessionScopeVisible(apiKey?.allowedSessions, r.sessionScope))+ .map(r => this.view(r, routes, false));}@Get(':instanceId')@ApiResponse({ status: 200, description: 'The instance (secret masked).', type: InstanceView })- async getOne(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<InstanceView> {- const inst = await this.instances.resolve(pluginId, instanceId);- if (!inst) throw new NotFoundException('instance not found');+ async getOne(+ @Param('pluginId') pluginId: string,+ @Param('instanceId') instanceId: string,+ @CurrentApiKey() apiKey?: ApiKey,+ ): Promise<InstanceView> {+ const inst = await this.resolveVisible(pluginId, instanceId, apiKey);return this.view(inst, this.pluginRoutes(pluginId), false);}@@ -92,8 +104,9 @@ export class IntegrationInstanceController {async regenerate(@Param('pluginId') pluginId: string,@Param('instanceId') instanceId: string,+ @CurrentApiKey() apiKey?: ApiKey,): Promise<InstanceView> {- if (!(await this.instances.resolve(pluginId, instanceId))) throw new NotFoundException('instance not found');+ await this.resolveVisible(pluginId, instanceId, apiKey);const inst = await this.instances.regenerateSecret(pluginId, instanceId);void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_SECRET_REGENERATED, {metadata: { pluginId, instanceId },@@ -107,9 +120,10 @@ export class IntegrationInstanceController {@Param('pluginId') pluginId: string,@Param('instanceId') instanceId: string,@Body() dto: UpdateInstanceDto,+ @CurrentApiKey() apiKey?: ApiKey,): Promise<InstanceView> {- let inst: PluginInstance | null = await this.instances.resolve(pluginId, instanceId);- if (!inst) throw new NotFoundException('instance not found');+ let inst: PluginInstance | null = await this.resolveVisible(pluginId, instanceId, apiKey);+ if (dto.sessionScope !== undefined) this.assertScopeWritable(apiKey, dto.sessionScope);const previousScope = inst.sessionScope;if (dto.enabled !== undefined) inst = await this.instances.setEnabled(pluginId, instanceId, dto.enabled);if (dto.sessionScope !== undefined || dto.config !== undefined) {@@ -134,9 +148,12 @@ export class IntegrationInstanceController {@Delete(':instanceId')@HttpCode(204)@ApiResponse({ status: 204, description: 'Instance deleted and its session scope torn down.' })- async remove(@Param('pluginId') pluginId: string, @Param('instanceId') instanceId: string): Promise<void> {- const inst = await this.instances.resolve(pluginId, instanceId);- if (!inst) throw new NotFoundException('instance not found');+ async remove(+ @Param('pluginId') pluginId: string,+ @Param('instanceId') instanceId: string,+ @CurrentApiKey() apiKey?: ApiKey,+ ): Promise<void> {+ const inst = await this.resolveVisible(pluginId, instanceId, apiKey);const scope = inst.sessionScope;// Delete the row FIRST, then tear down its scope: for a wildcard/null scope the teardown lists the// remaining instances to decide whether to retire '*', and that check must not count this instance.@@ -145,6 +162,25 @@ export class IntegrationInstanceController {void this.audit.logInfo(AuditAction.INTEGRATION_INSTANCE_DELETED, { metadata: { pluginId, instanceId } });}+ // Resolve an instance the calling key may see: a session-scoped key only reaches instances bound+ // to one of its own sessions. Out-of-scope instances answer 404 (identical to a missing one) so+ // the endpoint cannot be used to probe which instances exist on other sessions.+ private async resolveVisible(pluginId: string, instanceId: string, apiKey?: ApiKey): Promise<PluginInstance> {+ const inst = await this.instances.resolve(pluginId, instanceId);+ if (!inst || !sessionScopeVisible(apiKey?.allowedSessions, inst.sessionScope)) {+ throw new NotFoundException('instance not found');+ }+ return inst;+ }++ // A scoped key may only bind an instance to a session inside its own fence — never to another+ // session, and never to the all-sessions (omitted/'*') scope.+ private assertScopeWritable(apiKey: ApiKey | undefined, sessionScope: string | null | undefined): void {+ if (!sessionScopeVisible(apiKey?.allowedSessions, sessionScope)) {+ throw new ForbiddenException("sessionScope is outside the API key's allowed sessions");+ }+ }+// The plugin must exist AND declare ingress + the webhook:ingress permission to have instances.private assertIngressCapable(pluginId: string): string[] {const plugin = this.loader.getPlugin(pluginId);diff --git a/src/modules/integration/redrive.controller.spec.ts b/src/modules/integration/redrive.controller.spec.tsindex 35ee5763b..e6edbc262 100644--- a/src/modules/integration/redrive.controller.spec.ts+++ b/src/modules/integration/redrive.controller.spec.ts@@ -1,7 +1,10 @@import { Reflector } from '@nestjs/core';+import { NotFoundException } from '@nestjs/common';import { RedriveController } from './redrive.controller';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';+import { PluginInstanceService } from './plugin-instance.service';+import { RedriveService } from './redrive.service';describe('RedriveController authz', () => {it('is ADMIN-gated (re-dispatching DLQ payloads can cause real sends; a VIEWER/OPERATOR key must not)', () => {@@ -11,3 +14,55 @@ describe('RedriveController authz', () => {expect(role).toBe(ApiKeyRole.ADMIN);});});++// The instance's session binding lives in the persisted row, which the ApiKeyGuard's route-param+// fence never sees — the controller must confine a session-scoped key itself.+describe('RedriveController session-scope fence', () => {+ const scopedKey = { allowedSessions: ['sess-1'] } as ApiKey;++ function build(sessionScope: string | null) {+ const redrive = { redriveInstance: jest.fn().mockResolvedValue({ redriven: 0, remaining: 0, batchSize: 100 }) };+ const instances = {+ resolve: jest+ .fn()+ .mockResolvedValue(+ sessionScope === undefined ? null : { pluginId: 'chatwoot', instanceId: 'acct1', sessionScope },+ ),+ };+ const controller = new RedriveController(+ redrive as unknown as RedriveService,+ instances as unknown as PluginInstanceService,+ );+ return { controller, redrive };+ }++ it('lets a scoped key redrive an instance bound to one of its sessions', async () => {+ const { controller, redrive } = build('sess-1');++ await controller.redriveInstance('chatwoot', 'acct1', scopedKey);++ expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1');+ });++ it('answers 404 when a scoped key redrives an out-of-scope instance (and never dispatches)', async () => {+ const { controller, redrive } = build('sess-2');++ await expect(controller.redriveInstance('chatwoot', 'acct1', scopedKey)).rejects.toThrow(NotFoundException);+ expect(redrive.redriveInstance).not.toHaveBeenCalled();+ });++ it('answers 404 when a scoped key redrives an all-sessions (null scope) instance', async () => {+ const { controller, redrive } = build(null);++ await expect(controller.redriveInstance('chatwoot', 'acct1', scopedKey)).rejects.toThrow(NotFoundException);+ expect(redrive.redriveInstance).not.toHaveBeenCalled();+ });++ it('lets an unrestricted key redrive any instance', async () => {+ const { controller, redrive } = build('sess-2');++ await controller.redriveInstance('chatwoot', 'acct1', { allowedSessions: null } as unknown as ApiKey);++ expect(redrive.redriveInstance).toHaveBeenCalledWith('chatwoot', 'acct1');+ });+});diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.tsindex ef51b0754..6d5ec9ea7 100644--- a/src/modules/integration/redrive.controller.ts+++ b/src/modules/integration/redrive.controller.ts@@ -1,7 +1,9 @@-import { Controller, Param, Post } from '@nestjs/common';+import { Controller, NotFoundException, Param, Post } from '@nestjs/common';import { ApiTags, ApiResponse } from '@nestjs/swagger';-import { RequireRole } from '../auth/decorators/auth.decorators';-import { ApiKeyRole } from '../auth/entities/api-key.entity';+import { CurrentApiKey, RequireRole } from '../auth/decorators/auth.decorators';+import { type ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';+import { sessionScopeVisible } from '../../common/security/session-scope';+import { PluginInstanceService } from './plugin-instance.service';import { RedriveService } from './redrive.service';// Re-dispatching DLQ'd inbound payloads can cause real downstream sends, so this operator action is@@ -11,17 +13,27 @@ import { RedriveService } from './redrive.service';@Controller('integration/instances')@RequireRole(ApiKeyRole.ADMIN)export class RedriveController {- constructor(private readonly redrive: RedriveService) {}+ constructor(+ private readonly redrive: RedriveService,+ private readonly instances: PluginInstanceService,+ ) {}@Post(':pluginId/:instanceId/redrive')@ApiResponse({status: 201,description: 'One bounded batch of dead-lettered ingress deliveries re-dispatched, with remaining depth.',})- redriveInstance(+ async redriveInstance(@Param('pluginId') pluginId: string,@Param('instanceId') instanceId: string,+ @CurrentApiKey() apiKey?: ApiKey,): 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.+ const inst = await this.instances.resolve(pluginId, instanceId);+ if (inst && !sessionScopeVisible(apiKey?.allowedSessions, inst.sessionScope)) {+ throw new NotFoundException('instance not found');+ }return this.redrive.redriveInstance(pluginId, instanceId);}}diff --git a/test/integration-instance.e2e-spec.ts b/test/integration-instance.e2e-spec.tsindex ebfab70a4..e735c5ad0 100644--- a/test/integration-instance.e2e-spec.ts+++ b/test/integration-instance.e2e-spec.ts@@ -13,6 +13,8 @@ import { App } from 'supertest/types';import { AppModule } from '../src/app.module';import { applyGlobalValidation } from '../src/config/app-validation';import { PluginLoaderService } from '../src/core/plugins/plugin-loader.service';+import { AuthService } from '../src/modules/auth/auth.service';+import { ApiKeyRole } from '../src/modules/auth/entities/api-key.entity';// A stub ingress-capable plugin so the capability check passes without a real plugin on disk.const INGRESS_PLUGIN = {@@ -163,4 +165,112 @@ describe('IntegrationInstanceController (e2e)', () => {await request(app.getHttpServer()).delete(`${base}/chatwoot/instances/acct1`).set('X-API-Key', key).expect(204);await request(app.getHttpServer()).get(`${base}/chatwoot/instances/acct1`).set('X-API-Key', key).expect(404);});++ /**+ * sessionScope travels in the request body / persisted row, which the ApiKeyGuard's route-param+ * fence never sees — so the controllers themselves confine a session-scoped ADMIN key to+ * instances bound inside its allowedSessions. Out-of-scope instances must look exactly like+ * missing ones (404), and an all-sessions (omitted) scope must be uncreatable/unreachable.+ */+ describe('session-scoped API key fence', () => {+ let scopedKey: string; // ADMIN, allowedSessions: ['sess-1']++ beforeAll(async () => {+ const authService = app.get(AuthService);+ scopedKey = (+ await authService.createApiKey({ name: 'e2e-scoped-int', role: ApiKeyRole.ADMIN, allowedSessions: ['sess-1'] })+ ).rawKey;+ // Fixtures created with the unrestricted key: one instance inside the fence, one outside, one global.+ const mk = (instanceId: string, body: Record<string, unknown>) =>+ request(app.getHttpServer())+ .post(`${base}/chatwoot/instances`)+ .set('X-API-Key', key)+ .send({ instanceId, ...body });+ await mk('own1', { sessionScope: 'sess-1' }).expect(201);+ await mk('other1', { sessionScope: 'sess-2' }).expect(201);+ await mk('global1', {}).expect(201);+ });++ it('allows creating an instance bound to its own session', async () => {+ await request(app.getHttpServer())+ .post(`${base}/chatwoot/instances`)+ .set('X-API-Key', scopedKey)+ .send({ instanceId: 'own2', sessionScope: 'sess-1' })+ .expect(201);+ });++ it('rejects create with a sessionScope outside the fence — or omitted (all sessions)', async () => {+ await request(app.getHttpServer())+ .post(`${base}/chatwoot/instances`)+ .set('X-API-Key', scopedKey)+ .send({ instanceId: 'x1', sessionScope: 'sess-2' })+ .expect(403);+ await request(app.getHttpServer())+ .post(`${base}/chatwoot/instances`)+ .set('X-API-Key', scopedKey)+ .send({ instanceId: 'x2' })+ .expect(403);+ });++ it('lists only instances bound inside the fence', async () => {+ const res = await request(app.getHttpServer())+ .get(`${base}/chatwoot/instances`)+ .set('X-API-Key', scopedKey)+ .expect(200);+ const ids = (res.body as Array<{ instanceId: string }>).map(i => i.instanceId);+ expect(ids).toContain('own1');+ expect(ids).toContain('own2');+ expect(ids).not.toContain('other1');+ expect(ids).not.toContain('global1');+ });++ it('answers 404 on getOne/regenerate/delete for instances outside the fence', async () => {+ await request(app.getHttpServer())+ .get(`${base}/chatwoot/instances/other1`)+ .set('X-API-Key', scopedKey)+ .expect(404);+ await request(app.getHttpServer())+ .get(`${base}/chatwoot/instances/global1`)+ .set('X-API-Key', scopedKey)+ .expect(404);+ await request(app.getHttpServer())+ .post(`${base}/chatwoot/instances/other1/regenerate-secret`)+ .set('X-API-Key', scopedKey)+ .expect(404);+ await request(app.getHttpServer())+ .delete(`${base}/chatwoot/instances/other1`)+ .set('X-API-Key', scopedKey)+ .expect(404);+ });++ it('answers 404 when patching an out-of-scope instance, 403 when moving an in-scope one out', async () => {+ await request(app.getHttpServer())+ .patch(`${base}/chatwoot/instances/other1`)+ .set('X-API-Key', scopedKey)+ .send({ enabled: false })+ .expect(404);+ await request(app.getHttpServer())+ .patch(`${base}/chatwoot/instances/own1`)+ .set('X-API-Key', scopedKey)+ .send({ sessionScope: 'sess-2' })+ .expect(403);+ // …while an in-scope patch that leaves sessionScope alone still works.+ await request(app.getHttpServer())+ .patch(`${base}/chatwoot/instances/own1`)+ .set('X-API-Key', scopedKey)+ .send({ enabled: false })+ .expect(200);+ });++ it('answers 404 when redriving an out-of-scope instance, but redrives its own', async () => {+ await request(app.getHttpServer())+ .post('/api/integration/instances/chatwoot/other1/redrive')+ .set('X-API-Key', scopedKey)+ .expect(404);+ await request(app.getHttpServer())+ .post('/api/integration/instances/chatwoot/own1/redrive')+ .set('X-API-Key', scopedKey)+ .expect(201);+ });+ });});diff --git a/test/session-scope.e2e-spec.ts b/test/session-scope.e2e-spec.tsindex fc5474c36..d23ea34ff 100644--- a/test/session-scope.e2e-spec.ts+++ b/test/session-scope.e2e-spec.ts@@ -27,6 +27,8 @@ describe('Session-scoped query endpoints (e2e)', () => {let sessB: string;let scopedKey: string; // ADMIN, allowedSessions: [sessA]let adminKey: string; // ADMIN, unrestricted+ let throwawayId: string; // a VIEWER key used as the :id target for key-management routes+ let auditRepo: Repository<AuditLog>;beforeAll(async () => {const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [AppModule] }).compile();@@ -35,7 +37,7 @@ describe('Session-scoped query endpoints (e2e)', () => {await app.init();const sessionRepo: Repository<Session> = app.get(getRepositoryToken(Session, 'data'));- const auditRepo: Repository<AuditLog> = app.get(getRepositoryToken(AuditLog, 'main'));+ auditRepo = 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()}` }));@@ -65,6 +67,7 @@ describe('Session-scoped query endpoints (e2e)', () => {await authService.createApiKey({ name: 'e2e-scoped', role: ApiKeyRole.ADMIN, allowedSessions: [sessA] })).rawKey;adminKey = (await authService.createApiKey({ name: 'e2e-admin', role: ApiKeyRole.ADMIN })).rawKey;+ throwawayId = (await authService.createApiKey({ name: 'e2e-throwaway', role: ApiKeyRole.VIEWER })).apiKey.id;});afterAll(async () => {@@ -134,4 +137,85 @@ describe('Session-scoped query endpoints (e2e)', () => {expect(sessions).toContain(sessB);});});++ /**+ * The key-lifecycle routes carry no session id at all (neither route param nor query), so the+ * guard's route-param fence can never bite: a session-scoped ADMIN key would otherwise mint an+ * unrestricted key (POST), clear another key's allowedSessions (PUT), or enumerate every+ * credential (GET). These routes must reject scoped keys outright — while leaving unrestricted+ * ADMIN keys fully functional.+ */+ describe('API-key management routes (/api/auth/api-keys)', () => {+ it('rejects a scoped ADMIN on POST (cannot mint a key beyond its fence)', async () => {+ await request(app.getHttpServer())+ .post('/api/auth/api-keys')+ .set('X-API-Key', scopedKey)+ .send({ name: 'escape-attempt', role: 'admin', allowedSessions: [] })+ .expect(403);+ });++ it('rejects a scoped ADMIN on GET list (cannot enumerate credentials)', async () => {+ await request(app.getHttpServer()).get('/api/auth/api-keys').set('X-API-Key', scopedKey).expect(403);+ });++ it('rejects a scoped ADMIN on GET :id', async () => {+ await request(app.getHttpServer())+ .get(`/api/auth/api-keys/${throwawayId}`)+ .set('X-API-Key', scopedKey)+ .expect(403);+ });++ it('rejects a scoped ADMIN on PUT :id (cannot clear another key\u2019s scope)', async () => {+ await request(app.getHttpServer())+ .put(`/api/auth/api-keys/${throwawayId}`)+ .set('X-API-Key', scopedKey)+ .send({ allowedSessions: [] })+ .expect(403);+ });++ it('rejects a scoped ADMIN on DELETE :id', async () => {+ await request(app.getHttpServer())+ .delete(`/api/auth/api-keys/${throwawayId}`)+ .set('X-API-Key', scopedKey)+ .expect(403);+ });++ it('rejects a scoped ADMIN on POST :id/revoke', async () => {+ await request(app.getHttpServer())+ .post(`/api/auth/api-keys/${throwawayId}/revoke`)+ .set('X-API-Key', scopedKey)+ .expect(403);+ });++ it('leaves an unrestricted ADMIN fully functional across the key lifecycle', async () => {+ await request(app.getHttpServer()).get('/api/auth/api-keys').set('X-API-Key', adminKey).expect(200);+ const created = await request(app.getHttpServer())+ .post('/api/auth/api-keys')+ .set('X-API-Key', adminKey)+ .send({ name: 'e2e-lifecycle', role: 'viewer' })+ .expect(201);+ const id = (created.body as { id: string }).id;+ await request(app.getHttpServer())+ .put(`/api/auth/api-keys/${id}`)+ .set('X-API-Key', adminKey)+ .send({ name: 'e2e-lifecycle-renamed' })+ .expect(200);+ await request(app.getHttpServer()).post(`/api/auth/api-keys/${id}/revoke`).set('X-API-Key', adminKey).expect(200);+ await request(app.getHttpServer()).delete(`/api/auth/api-keys/${id}`).set('X-API-Key', adminKey).expect(204);+ });++ it('audits the scoped denial as a failed-auth event', async () => {+ await request(app.getHttpServer()).get('/api/auth/api-keys').set('X-API-Key', scopedKey).expect(403);+ // The audit write is fire-and-forget; poll briefly for it to land.+ const deadline = Date.now() + 5000;+ let row: AuditLog | null = null;+ while (Date.now() < deadline && !row) {+ row = await auditRepo.findOne({+ where: { action: AuditAction.API_KEY_AUTH_FAILED, path: '/api/auth/api-keys' },+ });+ if (!row) await new Promise(r => setTimeout(r, 100));+ }+ expect(row).not.toBeNull();+ });+ });});