Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(auth): read the presented API key in one place

Yudhi Armyndharise9c9c8d8e29e
diff --git a/src/common/security/bearer-token.spec.ts b/src/common/security/bearer-token.spec.ts
new file mode 100644
index 000000000..fe000efdf
--- /dev/null
+++ b/src/common/security/bearer-token.spec.ts
@@ -0,0 +1,39 @@
+import { bearerToken, presentedApiKey } from './bearer-token';
+
+describe('bearerToken', () => {
+ it('reads the token of a Bearer header, the scheme in any case', () => {
+ expect(bearerToken('Bearer abc')).toBe('abc');
+ expect(bearerToken('bearer abc ')).toBe('abc');
+ expect(bearerToken('BEARER abc')).toBe('abc');
+ });
+
+ it.each([undefined, '', 'Basic abc', 'Bearer', 'Bearer two tokens'])('refuses %p', header => {
+ expect(bearerToken(header)).toBeUndefined();
+ });
+});
+
+describe('presentedApiKey', () => {
+ it('prefers the X-API-Key header over a Bearer token', () => {
+ expect(presentedApiKey({ 'x-api-key': 'from-header', authorization: 'Bearer from-bearer' })).toBe('from-header');
+ });
+
+ it('falls back to the Bearer token when the header is absent or empty', () => {
+ expect(presentedApiKey({ authorization: 'Bearer from-bearer' })).toBe('from-bearer');
+ expect(presentedApiKey({ 'x-api-key': '', authorization: 'Bearer from-bearer' })).toBe('from-bearer');
+ });
+
+ it('returns the header as it was sent, whitespace included', () => {
+ expect(presentedApiKey({ 'x-api-key': ' key ' })).toBe(' key ');
+ });
+
+ it('takes the first value of a repeated header', () => {
+ expect(presentedApiKey({ 'x-api-key': ['first', 'second'] })).toBe('first');
+ expect(presentedApiKey({ authorization: ['Bearer first', 'Bearer second'] })).toBe('first');
+ });
+
+ it('answers nothing when no key is presented or the Authorization header is not a Bearer one', () => {
+ expect(presentedApiKey({})).toBeUndefined();
+ expect(presentedApiKey({ authorization: 'Basic abc' })).toBeUndefined();
+ expect(presentedApiKey({ 'x-api-key': [] })).toBeUndefined();
+ });
+});
diff --git a/src/common/security/bearer-token.ts b/src/common/security/bearer-token.ts
index 9b0b1a12d..15ad8e0e3 100644
--- a/src/common/security/bearer-token.ts
+++ b/src/common/security/bearer-token.ts
@@ -6,3 +6,19 @@
export function bearerToken(header: string | undefined): string | undefined {
return header ? /^bearer\s+(\S+)\s*$/i.exec(header)?.[1] : undefined;
}
+
+/** The headers an API key can arrive in; Express and Node both type them like this. */
+interface KeyHeaders {
+ 'x-api-key'?: string | string[];
+ authorization?: string | string[];
+}
+
+/**
+ * The API key a request presents: the `X-API-Key` header, else an `Authorization: Bearer` token. Every
+ * surface that authenticates a key reads it through here, so none of them can disagree on what the
+ * credential is. A repeated header counts by its first value; an empty one is as good as absent.
+ */
+export function presentedApiKey(headers: KeyHeaders): string | undefined {
+ const first = (value: string | string[] | undefined): string | undefined => (Array.isArray(value) ? value[0] : value);
+ return first(headers['x-api-key']) || bearerToken(first(headers.authorization));
+}
diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.ts
index 1fe7ab3bd..d40f70300 100644
--- a/src/common/security/bull-board-auth.middleware.ts
+++ b/src/common/security/bull-board-auth.middleware.ts
@@ -8,7 +8,7 @@ import { AuditAction } from '../../modules/audit/entities/audit-log.entity';
import { allowUnauthenticatedAuditRow } from '../../modules/audit/auth-failure-audit-limiter';
import { KeyRateLimiter, readIpRateLimitConfig } from '../../modules/mcp/mcp-rate-limit';
import { limiterKeyForIp, resolveClientIp } from '../utils/ip';
-import { bearerToken } from './bearer-token';
+import { presentedApiKey } from './bearer-token';
import { setRequestActor } from '../services/request-context';
/**
@@ -146,11 +146,8 @@ export class BullBoardAuthMiddleware implements NestMiddleware {
}
private extractKey(req: Request): string | undefined {
- const header = req.headers['x-api-key'];
- if (typeof header === 'string' && header) return header;
-
// No ?apiKey query fallback — an admin key in the URL leaks into logs/history.
- return bearerToken(req.headers['authorization']);
+ return presentedApiKey(req.headers);
}
private getClientIp(req: Request): string {
diff --git a/src/modules/auth/active-key-index.ts b/src/modules/auth/active-key-index.ts
index 2525edc68..0de98a0c2 100644
--- a/src/modules/auth/active-key-index.ts
+++ b/src/modules/auth/active-key-index.ts
@@ -4,7 +4,7 @@ import { Repository } from 'typeorm';
import type { IncomingHttpHeaders } from 'http';
import { ApiKey } from './entities/api-key.entity';
import { hashApiKey } from './api-key-hash';
-import { bearerToken } from '../../common/security/bearer-token';
+import { presentedApiKey } from '../../common/security/bearer-token';
import { ipMatches } from '../../common/utils/ip';
import { createLogger } from '../../common/services/logger.service';
@@ -81,8 +81,7 @@ export class ActiveKeyIndex implements OnApplicationBootstrap, OnModuleDestroy {
* a Bearer token, trimmed.
*/
recognise(headers: IncomingHttpHeaders, clientIp: string): string | undefined {
- const header = headers['x-api-key'];
- const raw = (typeof header === 'string' && header ? header : bearerToken(headers.authorization))?.trim();
+ const raw = presentedApiKey(headers)?.trim();
if (!raw) return undefined;
const keyHash = hashApiKey(raw, process.env.API_KEY_PEPPER);
const key = this.keys.get(keyHash);
diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.ts
index 391984b88..a3b8b59cc 100644
--- a/src/modules/auth/guards/api-key.guard.ts
+++ b/src/modules/auth/guards/api-key.guard.ts
@@ -23,7 +23,7 @@ import {
ChatScopeKind,
} from '../decorators/auth.decorators';
import { resolveClientIp } from '../../../common/utils/ip';
-import { bearerToken } from '../../../common/security/bearer-token';
+import { presentedApiKey } from '../../../common/security/bearer-token';
import { setRequestActor } from '../../../common/services/request-context';
import { AuditService } from '../../audit/audit.service';
import { AuditAction } from '../../audit/entities/audit-log.entity';
@@ -228,11 +228,8 @@ export class ApiKeyGuard implements CanActivate {
}
private extractApiKey(request: Request): string | undefined {
- // Support both X-API-Key header and Authorization Bearer
- const xApiKey = request.headers['x-api-key'] as string;
- if (xApiKey) return xApiKey;
-
- return bearerToken(request.headers['authorization']);
+ // Both the X-API-Key header and Authorization Bearer are supported.
+ return presentedApiKey(request.headers);
}
/**
diff --git a/src/modules/health/health.controller.ts b/src/modules/health/health.controller.ts
index ed6fe96c0..ec00f2bda 100644
--- a/src/modules/health/health.controller.ts
+++ b/src/modules/health/health.controller.ts
@@ -13,7 +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';
+import { presentedApiKey } from '../../common/security/bearer-token';
interface DependencyStatus {
status: 'up' | 'down';
@@ -82,8 +82,7 @@ export class HealthController {
* none presented, invalid, revoked, IP-denied — withholds the version; it never fails the check.
*/
private async hasValidApiKey(req: Request): Promise<boolean> {
- const xApiKey = req.headers['x-api-key'];
- const rawKey = (typeof xApiKey === 'string' && xApiKey) || bearerToken(req.headers['authorization']);
+ const rawKey = presentedApiKey(req.headers);
if (!rawKey) return false;
const clientIp = resolveClientIp(req, this.configService.get<string[]>('security.trustedProxies') ?? []);
const subject = limiterKeyForIp(clientIp);
diff --git a/src/modules/mcp/mcp.server.ts b/src/modules/mcp/mcp.server.ts
index c1d52e679..713ee225d 100644
--- a/src/modules/mcp/mcp.server.ts
+++ b/src/modules/mcp/mcp.server.ts
@@ -19,7 +19,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';
+import { presentedApiKey } from '../../common/security/bearer-token';
const logger = createLogger('McpServer');
@@ -39,12 +39,7 @@ export interface McpRequestContext {
* cannot disagree on what the credential is (the SDK's own header copy joins duplicate headers).
*/
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;
- }
- const auth = headers['authorization'];
- return bearerToken(Array.isArray(auth) ? auth[0] : auth);
+ return presentedApiKey(headers);
}
/**