Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): scope session-id enforcement to session routes; gate plugin reads to ADMIN (#398)
Yudhi Armyndharis745c0518b489
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c11e1ef48..c2867b7f9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -15,9 +15,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0any other flag) was silently never applied. In a hardened/containerized environment that can wedgesession startup. The parser now accepts either delimiter, and an already-saved space-separated valueis repaired on the next boot. (#397)+- **A session-restricted API key is no longer wrongly denied on non-session routes.** The guard+ derived the session for a key's `allowedSessions` scope from the `:id` route param, but `:id` is+ also the resource id on unrelated routes (e.g. `auth/api-keys/:id`, `plugins/:id`) — so a+ session-scoped key got a spurious `401` there. Session scoping is now applied only where `:id`+ actually denotes a session; enforcement on the real `sessions/:id/...` routes is unchanged. (#398)### Security+- **Plugin inventory, detail, and health reads now require the ADMIN role.** `GET /plugins`,+ `GET /plugins/:id`, and `GET /plugins/:id/health` were readable by any authenticated key (including+ the read-only VIEWER role), exposing installed plugin versions, non-secret configuration, and+ health/error text. They now require ADMIN, matching the plugin write routes and the infrastructure+ endpoints. (Secret config values were — and remain — redacted regardless.) (#398)- **The dashboard-generated env file is now written owner-only (`0600`).** Saving Infrastructureconfiguration wrote `data/.env.generated` — which can hold the database, S3, and Redis credentials —with default permissions (world-readable `0644`) until the next restart re-tightened it. It is nowdiff --git a/src/modules/auth/decorators/auth.decorators.ts b/src/modules/auth/decorators/auth.decorators.tsindex e39d6c610..ff70e47e0 100644--- a/src/modules/auth/decorators/auth.decorators.ts+++ b/src/modules/auth/decorators/auth.decorators.ts@@ -5,6 +5,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';/*** Mark a route as requiring a specific role@@ -12,6 +13,15 @@ export const PUBLIC_KEY = 'isPublic';*/export const RequireRole = (role: ApiKeyRole) => SetMetadata(REQUIRED_ROLE_KEY, role);+/**+ * Mark a controller (or route) whose `:id` route param denotes a WhatsApp session id, so the+ * ApiKeyGuard enforces a key's `allowedSessions` scope against it. Without this, `:id` is treated+ * as an opaque resource id (e.g. an API-key or plugin id) and is NOT used for session scoping —+ * preventing the guard from spuriously denying a session-restricted key on unrelated routes.+ * @example @SessionScoped() @Controller('sessions')+ */+export const SessionScoped = () => SetMetadata(SESSION_SCOPED_KEY, true);+/*** Mark a route as public (no API key required)* @example @Public()diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex ca3103287..5badba8e1 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -154,6 +154,38 @@ describe('ApiKeyGuard', () => {expect(authService.validateApiKey).toHaveBeenCalledWith('key', '127.0.0.1', 'sess-123');});+ it('does not treat a non-session route :id as a session id (no @SessionScoped)', async () => {+ reflector.getAllAndOverride+ .mockReturnValueOnce(false) // not public+ .mockReturnValueOnce(undefined) // no required role+ .mockReturnValueOnce(undefined); // controller is NOT @SessionScoped++ const apiKey = createMockApiKey();+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ // e.g. GET /plugins/:id or /auth/api-keys/:id — :id is a plugin/key id, not a session.+ const context = createMockContext({ 'x-api-key': 'key' }, { id: 'plugin-x' });+ await guard.canActivate(context);++ expect(authService.validateApiKey).toHaveBeenCalledWith('key', '127.0.0.1', undefined);+ });++ it('treats :id as the session id on a @SessionScoped controller (session scoping preserved)', async () => {+ reflector.getAllAndOverride+ .mockReturnValueOnce(false) // not public+ .mockReturnValueOnce(undefined) // no required role+ .mockReturnValueOnce(true); // controller IS @SessionScoped (SessionController)++ const apiKey = createMockApiKey();+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);++ // GET /sessions/:id/... — :id IS the session, so allowedSessions must still be enforced.+ const context = createMockContext({ 'x-api-key': 'key' }, { id: 'sess-B' });+ await guard.canActivate(context);++ expect(authService.validateApiKey).toHaveBeenCalledWith('key', '127.0.0.1', 'sess-B');+ });+it('ignores X-Forwarded-For by default (no trusted proxies) to prevent IP spoofing', 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 4d3d136be..edef1fb1b 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 } from '../decorators/auth.decorators';+import { REQUIRED_ROLE_KEY, PUBLIC_KEY, SESSION_SCOPED_KEY } from '../decorators/auth.decorators';import { resolveClientIp } from '../../../common/utils/ip';@Injectable()@@ -30,19 +30,27 @@ export class ApiKeyGuard implements CanActivate {throw new UnauthorizedException('API key is required');}- // Get session ID from route params if present- const sessionId = (request.params['sessionId'] || request.params['id']) as string | undefined;- const clientIp = this.getClientIp(request);-- // Validate API key- const apiKey = await this.authService.validateApiKey(apiKeyHeader, clientIp, sessionId);-- // Check role permissionconst requiredRole = this.reflector.getAllAndOverride<ApiKeyRole>(REQUIRED_ROLE_KEY, [context.getHandler(),context.getClass(),]);+ // Resolve the session id used for the key's allowedSessions scope. `:sessionId` is always a+ // session; the bare `:id` param is only a session on controllers marked @SessionScoped (i.e.+ // SessionController) — on other routes `:id` is an unrelated resource id (API key, plugin, …)+ // and must NOT be fed to the allowedSessions check, which would spuriously deny a scoped key.+ const sessionScoped = this.reflector.getAllAndOverride<boolean>(SESSION_SCOPED_KEY, [+ context.getHandler(),+ context.getClass(),+ ]);+ const sessionId = (request.params['sessionId'] || (sessionScoped ? request.params['id'] : undefined)) as+ | string+ | undefined;+ const clientIp = this.getClientIp(request);++ // Validate API key+ const apiKey = await this.authService.validateApiKey(apiKeyHeader, clientIp, sessionId);+if (requiredRole && !this.authService.hasPermission(apiKey, requiredRole)) {throw new ForbiddenException(`Insufficient permissions. Required: ${requiredRole}`);}diff --git a/src/modules/plugins/plugins.controller.spec.ts b/src/modules/plugins/plugins.controller.spec.tsnew file mode 100644index 000000000..d4e39840c--- /dev/null+++ b/src/modules/plugins/plugins.controller.spec.ts@@ -0,0 +1,19 @@+import { Reflector } from '@nestjs/core';+import { PluginsController } from './plugins.controller';+import { REQUIRED_ROLE_KEY } from '../auth/decorators/auth.decorators';+import { ApiKeyRole } from '../auth/entities/api-key.entity';++describe('PluginsController authorization', () => {+ const reflector = new Reflector();++ // Plugin reads expose installed versions, non-secret config, and health/error text — privileged+ // inventory on par with the ADMIN-gated write routes and the InfraController convention. A+ // VIEWER/OPERATOR key (or a session-scoped key) must not be able to enumerate it via the raw API.+ const adminOnly = ['findAll', 'findOne', 'healthCheck', 'enable', 'disable', 'updateConfig'] as const;++ it.each(adminOnly)('%s requires the ADMIN role', method => {+ const handler = PluginsController.prototype[method];+ const role = reflector.get<ApiKeyRole | undefined>(REQUIRED_ROLE_KEY, handler);+ expect(role).toBe(ApiKeyRole.ADMIN);+ });+});diff --git a/src/modules/plugins/plugins.controller.ts b/src/modules/plugins/plugins.controller.tsindex 70f617a17..7e892444b 100644--- a/src/modules/plugins/plugins.controller.ts+++ b/src/modules/plugins/plugins.controller.ts@@ -11,6 +11,7 @@ export class PluginsController {constructor(private readonly pluginsService: PluginsService) {}@Get()+ @RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'List all plugins' })@ApiResponse({ status: 200, description: 'List of all plugins' })findAll(): PluginDto[] {@@ -18,6 +19,7 @@ export class PluginsController {}@Get(':id')+ @RequireRole(ApiKeyRole.ADMIN)@ApiOperation({ summary: 'Get plugin by ID' })@ApiResponse({ status: 200, description: 'Plugin details' })@ApiResponse({ status: 404, description: 'Plugin not found' })@@ -52,6 +54,7 @@ export class PluginsController {}@Get(':id/health')+ @RequireRole(ApiKeyRole.ADMIN)@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 f72f92311..70936746b 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -15,11 +15,14 @@ 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 } from '../auth/decorators/auth.decorators';+import { RequireRole, CurrentApiKey, SessionScoped } from '../auth/decorators/auth.decorators';import { ApiKey, ApiKeyRole } from '../auth/entities/api-key.entity';@ApiTags('sessions')@Controller('sessions')+// The `:id` route param here is a WhatsApp session id, so the ApiKeyGuard enforces a key's+// allowedSessions scope against it (other controllers' `:id` is an unrelated resource id).+@SessionScoped()export class SessionController {constructor(private readonly sessionService: SessionService,