Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(security): require an ADMIN API key for the Bull Board queue UI (#214)
Yudhi Armyndharis4b8d315c0cb0
diff --git a/src/common/security/bull-board-auth.middleware.spec.ts b/src/common/security/bull-board-auth.middleware.spec.tsnew file mode 100644index 000000000..26f00c5bf--- /dev/null+++ b/src/common/security/bull-board-auth.middleware.spec.ts@@ -0,0 +1,61 @@+import { UnauthorizedException, ForbiddenException } from '@nestjs/common';+import { Request, Response } from 'express';+import { BullBoardAuthMiddleware } from './bull-board-auth.middleware';+import { AuthService } from '../../modules/auth/auth.service';+import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';++describe('BullBoardAuthMiddleware', () => {+ let mw: BullBoardAuthMiddleware;+ let authService: { validateApiKey: jest.Mock; hasPermission: jest.Mock };+ const res = {} as Response;++ const reqWith = (headers: Record<string, unknown> = {}, query: Record<string, unknown> = {}): Request =>+ ({ headers, query, ip: '127.0.0.1', socket: { remoteAddress: '127.0.0.1' } }) as unknown as Request;++ beforeEach(() => {+ authService = { validateApiKey: jest.fn(), hasPermission: jest.fn() };+ mw = new BullBoardAuthMiddleware(authService as unknown as AuthService);+ });++ it('rejects when no API key is provided', async () => {+ const next = jest.fn();+ await mw.use(reqWith({}), res, next);+ expect(next).toHaveBeenCalledWith(expect.any(UnauthorizedException));+ expect(authService.validateApiKey).not.toHaveBeenCalled();+ });++ it('propagates an invalid-key rejection', async () => {+ authService.validateApiKey.mockRejectedValue(new UnauthorizedException('Invalid API key'));+ const next = jest.fn();+ await mw.use(reqWith({ 'x-api-key': 'bad' }), res, next);+ expect(next).toHaveBeenCalledWith(expect.any(UnauthorizedException));+ });++ it('forbids a valid non-admin key', async () => {+ authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.OPERATOR });+ authService.hasPermission.mockReturnValue(false);+ const next = jest.fn();+ await mw.use(reqWith({ 'x-api-key': 'op' }), res, next);+ expect(next).toHaveBeenCalledWith(expect.any(ForbiddenException));+ });++ it('allows a valid ADMIN key via X-API-Key', async () => {+ authService.validateApiKey.mockResolvedValue({ role: ApiKeyRole.ADMIN });+ authService.hasPermission.mockReturnValue(true);+ const next = jest.fn();+ await mw.use(reqWith({ 'x-api-key': 'admin' }), res, next);+ expect(next).toHaveBeenCalledWith();+ expect(authService.validateApiKey).toHaveBeenCalledWith('admin', '127.0.0.1');+ });++ it('accepts a Bearer token and the ?apiKey query param', 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');++ await mw.use(reqWith({}, { apiKey: 'qkey' }), res, jest.fn());+ expect(authService.validateApiKey).toHaveBeenLastCalledWith('qkey', '127.0.0.1');+ });+});diff --git a/src/common/security/bull-board-auth.middleware.ts b/src/common/security/bull-board-auth.middleware.tsnew file mode 100644index 000000000..ca71d1151--- /dev/null+++ b/src/common/security/bull-board-auth.middleware.ts@@ -0,0 +1,54 @@+import { Injectable, NestMiddleware, UnauthorizedException, ForbiddenException } from '@nestjs/common';+import { Request, Response, NextFunction } from 'express';+import { AuthService } from '../../modules/auth/auth.service';+import { ApiKeyRole } from '../../modules/auth/entities/api-key.entity';++/**+ * Protects the Bull Board UI (/admin/queues).+ *+ * Bull Board is mounted as raw Express middleware by @bull-board/nestjs, so the+ * global ApiKeyGuard — which only runs on Nest controller handlers — does not+ * cover it. This middleware requires a valid ADMIN-role API key, supplied via+ * the X-API-Key header, an Authorization: Bearer token, or an ?apiKey query+ * param (the latter for direct browser access).+ */+@Injectable()+export class BullBoardAuthMiddleware implements NestMiddleware {+ constructor(private readonly authService: AuthService) {}++ async use(req: Request, _res: Response, next: NextFunction): Promise<void> {+ try {+ const rawKey = this.extractKey(req);+ if (!rawKey) {+ throw new UnauthorizedException('API key is required to access the queue dashboard');+ }++ const apiKey = await this.authService.validateApiKey(rawKey, this.getClientIp(req));+ if (!this.authService.hasPermission(apiKey, ApiKeyRole.ADMIN)) {+ throw new ForbiddenException('Admin role required to access the queue dashboard');+ }++ next();+ } catch (err) {+ // Forward to Nest's exception layer so the response uses the standard format.+ next(err);+ }+ }++ private extractKey(req: Request): string | undefined {+ 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);++ const queryKey = req.query?.apiKey;+ if (typeof queryKey === 'string' && queryKey) return queryKey;++ return undefined;+ }++ private getClientIp(req: Request): string {+ return req.socket?.remoteAddress || req.ip || '';+ }+}diff --git a/src/main.ts b/src/main.tsindex 61966fb2b..b62715ac4 100644--- a/src/main.ts+++ b/src/main.ts@@ -4,6 +4,9 @@ import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';import helmet from 'helmet';import { AppModule } from './app.module';import { ShutdownService } from './common/services/shutdown.service';+import { BullBoardAuthMiddleware } from './common/security/bull-board-auth.middleware';+import { AuthService } from './modules/auth/auth.service';+import { Request, Response, NextFunction } from 'express';import * as dotenv from 'dotenv';import * as fs from 'fs';import * as path from 'path';@@ -159,6 +162,15 @@ async function bootstrap() {const document = SwaggerModule.createDocument(app, config);SwaggerModule.setup('api/docs', app, document);+ // Protect the Bull Board queue UI (/api/admin/queues). It is mounted by+ // @bull-board/nestjs as raw Express middleware that the global ApiKeyGuard+ // does not cover; registering this before app.listen() ensures it runs ahead+ // of the Bull Board router. Requires a valid ADMIN API key.+ const bullBoardAuth = new BullBoardAuthMiddleware(app.get(AuthService));+ app.use('/api/admin/queues', (req: Request, res: Response, next: NextFunction) => {+ void bullBoardAuth.use(req, res, next);+ });+const port = process.env.PORT || 2785;await app.listen(port);