Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): harden auth surfaces (WS credential, MCP default, non-REST audit) (#601)
Yudhi Armyndharis7b5a26f490da
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex df53fe608..c1d0bf148 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -20,7 +20,7 @@ A global API-key guard protects every route unless it is explicitly marked **pubX-API-Key: owa_k1_your-api-key-here```-> **REST auth is header-only.** A query-parameter API key is **not** accepted on REST routes. The only place an `?apiKey=` query value is honoured is the WebSocket (Socket.IO) handshake — see §6.5 Real-time API — which accepts the key via the handshake `auth.apiKey` field, the `X-API-Key` header, or an `?apiKey=` query string. Do not put the key in a REST URL.+> **Auth is header-only (never in a URL).** A query-parameter API key is **not** accepted anywhere. REST routes take the key via the `X-API-Key` header; the WebSocket (Socket.IO) handshake — see §6.5 Real-time API — accepts it via the handshake `auth.apiKey` field or the `X-API-Key` header. The former `?apiKey=` query fallback was **removed** (it leaked the credential into proxy/access logs). Never put the key in a URL.The metrics endpoint is the lone exception to the API-key scheme: it authenticates with `Authorization: Bearer <METRICS_TOKEN>` instead of `X-API-Key`.@@ -4332,7 +4332,7 @@ MCP Streamable-HTTP / JSON-RPC 2.0 transport that exposes the agent-tool registrKey facts:- **Path is exactly `POST /mcp` — no `/api` prefix.** The global `api` prefix applies only to Nest controllers; this route is mounted straight on Express.- Gated by **`MCP_ENABLED=true`**. When off, the module/route is never mounted and `POST /mcp` returns `404`.-- `MCP_READONLY=true` registers only read-tier tools. Per-key sliding-window rate limit: `MCP_RATE_LIMIT_MAX` (default 60) per `MCP_RATE_LIMIT_WINDOW_MS` (default 60000).+- MCP is **read-only by default**: only read-tier tools are registered unless you set `MCP_READONLY=false` to expose write tools. Per-key sliding-window rate limit: `MCP_RATE_LIMIT_MAX` (default 60) per `MCP_RATE_LIMIT_WINDOW_MS` (default 60000).- Stateless transport (no SSE/session id for normal calls).**Request body** — JSON-RPC 2.0 envelope (validated by the MCP SDK, **not** the Nest ValidationPipe)@@ -4376,11 +4376,12 @@ Point a Socket.IO client at `<host>:2785` with path-less namespace `/events`:ws://<host>:2785/events (or wss:// behind TLS)```-The client must authenticate during the Socket.IO handshake. Three sources are accepted, in this precedence order:+The client must authenticate during the Socket.IO handshake. Two sources are accepted, in this precedence order:1. **Handshake `auth` (recommended)** — `io(url, { auth: { apiKey } })`. Not written to URLs or access logs.2. **Header** — `x-api-key: <key>`.-3. **Query param (deprecated fallback)** — `?apiKey=<key>`. The key leaks into access logs; avoid in production.++> The former `?apiKey=<key>` query fallback was **removed** — it leaked the credential into proxy/access logs. Pass the key via the handshake `auth` field or the `x-api-key` header only.If no key is supplied, or validation fails, the server emits an `error` message (`code: "UNAUTHORIZED"`) on the `message` event and immediately disconnects the socket. CORS for the namespace reuses the HTTP `CORS_ORIGINS` policy (dev allows any origin; production uses the allowlist).diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.mdindex 05acbaf5b..fd607f377 100644--- a/docs/24-mcp-integration.md+++ b/docs/24-mcp-integration.md@@ -22,7 +22,7 @@| Capability | Status | Notes ||-----------|--------|-------|-| **Read-only mode** | ✅ Implemented | `MCP_READONLY=true` mounts read tools only |+| **Read-only mode** | ✅ Implemented | **Default read-only**; set `MCP_READONLY=false` to expose write tools || **OAuth 2.1 (public exposure)** | 🔜 Planned | Static API key is used today (suitable for self-hosted/internal) || **Agent-action audit provenance** | 🔜 Planned | Mark audited actions as agent-initiated || **Env-tunable rate limits** | ✅ Implemented | `MCP_RATE_LIMIT_MAX` / `MCP_RATE_LIMIT_WINDOW_MS` |@@ -134,8 +134,10 @@ These are destructive, privileged, or have no agent use case.### Read-only mode-Set `MCP_READONLY=true` to mount **only** `tier: 'read'` tools. This is the recommended-posture when an agent only needs to observe.+The server is **read-only by default** — it mounts **only** `tier: 'read'` tools unless you explicitly+opt in to write tools with `MCP_READONLY=false`. Any other value (or leaving it unset) keeps the safe+read-only posture, so enabling MCP never silently exposes state-changing tools. Set `MCP_READONLY=false`+only when an agent genuinely needs to send messages / mutate state.## 24.5 Authentication & Security@@ -170,7 +172,7 @@ posture when an agent only needs to observe.```bashMCP_ENABLED=true npm run start:prod # or set MCP_ENABLED in your .env / compose# optional:-MCP_READONLY=true # read tools only+MCP_READONLY=false # expose write tools (default is read-only when unset)MCP_RATE_LIMIT_MAX=60 # max tool calls per key per window (default 60)MCP_RATE_LIMIT_WINDOW_MS=60000 # sliding window in ms (default 60000 = 1 min)MCP_IP_RATE_LIMIT_MAX=120 # pre-auth per-IP request cap per window (default 120)diff --git a/src/modules/auth/role-coverage.spec.ts b/src/modules/auth/role-coverage.spec.tsnew file mode 100644index 000000000..16d3a3cf1--- /dev/null+++ b/src/modules/auth/role-coverage.spec.ts@@ -0,0 +1,18 @@+import 'reflect-metadata';+import { REQUIRED_ROLE_KEY } from './decorators/auth.decorators';+import { ApiKeyRole } from './entities/api-key.entity';+import { IntegrationInstanceController } from '../integration/integration-instance.controller';+import { RedriveController } from '../integration/redrive.controller';++// The dashboard's client-side role (seeded from localStorage) is cosmetic UX only — the ACTUAL+// authorization boundary is the backend @RequireRole guard. These assertions lock that the sensitive+// ADMIN-only integration provisioning / redrive surfaces are role-gated server-side at the class level,+// so a tampered client role can never reach them regardless of what the browser claims.+describe('admin controller role coverage (server-side authorization is the real gate)', () => {+ it.each([+ ['IntegrationInstanceController', IntegrationInstanceController],+ ['RedriveController', RedriveController],+ ])('%s requires the ADMIN role at the class level', (_name, controller) => {+ expect(Reflect.getMetadata(REQUIRED_ROLE_KEY, controller)).toBe(ApiKeyRole.ADMIN);+ });+});diff --git a/src/modules/events/events.gateway.spec.ts b/src/modules/events/events.gateway.spec.tsindex 46e89bf8e..431d45fab 100644--- a/src/modules/events/events.gateway.spec.ts+++ b/src/modules/events/events.gateway.spec.ts@@ -2,6 +2,8 @@ import { UnauthorizedException } from '@nestjs/common';import { Socket } from 'socket.io';import { EventsGateway, isSessionSubscriptionAllowed } from './events.gateway';import { AuthService } from '../auth/auth.service';+import { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';import { SUBSCRIBABLE_EVENTS, buildRoomName } from './dto/ws-messages.dto';import type { WSClientMessage, WSErrorResponse, WSSubscribedResponse, WSEventMessage } from './dto/ws-messages.dto';import { WEBHOOK_RESERVED_EVENTS } from '../webhook/dto/webhook.dto';@@ -31,7 +33,12 @@ describe('isSessionSubscriptionAllowed (WS session-scope enforcement)', () => {interface MockSocket {id: string;- handshake: { headers: Record<string, string>; query: Record<string, string>; auth: { apiKey?: string } };+ handshake: {+ headers: Record<string, string>;+ query: Record<string, string>;+ auth: { apiKey?: string };+ address: string;+ };data: Record<string, unknown>;emit: jest.Mock;disconnect: jest.Mock;@@ -45,7 +52,7 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {const makeSocket = (auth: { apiKey?: string } = {}): MockSocket => ({id: 'sock-1',- handshake: { headers: {}, query: {}, auth },+ handshake: { headers: {}, query: {}, auth, address: '203.0.113.5' },data: {},emit: jest.fn(),disconnect: jest.fn(),@@ -56,9 +63,12 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {const subscribeMsg = (sessionId: string, events: string[]): WSClientMessage =>({ type: 'subscribe', sessionId, events, requestId: 'r1' }) as unknown as WSClientMessage;+ let auditService: { logWarn: jest.Mock };+beforeEach(() => {authService = { validateApiKey: jest.fn() };- gateway = new EventsGateway(authService as unknown as AuthService);+ auditService = { logWarn: jest.fn().mockResolvedValue(null) };+ gateway = new EventsGateway(authService as unknown as AuthService, auditService as unknown as AuditService);});it('rejects a connection with no API key (and never calls validate)', async () => {@@ -68,6 +78,24 @@ describe('EventsGateway connection auth + subscribe re-validation', () => {expect(authService.validateApiKey).not.toHaveBeenCalled();});+ it('does NOT accept the API key from the query string (credential must not travel in the URL)', async () => {+ const sock = makeSocket({});+ sock.handshake.query.apiKey = 'leaky-key-in-url';+ await gateway.handleConnection(asSocket(sock));+ expect(authService.validateApiKey).not.toHaveBeenCalled(); // query key ignored → treated as missing+ expect(sock.disconnect).toHaveBeenCalled();+ });++ it('audits a rejected WebSocket auth attempt (forensic parity with the REST guard)', async () => {+ authService.validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));+ const sock = makeSocket({ apiKey: 'bad' });+ await gateway.handleConnection(asSocket(sock));+ expect(auditService.logWarn).toHaveBeenCalledWith(+ AuditAction.API_KEY_AUTH_FAILED,+ expect.objectContaining({ ipAddress: '203.0.113.5', metadata: { surface: 'websocket' } }),+ );+ });+it('rejects a connection when validateApiKey throws (the real auth-failure contract)', async () => {authService.validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));const sock = makeSocket({ apiKey: 'bad' });diff --git a/src/modules/events/events.gateway.ts b/src/modules/events/events.gateway.tsindex ab0993f24..99ac7f42c 100644--- a/src/modules/events/events.gateway.ts+++ b/src/modules/events/events.gateway.ts@@ -11,6 +11,8 @@ import {import { Server, Socket } from 'socket.io';import { Logger } from '@nestjs/common';import { AuthService } from '../auth/auth.service';+import { AuditService } from '../audit/audit.service';+import { AuditAction } from '../audit/entities/audit-log.entity';import { resolveCorsPolicy } from '../../config/bootstrap-security';/**@@ -64,23 +66,28 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGateprivate logger = new Logger('EventsGateway');- constructor(private readonly authService: AuthService) {}+ constructor(+ private readonly authService: AuthService,+ private readonly auditService: AuditService,+ ) {}afterInit() {this.logger.log('WebSocket Gateway initialized');}async handleConnection(client: Socket) {- // Prefer Socket.IO's `auth` field (not logged in URLs), then the header; the query- // param is a deprecated transition fallback (the key leaks into access logs).+ // Accept the key only via Socket.IO's `auth` field or the header — never the query string, which+ // leaks the credential into proxy/access logs. (The deprecated `?apiKey=` fallback was removed.)const handshakeAuth = client.handshake.auth as { apiKey?: string } | undefined;- const apiKey =- handshakeAuth?.apiKey ||- (client.handshake.headers['x-api-key'] as string) ||- (client.handshake.query.apiKey as string);+ const apiKey = handshakeAuth?.apiKey || (client.handshake.headers['x-api-key'] as string);if (!apiKey) {this.logger.warn(`Client ${client.id} rejected: No API key provided`);+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: client.handshake.address,+ metadata: { surface: 'websocket' },+ errorMessage: 'missing API key',+ });client.emit('message', this.createError('UNAUTHORIZED', 'API key required'));client.disconnect();return;@@ -100,6 +107,13 @@ export class EventsGateway implements OnGatewayInit, OnGatewayConnection, OnGatethis.logger.warn(`Client ${client.id} rejected: Auth error`, {error: error instanceof Error ? error.message : String(error),});+ // Audit the rejected credential like the REST guard does, so probing over the WS surface leaves+ // a forensic trail too. Fire-and-forget: audit logging must never affect the rejection path.+ void this.auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {+ ipAddress: client.handshake.address,+ metadata: { surface: 'websocket' },+ errorMessage: error instanceof Error ? error.message : String(error),+ });client.emit('message', this.createError('UNAUTHORIZED', 'Authentication failed'));client.disconnect();}diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.tsindex f4e9dbc16..7b2267e27 100644--- a/src/modules/mcp/mcp.server.spec.ts+++ b/src/modules/mcp/mcp.server.spec.ts@@ -1,7 +1,39 @@import type { Request, Response } from 'express';-import { createIpThrottle } from './mcp.server';+import { createIpThrottle, resolveMcpReadOnly } from './mcp.server';import { KeyRateLimiter } from './mcp-rate-limit';+describe('resolveMcpReadOnly (secure-by-default MCP read-only flag)', () => {+ const prev = process.env.MCP_READONLY;+ afterEach(() => {+ if (prev === undefined) delete process.env.MCP_READONLY;+ else process.env.MCP_READONLY = prev;+ });++ it('defaults to read-only when MCP_READONLY is unset (write tools NOT exposed by default)', () => {+ delete process.env.MCP_READONLY;+ expect(resolveMcpReadOnly()).toBe(true);+ });++ it('exposes write tools only on an explicit MCP_READONLY=false opt-out', () => {+ process.env.MCP_READONLY = 'false';+ expect(resolveMcpReadOnly()).toBe(false);+ });++ it('stays read-only for any other value', () => {+ process.env.MCP_READONLY = 'true';+ expect(resolveMcpReadOnly()).toBe(true);+ process.env.MCP_READONLY = 'yes';+ expect(resolveMcpReadOnly()).toBe(true);+ });++ it('an explicit options.readOnly wins over the env', () => {+ process.env.MCP_READONLY = 'false';+ expect(resolveMcpReadOnly(true)).toBe(true);+ delete process.env.MCP_READONLY;+ expect(resolveMcpReadOnly(false)).toBe(false);+ });+});+// The MCP mount is raw Express (outside the Nest guard pipeline) and the per-key limiter only fires// after key validation, so a missing/invalid-key flood would otherwise reach a DB lookup unthrottled.// createIpThrottle gates by resolved client IP BEFORE auth and answers with a JSON-RPC 429.diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.tsindex cb96b2db2..8a9f3c791 100644--- a/src/modules/mcp/mcp.server.ts+++ b/src/modules/mcp/mcp.server.ts@@ -124,6 +124,16 @@ export function createIpThrottle(ipRateLimiter: KeyRateLimiter): RequestHandler};}+/**+ * Resolve the MCP read-only flag with a SECURE default: read-only unless the operator explicitly opts+ * out with MCP_READONLY=false. Previously an unset MCP_READONLY defaulted to read-WRITE, silently+ * exposing state-changing tools (send messages, group ops) to any MCP caller the moment MCP_ENABLED+ * was on. An explicit `options.readOnly` (tests / programmatic mounts) still wins.+ */+export function resolveMcpReadOnly(optionsReadOnly?: boolean): boolean {+ return optionsReadOnly ?? process.env.MCP_READONLY !== 'false';+}+export function mountMcpServer(httpAdapter: HttpAdapter,registry: ToolRegistryService,@@ -134,7 +144,7 @@ export function mountMcpServer(): void {const basePath = (options.basePath ?? '/mcp').replace(/\/$/, '') || '/mcp';const serverInfo = options.serverInfo ?? { name: 'openwa', version: '0.0.0' };- const readOnly = options.readOnly ?? process.env.MCP_READONLY === 'true';+ const readOnly = resolveMcpReadOnly(options.readOnly);// Eagerly compute the tool list at mount time to validate the registry is populated// and to emit the log line once. The actual McpServer is re-created per request to