Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(auth): parse Bearer on /health and MCP with the shared helper

Yudhi Armyndharis7339a7bca486
diff --git a/src/modules/health/health.controller.spec.ts b/src/modules/health/health.controller.spec.ts
index 41861f4a2..b7a3397b3 100644
--- a/src/modules/health/health.controller.spec.ts
+++ b/src/modules/health/health.controller.spec.ts
@@ -89,6 +89,17 @@ describe('HealthController', () => {
expect(result.version).toBeDefined();
expect(validateApiKey).toHaveBeenCalledWith('good-key', '127.0.0.1');
});
+
+ // The auth scheme is case-insensitive (RFC 7235), and the REST guard, Bull Board and MCP already
+ // read it that way; an exact 'Bearer ' match here withheld the version from the same valid key.
+ it.each(['bearer good-key', 'BEARER good-key'])('accepts the scheme in any case (%s)', async header => {
+ validateApiKey.mockResolvedValue({ id: 'k1' });
+
+ const result = await controller.check(reqWith({ authorization: header }));
+
+ expect(result.version).toBeDefined();
+ expect(validateApiKey).toHaveBeenCalledWith('good-key', '127.0.0.1');
+ });
});
describe('key-probe auditing', () => {
diff --git a/src/modules/health/health.controller.ts b/src/modules/health/health.controller.ts
index 6e0832ee0..c4f868c4f 100644
--- a/src/modules/health/health.controller.ts
+++ b/src/modules/health/health.controller.ts
@@ -13,6 +13,7 @@ import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { SlidingWindowLimiter } from '../events/ws-rate-limit';
import { limiterKeyForIp, resolveClientIp } from '../../common/utils/ip';
+import { bearerToken } from '../../common/security/bearer-token';
interface DependencyStatus {
status: 'up' | 'down';
@@ -77,9 +78,7 @@ export class HealthController {
*/
private async hasValidApiKey(req: Request): Promise<boolean> {
const xApiKey = req.headers['x-api-key'];
- const authHeader = req.headers['authorization'];
- const rawKey =
- (typeof xApiKey === 'string' && xApiKey) || (authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : undefined);
+ const rawKey = (typeof xApiKey === 'string' && xApiKey) || bearerToken(req.headers['authorization']);
if (!rawKey) return false;
try {
const clientIp = resolveClientIp(req, this.configService.get<string[]>('security.trustedProxies') ?? []);
diff --git a/src/modules/mcp/mcp.server.spec.ts b/src/modules/mcp/mcp.server.spec.ts
index 2a60eebd8..b7bc12ce6 100644
--- a/src/modules/mcp/mcp.server.spec.ts
+++ b/src/modules/mcp/mcp.server.spec.ts
@@ -396,6 +396,26 @@ describe('mountMcpServer (raw-Express request-handling path)', () => {
);
});
+ // One parser for every surface that reads Authorization, so a header the REST guard accepts is
+ // accepted here too and one it refuses is refused here too.
+ it.each([
+ ['bearer good-key', 'good-key'],
+ ['Bearer\tgood-key', 'good-key'],
+ ['Bearer good-key extra', undefined],
+ ])('reads the Authorization header %j like the REST guard', async (header, expected) => {
+ const h = mount();
+ h.authService.validateApiKey.mockResolvedValue({ id: 'k1' });
+ await post(h, { jsonrpc: '2.0', id: 1 }, { authorization: header });
+
+ await toolCallback()(
+ { sessionId: 's1', to: '123', text: 'hi' },
+ { requestInfo: { headers: { authorization: header } } },
+ );
+
+ if (expected === undefined) expect(h.authService.validateApiKey).not.toHaveBeenCalled();
+ else expect(h.authService.validateApiKey).toHaveBeenCalledWith(expected, undefined, 's1');
+ });
+
it('fails closed on a session-scoped tool call without sessionId (guard fires before the auth lookup)', async () => {
const h = mount();
await post(h, { jsonrpc: '2.0', id: 1 }, { authorization: 'Bearer good-key' });
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index 66a1a482e..6af8f3af6 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -15,6 +15,7 @@ import { handleToolError, jsonToolResult, smartToolResult } from './tool-result'
import type { KeyRateLimiter } from './mcp-rate-limit';
import { limiterKeyForIp, resolveClientIp } from '../../common/utils/ip';
import { resolveBodyLimit } from '../../config/bootstrap-security';
+import { bearerToken } from '../../common/security/bearer-token';
const logger = new Logger('McpServer');
@@ -36,11 +37,7 @@ function extractApiKey(extra: ToolExtra): string | undefined {
return Array.isArray(xApiKey) ? xApiKey[0] : xApiKey;
}
const auth = headers['authorization'];
- const authStr = Array.isArray(auth) ? auth[0] : auth;
- if (authStr?.toLowerCase().startsWith('bearer ')) {
- return authStr.slice(7).trim();
- }
- return undefined;
+ return bearerToken(Array.isArray(auth) ? auth[0] : auth);
}
/**