Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(mcp)!: require a valid API key on every MCP request

Yudhi Armyndharis281e1da76dbe
diff --git a/docs/04-security-design.md b/docs/04-security-design.md
index 2c8f248f2..a04286234 100644
--- a/docs/04-security-design.md
+++ b/docs/04-security-design.md
@@ -280,7 +280,7 @@ Each window is counted **per route handler per client IP** (the IP resolved thro
TTL values are in milliseconds. The `/api/metrics` and `/api/health*` routes are exempt (`@SkipThrottle`); `/api/health` still looks up at most 30 failed key presentations per client per minute, and past that answers without `version` and without a key lookup. To enforce tighter per-route limits, lower the global windows or add a limiter at your reverse proxy.
-An IPv6 client is keyed on its /64, so rotating addresses inside one allocation does not mint fresh buckets. The same key is used by every other per-client limit: the MCP and Bull Board pre-auth throttles, the WebSocket limits below, the per-client share of the in-flight body budget, the health route's key-lookup budget and auth-failure audit bound, and the REST and queue-dashboard auth-failure audit bound. `allowedIps` matching and audit rows still see the full address.
+An IPv6 client is keyed on its /64, so rotating addresses inside one allocation does not mint fresh buckets. The same key is used by every other per-client limit: the MCP and Bull Board pre-auth throttles, the WebSocket limits below, the per-client share of the in-flight body budget, the health route's key-lookup budget and auth-failure audit bound, and the REST, queue-dashboard and MCP auth-failure audit bound. `allowedIps` matching and audit rows still see the full address.
### Response on limit
@@ -502,7 +502,7 @@ flowchart TB
### Security Alerts
-> **Not implemented.** There is no alerting or automatic temp-block subsystem; the table below is a design target, not shipped behavior. The signals do get recorded: rejected authentication and WebSocket rate-limit violations write persisted audit rows, and an IP-restricted key used from a disallowed IP also emits a `logger.warn`; but nothing acts on them. A REST or queue-dashboard rejection that names no stored key (missing or unknown) is capped at 10 rows per client IP per minute; a rejection of a stored key (revoked, expired, IP or session refused, insufficient role) is recorded every time there. The public `/api/health` route bounds every auth-failure row it writes, stored key or not, at 10 per client IP per minute. Rate-limit violations are sampled. Forward the audit log / application log to your SIEM to build these alerts.
+> **Not implemented.** There is no alerting or automatic temp-block subsystem; the table below is a design target, not shipped behavior. The signals do get recorded: rejected authentication and WebSocket rate-limit violations write persisted audit rows, and an IP-restricted key used from a disallowed IP also emits a `logger.warn`; but nothing acts on them. A REST, queue-dashboard or MCP rejection that names no stored key (missing or unknown) is capped at 10 rows per client IP per minute; a rejection of a stored key (revoked, expired, IP or session refused, insufficient role) is recorded every time there. The public `/api/health` route bounds every auth-failure row it writes, stored key or not, at 10 per client IP per minute. Rate-limit violations are sampled. Forward the audit log / application log to your SIEM to build these alerts.
| Event | Severity | Intended action (roadmap) |
| -------------------- | -------- | ------------------------- |
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 30878ae83..671259d54 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -607,9 +607,9 @@ CREATE INDEX "IDX_c69efb19bf127c97e6740ad530" ON audit_logs("createdAt");
**Audit actions** are an enum (`AuditAction`) spanning API-key lifecycle (`api_key_created`,
`api_key_updated`, `api_key_used`, `api_key_revoked`, `api_key_deleted`, `api_key_auth_failed`, capped
-at 10 rows per client IP per minute for a REST or queue-dashboard rejection that names no stored key,
-where a rejection of a stored key is recorded every time, and at 10 per client IP per minute for any
-rejection on `/api/health`), session
+at 10 rows per client IP per minute for a REST, queue-dashboard or MCP rejection that names no stored
+key, where a rejection of a stored key is recorded every time, and at 10 per client IP per minute for
+any rejection on `/api/health`), session
lifecycle (`session_created`, `session_started`, `session_stopped`, `session_force_killed`,
`session_logged_out`, `session_deleted`, `session_qr_generated`, `session_connected`,
`session_disconnected`, `session_config_updated`), WhatsApp-imposed account restrictions (`session_restricted`,
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.md
index e8b492796..6e38ee6ea 100644
--- a/docs/06-api-specification.md
+++ b/docs/06-api-specification.md
@@ -6275,7 +6275,7 @@ such an instance, so its rows could only fail again. Re-enable the instance to r
MCP Streamable-HTTP / JSON-RPC 2.0 transport that exposes the agent-tool registry over the Model Context Protocol. **This is a transport, not a REST resource** — there is no NestJS controller, no DTO, and no `{success,data}` shape.
-**Auth:** API key — sent as `X-Api-Key: <key>` **or** `Authorization: Bearer <key>`. Auth is enforced **per tool call** inside the MCP layer (not by the global Nest guard), so an auth failure surfaces in-band, not as an HTTP `401`.
+**Auth:** API key — sent as `X-Api-Key: <key>` **or** `Authorization: Bearer <key>`. Every request, including `initialize` and `tools/list`, needs a valid key: a missing, unknown, revoked or expired key, or a key carrying `allowedIps` (there is no genuine client IP on this mount), is refused before any MCP method runs, with an HTTP error, a JSON-RPC error body (`code: -32000`, `id: null`) and `WWW-Authenticate: Bearer` on a `401`. The role, session and chat checks run **per tool call** inside the MCP layer (not by the global Nest guard) and surface in-band.
Key facts:
@@ -6316,9 +6316,9 @@ Key facts:
}
```
-For `tools/call` the result is an MCP `CallToolResult` (`content` array of `text` or embedded base64 `resource` items — payloads over 4096 bytes become a `resource`). **Tool-level failures are returned in-band as `CallToolResult` with `isError:true`** (HTTP stays 200), including missing/invalid API key (`name:'UnauthorizedException'`) and rate-limit hits (`message:'MCP rate limit exceeded'`).
+For `tools/call` the result is an MCP `CallToolResult` (`content` array of `text` or embedded base64 `resource` items — payloads over 4096 bytes become a `resource`). **Tool-level failures are returned in-band as `CallToolResult` with `isError:true`** (HTTP stays 200), including a role, session or chat refusal (`name:'ForbiddenException'`) and rate-limit hits (`message:'MCP rate limit exceeded'`).
-**Errors:** in-band JSON-RPC errors `-32601` (unknown method), `-32602` (invalid params / unknown tool), `-32700` (parse error), all at HTTP 200 · `500` only if the transport throws before headers are sent · `404` when `MCP_ENABLED` is not `true`
+**Errors:** `401` with a JSON-RPC error body for a missing or refused key · in-band JSON-RPC errors `-32601` (unknown method), `-32602` (invalid params / unknown tool), `-32700` (parse error), all at HTTP 200 · `500` if the key lookup fails for a reason other than a refused key, or if the transport throws before headers are sent · `404` when `MCP_ENABLED` is not `true`
> The full catalog of MCP tools (names, tiers, schemas) is documented separately — see **doc 24, MCP Integration**. This section documents only the transport endpoint.
diff --git a/docs/07-api-collection.md b/docs/07-api-collection.md
index 452e0811b..48465d31f 100644
--- a/docs/07-api-collection.md
+++ b/docs/07-api-collection.md
@@ -1651,7 +1651,7 @@ curl -X DELETE "$BASE/api/plugins/chat-flow" \
#### POST /mcp
-MCP JSON-RPC 2.0 transport (no `/api` prefix; gated by `MCP_ENABLED=true`). The API key goes via `X-Api-Key` or `Authorization: Bearer`; auth is enforced per tool call. The server is **read-only by default** — write tools such as `MessageSendText` are only mounted when `MCP_READONLY=false`. See doc 24 for the tool catalog.
+MCP JSON-RPC 2.0 transport (no `/api` prefix; gated by `MCP_ENABLED=true`). The API key goes via `X-Api-Key` or `Authorization: Bearer` on every request, `initialize` and `tools/list` included (a missing or refused key answers `401`); role and session scope are checked per tool call. The server is **read-only by default** — write tools such as `MessageSendText` are only mounted when `MCP_READONLY=false`. See doc 24 for the tool catalog.
```bash
# Initialize handshake
diff --git a/docs/24-mcp-integration.md b/docs/24-mcp-integration.md
index 5197ab0b0..5fafe77ab 100644
--- a/docs/24-mcp-integration.md
+++ b/docs/24-mcp-integration.md
@@ -97,7 +97,13 @@ flowchart LR
Invoker --> Services[Existing module services]
```
-A tool call flows through four steps, in this order:
+Every `POST /mcp`, including `initialize` and `tools/list`, first passes the pre-auth per-IP
+throttle and then a key gate: a missing, unknown, revoked or expired key, or one the gate
+otherwise refuses, gets an HTTP error with a JSON-RPC body (`401` carries
+`WWW-Authenticate: Bearer`) and an `API_KEY_AUTH_FAILED` audit row (a missing or unknown
+key's row is capped at 10 per client IP a minute, a budget shared with REST and the queue
+dashboard), and no MCP method runs.
+Past the gate, a tool call flows through four steps, in this order:
1. **Key extraction.** The adapter reads the API key from the `X-API-Key` header or
`Authorization: Bearer …`.
@@ -158,6 +164,9 @@ only when an agent genuinely needs to send messages / mutate state.
## 24.5 Authentication & Security
+- **Every request needs a key.** The mount refuses any `POST /mcp` without a valid key before
+ the transport answers, so the server version and tool catalogue are never served to an
+ unauthenticated caller. Role, session and chat scope are still checked per tool call.
- **Same authorization as REST.** Tool calls are authorized by `AuthService` — role and
per-session `allowedSessions` scoping are enforced identically to REST. A key scoped to
one session cannot act on another.
@@ -165,8 +174,8 @@ only when an agent genuinely needs to send messages / mutate state.
MCP client (`OPERATOR` role at most). The plaintext key is shown once on creation; to
rotate, create a new key and delete the old one.
- **No IP allow-list over MCP.** There is no genuine client IP on a tool call, so a key
- that carries an `allowedIps` list will be rejected. Use a key without `allowedIps` for
- MCP.
+ that carries an `allowedIps` list is refused at the mount. Use a key without `allowedIps`
+ for MCP.
- **Rate limiting.** A per-key limiter (keyed by the _authenticated_ key id) bounds tool
calls. The key map is capped (approximate-LRU eviction at 50,000 keys), so a
distinct-key flood cannot grow process memory without limit. This is independent of
diff --git a/src/modules/audit/auth-failure-audit-limiter.ts b/src/modules/audit/auth-failure-audit-limiter.ts
index 6b6e80340..f83233014 100644
--- a/src/modules/audit/auth-failure-audit-limiter.ts
+++ b/src/modules/audit/auth-failure-audit-limiter.ts
@@ -2,13 +2,13 @@ import { SlidingWindowLimiter } from '../events/ws-rate-limit';
import { limiterKeyForIp } from '../../common/utils/ip';
/**
- * Per-IP budget for API_KEY_AUTH_FAILED rows written by the REST guard and the Bull Board mount for a
- * rejection that resolved no key (UnresolvedApiKeyException: no key, or a key that matches no row).
- * Such a rejection costs the caller nothing, and the throttler counts per route handler, so without
- * this bound one source could write audit rows as fast as it can send requests. One module-level
- * instance so both surfaces draw on a single budget per client: 10 rows a minute, the same bound the
- * health route applies to its own probes. A rejection of a stored key (revoked, expired, IP or
- * session refused, or a 403) is not charged here; it is always audited.
+ * Per-IP budget for API_KEY_AUTH_FAILED rows written by the REST guard, the Bull Board mount and the
+ * MCP key gate for a rejection that resolved no key (UnresolvedApiKeyException: no key, or a key that
+ * matches no row). Such a rejection costs the caller nothing, and the throttler counts per route
+ * handler, so without this bound one source could write audit rows as fast as it can send requests.
+ * One module-level instance so all three surfaces draw on a single budget per client: 10 rows a
+ * minute, the same bound the health route applies to its own probes. A rejection of a stored key
+ * (revoked, expired, IP or session refused, or a 403) is not charged here; it is always audited.
*/
const limiter = new SlidingWindowLimiter(10, 60_000);
diff --git a/src/modules/auth/api-key-usage-write-scope.spec.ts b/src/modules/auth/api-key-usage-write-scope.spec.ts
index 205c05c12..35f6e80f5 100644
--- a/src/modules/auth/api-key-usage-write-scope.spec.ts
+++ b/src/modules/auth/api-key-usage-write-scope.spec.ts
@@ -179,6 +179,7 @@ describe('validateApiKey entrypoint coverage', () => {
['modules/auth/guards/api-key.guard.ts', 'REST route guard'],
['modules/events/events.gateway.ts', 'websocket connect and per-subscribe re-validation'],
['modules/health/health.controller.ts', 'version disclosure on the public health check'],
+ ['modules/mcp/mcp.server.ts', 'MCP mount key gate'],
]);
/** Where validateApiKey is declared, which is not a caller. */
diff --git a/src/modules/auth/auth.service.spec.ts b/src/modules/auth/auth.service.spec.ts
index 9fdf4ef6f..ea02d42e5 100644
--- a/src/modules/auth/auth.service.spec.ts
+++ b/src/modules/auth/auth.service.spec.ts
@@ -708,6 +708,19 @@ describe('AuthService', () => {
await expect(service.validateApiKey(` ${rawKey}\n`)).resolves.toMatchObject({ id: key.id });
});
+ it('leaves the usage stats alone when the caller opts out of recording', async () => {
+ const rawKey = 'gate-key';
+ const key = createMockApiKey({ keyHash: hashKey(rawKey), lastUsedAt: new Date(Date.now() - 5 * 60_000) });
+ (repository.findOne as jest.Mock).mockResolvedValue(key);
+
+ const result = await service.validateApiKey(rawKey, undefined, undefined, { recordUsage: false });
+
+ expect(result.id).toBe(key.id);
+ expect(result.usageCount).toBe(0);
+ expect(repository.update).not.toHaveBeenCalled();
+ expect(repository.increment).not.toHaveBeenCalled();
+ });
+
it('coalesces the usage-stat write within the throttle window', async () => {
const rawKey = 'recent-key';
const key = createMockApiKey({ keyHash: hashKey(rawKey), lastUsedAt: new Date(), usageCount: 5 });
diff --git a/src/modules/auth/auth.service.ts b/src/modules/auth/auth.service.ts
index b3499b6ca..1d9bc26f2 100644
--- a/src/modules/auth/auth.service.ts
+++ b/src/modules/auth/auth.service.ts
@@ -453,7 +453,12 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
return this.apiKeyRepository.findBy({ id: In(ids) });
}
- async validateApiKey(rawKey: string, clientIp?: string, sessionId?: string): Promise<ApiKey> {
+ async validateApiKey(
+ rawKey: string,
+ clientIp?: string,
+ sessionId?: string,
+ { recordUsage = true }: { recordUsage?: boolean } = {},
+ ): Promise<ApiKey> {
// Trim before hashing so every surface agrees on what the credential is. HTTP already strips
// surrounding whitespace from header values, so a pasted key with a stray space/newline
// authenticates over REST but fails on the WebSocket handshake (the CONNECT payload carries the
@@ -501,8 +506,9 @@ export class AuthService implements OnModuleInit, OnModuleDestroy {
}
}
- // Advisory stats only; the tracker coalesces the write and never throws.
- await this.usageTracker.record(apiKey);
+ // Advisory stats only; the tracker coalesces the write and never throws. A caller that validates
+ // the same key again later in the request (the MCP mount gate) opts out, so a request counts once.
+ if (recordUsage) await this.usageTracker.record(apiKey);
return apiKey;
}
diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.ts
index b7bc12ce6..b10f12a56 100644
--- a/src/modules/mcp/mcp.server.spec.ts
+++ b/src/modules/mcp/mcp.server.spec.ts
@@ -1,7 +1,8 @@
import { BadRequestException, ForbiddenException, UnauthorizedException } from '@nestjs/common';
+import { UnresolvedApiKeyException } from '../auth/auth.service';
import type { Request, Response } from 'express';
import { z } from 'zod';
-import { auditMcpAuthFailure, createIpThrottle, mountMcpServer, resolveMcpReadOnly } from './mcp.server';
+import { auditMcpAuthFailure, createIpThrottle, createKeyGate, mountMcpServer, resolveMcpReadOnly } from './mcp.server';
import { KeyRateLimiter } from './mcp-rate-limit';
import { AuditAction } from '../audit/entities/audit-log.entity';
import type { AnyToolDescriptor } from '../../core/agent-tools/tool-descriptor';
@@ -224,12 +225,127 @@ describe('auditMcpAuthFailure (MCP auth-failure audit trail, mirrors REST ApiKey
});
});
-// mountMcpServer is raw Express: every POST builds a fresh McpServer + transport and dispatches via
-// transport.handleRequest(req, res, req.body). These tests drive that route handler directly with
-// mock req/res. Auth is NOT a mount gate — it runs per tool call inside invokeTool (via the callback
-// registered with the per-request server), so a bad key is refused as a tool error result during the
-// dispatch, not as a rejected POST: transport.handleRequest is always reached once the IP throttle
-// and body parser have passed the request through.
+describe('createKeyGate (every MCP request needs a valid key)', () => {
+ type ResMock = { status: jest.Mock; json: jest.Mock; set: jest.Mock; statusCode?: number; body?: unknown };
+ const makeRes = (): ResMock => {
+ const res: ResMock = { status: jest.fn(), json: jest.fn(), set: jest.fn() };
+ res.status.mockImplementation((code: number) => {
+ res.statusCode = code;
+ return res;
+ });
+ res.json.mockImplementation((b: unknown) => {
+ res.body = b;
+ return res;
+ });
+ res.set.mockReturnValue(res);
+ return res;
+ };
+ const run = async (
+ validateApiKey: jest.Mock,
+ headers: Record<string, string> = {},
+ logWarn: jest.Mock = jest.fn(),
+ ip = '203.0.113.7',
+ ) => {
+ const gate = createKeyGate({ validateApiKey }, { logWarn });
+ const req = {
+ method: 'POST',
+ path: '/mcp',
+ headers,
+ socket: { remoteAddress: ip },
+ } as unknown as Request;
+ const res = makeRes();
+ const next = jest.fn();
+ await gate(req, res as unknown as Response, next);
+ return { res, next, logWarn };
+ };
+
+ it('refuses a request with no key before any lookup: 401, JSON-RPC body, audited within the IP budget', async () => {
+ const validateApiKey = jest.fn();
+ const { res, next, logWarn } = await run(validateApiKey);
+
+ expect(next).not.toHaveBeenCalled();
+ expect(validateApiKey).not.toHaveBeenCalled();
+ expect(res.statusCode).toBe(401);
+ expect(res.set).toHaveBeenCalledWith('WWW-Authenticate', 'Bearer');
+ expect(res.body).toEqual({ jsonrpc: '2.0', error: { code: -32000, message: 'Missing API key' }, id: null });
+ expect(logWarn).toHaveBeenCalledWith(
+ AuditAction.API_KEY_AUTH_FAILED,
+ expect.objectContaining({ ipAddress: '203.0.113.7', method: 'POST', path: '/mcp' }),
+ );
+ });
+
+ // The unauthenticated-row budget is a module-level singleton shared with the REST guard, so this
+ // test uses an IP no other test in this file uses.
+ it('writes at most 10 keyless rows a minute for one IP, and still records a revoked key after that', async () => {
+ const logWarn = jest.fn();
+ const ip = '198.51.100.91';
+ for (let i = 0; i < 11; i++) {
+ const { res, next } = await run(jest.fn(), {}, logWarn, ip);
+ expect(res.statusCode).toBe(401);
+ expect(next).not.toHaveBeenCalled();
+ }
+ expect(logWarn).toHaveBeenCalledTimes(10);
+
+ const revoked = jest.fn().mockRejectedValue(new UnauthorizedException('API key is revoked'));
+ const { res } = await run(revoked, { 'x-api-key': 'old-key' }, logWarn, ip);
+ expect(res.statusCode).toBe(401);
+ expect(logWarn).toHaveBeenCalledTimes(11);
+ expect(logWarn).toHaveBeenLastCalledWith(
+ AuditAction.API_KEY_AUTH_FAILED,
+ expect.objectContaining({ ipAddress: ip, errorMessage: 'API key is revoked' }),
+ );
+ });
+
+ it('refuses an unknown key with 401 and audits it', async () => {
+ const validateApiKey = jest.fn().mockRejectedValue(new UnresolvedApiKeyException('Invalid API key'));
+ const { res, next, logWarn } = await run(validateApiKey, { 'x-api-key': 'bad-key' });
+
+ expect(next).not.toHaveBeenCalled();
+ expect(validateApiKey).toHaveBeenCalledWith('bad-key', undefined, undefined, { recordUsage: false });
+ expect(res.statusCode).toBe(401);
+ expect(logWarn).toHaveBeenCalledWith(
+ AuditAction.API_KEY_AUTH_FAILED,
+ expect.objectContaining({ errorMessage: 'Invalid API key' }),
+ );
+ });
+
+ it.each([[{ 'x-api-key': 'good-key' }], [{ authorization: 'Bearer good-key' }]])(
+ 'passes a valid key through without a client IP or session (%j)',
+ async headers => {
+ const validateApiKey = jest.fn().mockResolvedValue({ id: 'k1' });
+ const { res, next } = await run(validateApiKey, headers);
+
+ expect(next).toHaveBeenCalledWith();
+ expect(validateApiKey).toHaveBeenCalledWith('good-key', undefined, undefined, { recordUsage: false });
+ expect(res.status).not.toHaveBeenCalled();
+ },
+ );
+
+ it('refuses a malformed Authorization header without a lookup', async () => {
+ const validateApiKey = jest.fn();
+ const { res, next } = await run(validateApiKey, { authorization: 'Bearer good-key extra' });
+
+ expect(next).not.toHaveBeenCalled();
+ expect(validateApiKey).not.toHaveBeenCalled();
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('answers 500, unaudited, when the key lookup itself fails', async () => {
+ const validateApiKey = jest.fn().mockRejectedValue(new Error('database is down'));
+ const { res, next, logWarn } = await run(validateApiKey, { 'x-api-key': 'good-key' });
+
+ expect(next).not.toHaveBeenCalled();
+ expect(res.statusCode).toBe(500);
+ expect(res.body).toEqual({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null });
+ expect(logWarn).not.toHaveBeenCalled();
+ });
+});
+
+// mountMcpServer is raw Express: every POST passes the IP throttle and the key gate, then builds a
+// fresh McpServer + transport and dispatches via transport.handleRequest(req, res, req.body). These
+// tests drive the terminal handler directly with mock req/res, past the gate. Role, session and chat
+// scope still run per tool call inside invokeTool (via the callback registered with the per-request
+// server), so a key refused there is answered as a tool error result during the dispatch.
// mcp.module.ts is pure Nest wiring (module registration + the raw-Express mount call), stays at 0%
// coverage, and is intentionally not a target.
describe('mountMcpServer (raw-Express request-handling path)', () => {
@@ -342,11 +458,41 @@ describe('mountMcpServer (raw-Express request-handling path)', () => {
}
});
- it('parses the body before the per-IP throttle so a batch is charged per message', () => {
+ it('parses the body before the per-IP throttle, and checks the key after the throttle', () => {
const h = mount();
- const [path, parser] = h.adapter.post.mock.calls[0] as unknown[];
+ const [path, parser, ...rest] = h.adapter.post.mock.calls[0] as unknown[];
expect(path).toBe('/mcp');
expect((parser as { name?: string }).name).toBe('jsonParser');
+ expect(rest).toHaveLength(3); // throttle, key gate, handler
+ });
+
+ it('refuses a keyless POST at the gate before any MCP server is built', async () => {
+ const h = mount();
+ const gate = (h.adapter.post.mock.calls[0] as unknown[])[3] as (
+ req: Request,
+ res: Response,
+ next: () => void,
+ ) => Promise<void>;
+ const res = { status: jest.fn(), json: jest.fn(), set: jest.fn() };
+ res.status.mockReturnValue(res);
+ res.set.mockReturnValue(res);
+ const next = jest.fn();
+ const body = { jsonrpc: '2.0', id: 1, method: 'initialize' };
+ await gate(
+ {
+ method: 'POST',
+ path: '/mcp',
+ headers: {},
+ body,
+ socket: { remoteAddress: '203.0.113.7' },
+ } as unknown as Request,
+ res as unknown as Response,
+ next,
+ );
+
+ expect(res.status).toHaveBeenCalledWith(401);
+ expect(next).not.toHaveBeenCalled();
+ expect(h.auditService.logWarn).toHaveBeenCalledWith(AuditAction.API_KEY_AUTH_FAILED, expect.anything());
});
it('dispatches the request to transport.handleRequest with the parsed body', async () => {
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index ae7956950..72a4d8a0d 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -9,7 +9,8 @@ import type { ServerNotification, ServerRequest } from '@modelcontextprotocol/sd
import express, { type Request, type RequestHandler, type Response } from 'express';
import { invokeTool } from '../../core/agent-tools/tool-invoker';
import type { ToolRegistryService } from '../../core/agent-tools/tool-registry.service';
-import type { AuthService } from '../auth/auth.service';
+import { UnresolvedApiKeyException, type AuthService } from '../auth/auth.service';
+import { allowUnauthenticatedAuditRow } from '../audit/auth-failure-audit-limiter';
import type { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { handleToolError, jsonToolResult, smartToolResult } from './tool-result';
@@ -30,9 +31,12 @@ export interface McpRequestContext {
path?: string;
}
-/** Extract the raw API key from MCP request headers. Accepts X-Api-Key or Bearer token. */
-function extractApiKey(extra: ToolExtra): string | undefined {
- const headers = extra.requestInfo?.headers ?? {};
+/**
+ * Extract the raw API key from request headers. Accepts X-Api-Key or Bearer token. The one parser for
+ * both the mount gate (Express headers) and the per-tool check (the SDK's request headers), so the two
+ * cannot disagree on what the credential is.
+ */
+function extractApiKey(headers: Record<string, string | string[] | undefined> = {}): string | undefined {
const xApiKey = headers['x-api-key'];
if (xApiKey) {
return Array.isArray(xApiKey) ? xApiKey[0] : xApiKey;
@@ -46,7 +50,9 @@ function extractApiKey(extra: ToolExtra): string | undefined {
* the Nest guard pipeline), so without this a credential-probing flood against /mcp leaves no forensic
* record. Records a WARN `API_KEY_AUTH_FAILED` for rejected/denied authentication attempts (401/403 only);
* non-auth errors (e.g. a 400 from bad tool input) are NOT audited — parity with the REST guard, which
- * only records Unauthorized/Forbidden. Fire-and-forget; best-effort (AuditService swallows insert errors).
+ * only records Unauthorized/Forbidden. A rejection that names no stored key (UnresolvedApiKeyException)
+ * draws on the per-IP budget the REST guard and Bull Board share; a stored key's rejection is always
+ * recorded. Fire-and-forget; best-effort (AuditService swallows insert errors).
*/
export function auditMcpAuthFailure(
auditService: Pick<AuditService, 'logWarn'> | undefined,
@@ -54,6 +60,9 @@ export function auditMcpAuthFailure(
reqContext: McpRequestContext,
): void {
if (!auditService) return;
+ if (error instanceof UnresolvedApiKeyException && !allowUnauthenticatedAuditRow(reqContext.ipAddress ?? '')) {
+ return;
+ }
if (error instanceof UnauthorizedException || error instanceof ForbiddenException) {
void auditService.logWarn(AuditAction.API_KEY_AUTH_FAILED, {
ipAddress: reqContext.ipAddress,
@@ -117,7 +126,7 @@ function buildServer(
},
},
async (input: Record<string, unknown>, extra: ToolExtra) => {
- const rawKey = extractApiKey(extra);
+ const rawKey = extractApiKey(extra.requestInfo?.headers);
try {
const result = await invokeTool(
tool,
@@ -156,6 +165,7 @@ export interface MountMcpServerOptions {
* at `POST {basePath}` (default `/mcp`), single-port.
*
* Tool handlers are built ONCE at mount time (closure over registry/authService/rateLimiter).
+ * Every POST passes the per-IP throttle and then the key gate before any MCP method runs.
* Per-request: mint a fresh McpServer + StreamableHTTPServerTransport, handle, tear down.
* Stateless (sessionIdGenerator: undefined): no session map; GET/DELETE answer 405.
* Creating a new McpServer per request is safe and avoids the single-transport constraint;
@@ -189,6 +199,39 @@ export function createIpThrottle(ipRateLimiter: KeyRateLimiter): RequestHandler
};
}
+/**
+ * Mount gate: every POST must carry a valid API key before the transport answers anything, including
+ * `initialize` (server version) and `tools/list` (tool catalogue). Runs after the per-IP throttle so a
+ * flood never reaches the key lookup. Validated with no client IP and no session, as the per-tool check
+ * does: a key with `allowedIps` is refused on MCP, and role, session and chat scope stay per tool call.
+ * Neither the per-key limiter nor the key's usage stats are charged here; invokeTool charges both per
+ * tool call, so a request counts once.
+ */
+export function createKeyGate(
+ authService: Pick<AuthService, 'validateApiKey'>,
+ auditService: Pick<AuditService, 'logWarn'> | undefined,
+): RequestHandler {
+ return async (req, res, next) => {
+ try {
+ const rawKey = extractApiKey(req.headers);
+ if (!rawKey) throw new UnresolvedApiKeyException('Missing API key');
+ await authService.validateApiKey(rawKey, undefined, undefined, { recordUsage: false });
+ } catch (err) {
+ if (err instanceof HttpException) {
+ auditMcpAuthFailure(auditService, err, resolveReqContext(req));
+ const status = err.getStatus();
+ if (status === 401) res.set('WWW-Authenticate', 'Bearer');
+ res.status(status).json({ jsonrpc: '2.0', error: { code: -32000, message: err.message }, id: null });
+ return;
+ }
+ logger.error('Error authenticating MCP request', err instanceof Error ? err.stack : String(err));
+ res.status(500).json({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal server error' }, id: null });
+ return;
+ }
+ next();
+ };
+}
+
/**
* 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
@@ -256,7 +299,13 @@ export function mountMcpServer(
// `limit` mirrors the same global cap for the same reason: without it a middleware reorder would
// silently leave this mount uncapped.
const bodyLimit = resolveBodyLimit(process.env.BODY_SIZE_LIMIT);
- adapter.post(basePath, express.json({ limit: bodyLimit, inflate: false }), createIpThrottle(ipRateLimiter), handler);
+ adapter.post(
+ basePath,
+ express.json({ limit: bodyLimit, inflate: false }),
+ createIpThrottle(ipRateLimiter),
+ createKeyGate(authService, auditService),
+ handler,
+ );
// Stateless transport: no standalone SSE stream and no session to delete. The Streamable HTTP spec
// requires a GET to be answered with a stream or 405, and SDK clients treat anything but 405 as an
// error on every connect. Routing these to the transport would open a stream (GET) or answer 200
diff --git a/test/mcp-auth.e2e-spec.ts b/test/mcp-auth.e2e-spec.ts
index ad20318ef..de543e47e 100644
--- a/test/mcp-auth.e2e-spec.ts
+++ b/test/mcp-auth.e2e-spec.ts
@@ -10,6 +10,8 @@ import request from 'supertest';
import type { App } from 'supertest/types';
import { AppModule } from '../src/app.module';
import { applyGlobalValidation } from '../src/config/app-validation';
+import { AuthService } from '../src/modules/auth/auth.service';
+import { ApiKeyRole } from '../src/modules/auth/entities/api-key.entity';
// --- MCP protocol helpers ---
@@ -52,6 +54,15 @@ function parseMcpResponse(res: { body: unknown; text: string }): Record<string,
describe('MCP server (e2e)', () => {
let app: INestApplication<App>;
+ let viewerKey: string;
+ let chatKey: string;
+ let ipKey: string;
+ const initialize = () =>
+ jsonRpcRequest('initialize', {
+ protocolVersion: '2025-11-25',
+ capabilities: {},
+ clientInfo: { name: 'test-client', version: '0.0.1' },
+ });
beforeAll(async () => {
const moduleFixture: TestingModule = await Test.createTestingModule({
@@ -61,6 +72,14 @@ describe('MCP server (e2e)', () => {
app = moduleFixture.createNestApplication();
applyGlobalValidation(app);
await app.init();
+
+ const authService = app.get(AuthService);
+ viewerKey = (await authService.createApiKey({ name: 'e2e-mcp-viewer', role: ApiKeyRole.VIEWER })).rawKey;
+ chatKey = (
+ await authService.createApiKey({ name: 'e2e-mcp-chat', role: ApiKeyRole.VIEWER, allowedChats: ['[email protected]'] })
+ ).rawKey;
+ ipKey = (await authService.createApiKey({ name: 'e2e-mcp-ip', role: ApiKeyRole.VIEWER, allowedIps: ['127.0.0.1'] }))
+ .rawKey;
}, 30_000);
afterAll(async () => {
@@ -72,19 +91,14 @@ describe('MCP server (e2e)', () => {
});
// ---------------------------------------------------------------------------
- // 1. MCP endpoint is reachable — initialize succeeds
+ // 1. MCP endpoint is reachable with a key: initialize succeeds
// ---------------------------------------------------------------------------
it('POST /mcp with initialize request responds with 200', async () => {
const res = await request(app.getHttpServer())
.post('/mcp')
.set(MCP_HEADERS)
- .send(
- jsonRpcRequest('initialize', {
- protocolVersion: '2025-11-25',
- capabilities: {},
- clientInfo: { name: 'test-client', version: '0.0.1' },
- }),
- );
+ .set('X-API-Key', viewerKey)
+ .send(initialize());
expect([200, 202]).toContain(res.status);
});
@@ -93,7 +107,11 @@ describe('MCP server (e2e)', () => {
// 2. tools/list returns the tool catalogue with known names
// ---------------------------------------------------------------------------
it('tools/list returns the tool catalogue', async () => {
- const res = await request(app.getHttpServer()).post('/mcp').set(MCP_HEADERS).send(jsonRpcRequest('tools/list'));
+ const res = await request(app.getHttpServer())
+ .post('/mcp')
+ .set(MCP_HEADERS)
+ .set('Authorization', `Bearer ${viewerKey}`)
+ .send(jsonRpcRequest('tools/list'));
expect(res.status).toBe(200);
const body = parseMcpResponse(res);
@@ -108,30 +126,60 @@ describe('MCP server (e2e)', () => {
});
// ---------------------------------------------------------------------------
- // 3. tools/call without API key returns an error tool result
- // (auth is protocol-level: tool errors surface as isError=true, not HTTP 401)
+ // 3. Every request needs a valid key: nothing is answered before it
// ---------------------------------------------------------------------------
- it('tools/call without API key returns isError tool result', async () => {
+ it('initialize without a key answers 401 and discloses no server info', async () => {
+ const res = await request(app.getHttpServer()).post('/mcp').set(MCP_HEADERS).send(initialize());
+
+ expect(res.status).toBe(401);
+ expect(res.headers['www-authenticate']).toBe('Bearer');
+ expect(res.body).toEqual({ jsonrpc: '2.0', error: { code: -32000, message: 'Missing API key' }, id: null });
+ expect(res.text).not.toContain('serverInfo');
+ });
+
+ it('tools/list with an unknown key answers 401 and lists no tools', async () => {
const res = await request(app.getHttpServer())
.post('/mcp')
.set(MCP_HEADERS)
- .send(
- jsonRpcRequest('tools/call', {
- name: 'SessionFindAll',
- arguments: {},
- }),
- );
+ .set('X-API-Key', 'owa_k1_not-a-real-key')
+ .send(jsonRpcRequest('tools/list'));
+
+ expect(res.status).toBe(401);
+ expect(res.text).not.toContain('SessionFindAll');
+ });
+
+ it('tools/call without a key answers 401', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/mcp')
+ .set(MCP_HEADERS)
+ .send(jsonRpcRequest('tools/call', { name: 'SessionFindAll', arguments: {} }));
+
+ expect(res.status).toBe(401);
+ });
+
+ it('refuses a key with an IP allow-list at the gate, as every MCP tool call does', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/mcp')
+ .set(MCP_HEADERS)
+ .set('X-API-Key', ipKey)
+ .send(jsonRpcRequest('tools/list'));
+
+ expect(res.status).toBe(401);
+ });
+
+ // Role, session and chat scope stay per tool call, answered in-band once the key passes the gate.
+ it('a chat-restricted key passes the gate and is refused in-band by the tool call', async () => {
+ const res = await request(app.getHttpServer())
+ .post('/mcp')
+ .set(MCP_HEADERS)
+ .set('X-API-Key', chatKey)
+ .send(jsonRpcRequest('tools/call', { name: 'SessionFindAll', arguments: {} }));
expect(res.status).toBe(200);
- const body = parseMcpResponse(res);
- // The tool handler catches UnauthorizedException and routes through handleToolError,
- // returning a tool result with isError=true.
- const result = body.result as Record<string, unknown> | undefined;
+ const result = parseMcpResponse(res).result as Record<string, unknown> | undefined;
expect(result?.isError).toBe(true);
const content = result?.content as Array<{ type: string; text?: string }> | undefined;
- expect(Array.isArray(content)).toBe(true);
- const text = content?.find(c => c.type === 'text')?.text ?? '';
- expect(text).toMatch(/unauthorized|missing api key/i);
+ expect(content?.find(c => c.type === 'text')?.text ?? '').toMatch(/restricted to selected chats/i);
});
// ---------------------------------------------------------------------------
@@ -141,6 +189,7 @@ describe('MCP server (e2e)', () => {
const res = await request(app.getHttpServer())
.post('/mcp')
.set({ 'Content-Type': 'text/plain', Accept: 'application/json, text/event-stream' })
+ .set('X-API-Key', viewerKey)
.send('{}');
expect(res.status).toBe(415);