Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): attribute a post-authentication denial to the credential
Yudhi Armyndharis4f9667980a46
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 8c795e24e..0b02a2e16 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- An authorization denial now records WHICH credential was denied. Both post-authentication 403s — an insufficient role, and a session-scoped key on a route that forbids one — threw before the resolved key was stamped into the request context, so every such audit row carried `apiKeyId` and `apiKeyName` as null. Behind NAT or a reverse proxy without `TRUSTED_PROXIES` the recorded IP is common to every tenant, leaving an operator able to see that a key had been denied but not which one to revoke. The same stamp was added to the queue-dashboard mount, which has the same shape. A denial that happens before any key resolves is unchanged: the IP really is all there is.+- The three group-picture routes now refuse an id that does not name a group. They reuse the account's own profile-picture primitives, and Baileys omits the `target` attribute whenever the jid is the account's own — so `PUT` or `DELETE /sessions/:id/groups/<own-jid>/picture` replaced or permanently deleted the WhatsApp account's own avatar and answered `{success: true}`, while whatsapp-web.js refused the same input with a 404. Both engines now reject it with a 400 before the id reaches either adapter.- `GET /sessions/:sessionId/messages` and the MCP `MessageList` tool now bound the inline media they return, via `MESSAGE_LIST_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default). The row count was clamped to 1..100, but a row is not a bounded object: each carries its base64 in `metadata.media.data`, so a hundred media rows serialised to well over a hundred megabytes, and a large enough page pushed `JSON.stringify` past its ceiling and failed the read outright — permanently for the dashboard, which requests the maximum page size with no way to ask for less. The budget is spent newest-first; past it a payload is replaced with the `{ omitted: true, sizeBytes }` marker the engine already emits for skipped inbound media, and remains fetchable from the per-message media route.diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.tsindex 5d88b7193..74faf5f5c 100644--- a/src/common/security/bull-board-auth.middleware.ts+++ b/src/common/security/bull-board-auth.middleware.ts@@ -7,6 +7,7 @@ import { AuditService } from '../../modules/audit/audit.service';import { AuditAction } from '../../modules/audit/entities/audit-log.entity';import { KeyRateLimiter, readIpRateLimitConfig } from '../../modules/mcp/mcp-rate-limit';import { resolveClientIp } from '../utils/ip';+import { setRequestActor } from '../services/request-context';/*** Protects the Bull Board UI (/admin/queues).@@ -69,6 +70,16 @@ export class BullBoardAuthMiddleware implements NestMiddleware {}const apiKey = await this.authService.validateApiKey(rawKey, clientIp);++ // Stamp the resolved actor before the two authorization checks below, matching ApiKeyGuard.+ // Both of those throw, and the catch that audits the denial cannot see `apiKey` — it is a const+ // inside this try. Without the stamp, a denial on the most privileged UI in the deployment was+ // recorded against an IP alone, so the operator could not tell which key had tried to reach the+ // queue dashboard without ADMIN, or which confined key had tried to escape its session fence.+ // This mount runs inside the request-context scope (requestContextMiddleware is installed+ // ahead of it in main.ts), so the stamp reaches AuditService.+ setRequestActor({ apiKeyId: apiKey.id, apiKeyName: apiKey.name, ipAddress: clientIp });+if (!this.authService.hasPermission(apiKey, ApiKeyRole.ADMIN)) {throw new ForbiddenException('Admin role required to access the queue dashboard');}diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex ebb54cd84..3ae2601ad 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -1,4 +1,5 @@import { ExecutionContext, UnauthorizedException, ForbiddenException } from '@nestjs/common';+import { runWithRequestId, getRequestActor } from '../../../common/services/request-context';import { Reflector } from '@nestjs/core';import { ConfigService } from '@nestjs/config';import { ApiKeyGuard } from './api-key.guard';@@ -210,6 +211,67 @@ describe('ApiKeyGuard', () => {);});+ // Both post-authentication denials threw BEFORE the actor was stamped, so every 403 the guard+ // raises wrote an audit row whose apiKeyId/apiKeyName were null — attributable to an IP that,+ // behind NAT or a proxy without TRUSTED_PROXIES, is common to every tenant. The operator could+ // see that a key was denied but not WHICH key, so could not revoke it.+ describe('a post-authentication denial is attributable to the credential', () => {+ const actorAfterDenial = async (setupReflector: () => void, apiKey: ReturnType<typeof createMockApiKey>) => {+ setupReflector();+ (authService.validateApiKey as jest.Mock).mockResolvedValue(apiKey);+ const context = createMockContext({ 'x-api-key': 'k' }, {}, '203.0.113.44');+ let actor: ReturnType<typeof getRequestActor>;+ await runWithRequestId('req-1', async () => {+ await expect(guard.canActivate(context)).rejects.toThrow(ForbiddenException);+ actor = getRequestActor();+ });+ return actor;+ };++ it('stamps the key on an insufficient-role denial', async () => {+ const apiKey = createMockApiKey({ id: 'key-uuid-1', name: 'Reporting key', role: ApiKeyRole.VIEWER });+ (authService.hasPermission as jest.Mock).mockReturnValue(false);++ const actor = await actorAfterDenial(() => {+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(ApiKeyRole.ADMIN);+ }, apiKey);++ expect(actor).toMatchObject({ apiKeyId: 'key-uuid-1', apiKeyName: 'Reporting key', ipAddress: '203.0.113.44' });+ });++ it('stamps the key on a session-scoped-key denial', async () => {+ const apiKey = createMockApiKey({ id: 'key-uuid-2', name: 'Tenant A', allowedSessions: ['sess-A'] });+ (authService.hasPermission as jest.Mock).mockReturnValue(true);++ const actor = await actorAfterDenial(() => {+ reflector.getAllAndOverride+ .mockReturnValueOnce(false)+ .mockReturnValueOnce(ApiKeyRole.ADMIN)+ .mockReturnValueOnce(undefined)+ .mockReturnValueOnce(true);+ }, apiKey);++ expect(actor).toMatchObject({ apiKeyId: 'key-uuid-2', apiKeyName: 'Tenant A' });+ });++ // Negative twin: a denial BEFORE the key resolves still has no key to name, and must not+ // invent one — the IP is genuinely all there is.+ it('leaves an unauthenticated denial attributable to the IP alone', async () => {+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);+ (authService.validateApiKey as jest.Mock).mockRejectedValue(new UnauthorizedException('bad key'));+ const context = createMockContext({ 'x-api-key': 'nope' }, {}, '203.0.113.44');++ let actor: ReturnType<typeof getRequestActor>;+ await runWithRequestId('req-2', async () => {+ await expect(guard.canActivate(context)).rejects.toThrow(UnauthorizedException);+ actor = getRequestActor();+ });++ expect(actor?.apiKeyId).toBeUndefined();+ expect(actor?.ipAddress).toBe('203.0.113.44');+ });+ });+it('admits an unrestricted key on a @RequireUnscopedKey route', async () => {reflector.getAllAndOverride.mockReturnValueOnce(false) // not publicdiff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex 115f798b7..bff900ee1 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -76,6 +76,18 @@ export class ApiKeyGuard implements CanActivate {// Validate API keyconst apiKey = await this.authService.validateApiKey(apiKeyHeader, clientIp, sessionId);+ // Stamp the resolved actor into the per-request async context so downstream audit log writes —+ // which fire from services deep in the call stack without DI access to the key — can attribute+ // the action to this key + IP. Without this every audit row's apiKey/ipAddress column is blank+ // because call sites pass only { sessionId } etc.+ //+ // Stamped HERE, the moment the key is known, rather than after the authorization checks below:+ // both of those throw, and the catch that audits the denial cannot see `apiKey` (it is a const+ // inside this method). Stamping afterwards meant every 403 the guard raised was recorded against+ // an IP alone — behind NAT or a proxy without TRUSTED_PROXIES that IP is common to every tenant,+ // so the operator could see that a key had been denied but not which one to revoke.+ setRequestActor({ apiKeyId: apiKey.id, apiKeyName: apiKey.name, ipAddress: clientIp });+if (requiredRole && !this.authService.hasPermission(apiKey, requiredRole)) {throw new ForbiddenException(`Insufficient permissions. Required: ${requiredRole}`);}@@ -98,12 +110,6 @@ export class ApiKeyGuard implements CanActivate {// ops) reuse the already-resolved value instead of re-deriving it.(request as Request & { clientIp?: string }).clientIp = clientIp;- // Stamp the resolved actor into the per-request async context so downstream audit log writes —- // which fire from services deep in the call stack without DI access to the key — can attribute- // the action to this key + IP. Without this every audit row's apiKey/ipAddress column is blank- // because call sites pass only { sessionId } etc.- setRequestActor({ apiKeyId: apiKey.id, apiKeyName: apiKey.name, ipAddress: clientIp });-return true;}