Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(auth): accept the Bearer scheme in any case on REST and Bull Board
Yudhi Armyndharisf6166b375ae9
diff --git a/src/common/security/bearer-token.ts b/src/common/security/bearer-token.tsnew file mode 100644index 000000000..9b0b1a12d--- /dev/null+++ b/src/common/security/bearer-token.ts@@ -0,0 +1,8 @@+/**+ * The credential of an `Authorization: Bearer <token>` header, or `undefined` for any other shape.+ * The scheme is matched case-insensitively (RFC 7235 section 2.1), so every surface that reads the+ * header accepts the same spellings.+ */+export function bearerToken(header: string | undefined): string | undefined {+ return header ? /^bearer\s+(\S+)\s*$/i.exec(header)?.[1] : undefined;+}diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.tsindex ae4baf5ad..d681ad6ff 100644--- a/src/common/security/bull-board-auth.middleware.spec.ts+++ b/src/common/security/bull-board-auth.middleware.spec.ts@@ -140,6 +140,14 @@ describe('BullBoardAuthMiddleware', () => {expect(authService.validateApiKey).toHaveBeenCalledWith('abc', '127.0.0.1');});+ it('accepts the Bearer scheme in any case', async () => {+ authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.ADMIN });+ authService.hasPermission.mockReturnValue(true);++ await mw.use(reqWith({ authorization: 'bearer abc' }), res, jest.fn());+ expect(authService.validateApiKey).toHaveBeenCalledWith('abc', '127.0.0.1');+ });+it('honors X-Forwarded-For only behind a configured trusted proxy (allowedIps parity with the guard)', async () => {configService.get.mockReturnValue(['127.0.0.1']); // the socket peer is a trusted proxyauthService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.ADMIN });diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.tsindex 9a4902b14..5d63b29bc 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 { limiterKeyForIp, resolveClientIp } from '../utils/ip';+import { bearerToken } from './bearer-token';import { setRequestActor } from '../services/request-context';/**@@ -141,11 +142,8 @@ export class BullBoardAuthMiddleware implements NestMiddleware {const header = req.headers['x-api-key'];if (typeof header === 'string' && header) return header;- const authHeader = req.headers['authorization'];- if (authHeader?.startsWith('Bearer ')) return authHeader.slice(7);-// No ?apiKey query fallback — an admin key in the URL leaks into logs/history.- return undefined;+ return bearerToken(req.headers['authorization']);}private getClientIp(req: Request): string {diff --git a/src/modules/auth/guards/api-key.guard.spec.ts b/src/modules/auth/guards/api-key.guard.spec.tsindex 9e5a4e31b..b2a8e623a 100644--- a/src/modules/auth/guards/api-key.guard.spec.ts+++ b/src/modules/auth/guards/api-key.guard.spec.ts@@ -142,6 +142,17 @@ describe('ApiKeyGuard', () => {expect(authService.validateApiKey).toHaveBeenCalledWith('my-bearer-key', '127.0.0.1', undefined);});+ // RFC 7235 section 2.1: the auth scheme is case-insensitive; MCP and metrics already read it so.+ it.each(['bearer my-bearer-key', 'BEARER my-bearer-key'])('accepts the scheme in any case: %j', async header => {+ reflector.getAllAndOverride.mockReturnValueOnce(false).mockReturnValueOnce(undefined);+ (authService.validateApiKey as jest.Mock).mockResolvedValue(createMockApiKey());++ const result = await guard.canActivate(createMockContext({ authorization: header }));++ expect(result).toBe(true);+ expect(authService.validateApiKey).toHaveBeenCalledWith('my-bearer-key', '127.0.0.1', undefined);+ });+it('should reject when API key validation fails', async () => {reflector.getAllAndOverride.mockReturnValueOnce(false);diff --git a/src/modules/auth/guards/api-key.guard.ts b/src/modules/auth/guards/api-key.guard.tsindex 82eccaec0..b95f69389 100644--- a/src/modules/auth/guards/api-key.guard.ts+++ b/src/modules/auth/guards/api-key.guard.ts@@ -23,6 +23,7 @@ import {ChatScopeKind,} from '../decorators/auth.decorators';import { resolveClientIp } from '../../../common/utils/ip';+import { bearerToken } 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';@@ -225,12 +226,7 @@ export class ApiKeyGuard implements CanActivate {const xApiKey = request.headers['x-api-key'] as string;if (xApiKey) return xApiKey;- const authHeader = request.headers['authorization'];- if (authHeader?.startsWith('Bearer ')) {- return authHeader.substring(7);- }-- return undefined;+ return bearerToken(request.headers['authorization']);}/**