Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(observability): X-Request-ID correlation across logs + audit (#711)
Yudhi Armyndharisa9e4b8fbb093
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7814495b7..9bcc67c7f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -49,6 +49,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`/api/metrics` are not counted. Conventional unprefixed names so a generic RED dashboard or a 5xxerror-rate alert matches them directly.+- **Request correlation ids (`X-Request-ID`).** Every inbound request now carries an id that+ propagates through the whole request via AsyncLocalStorage, so each JSON log line and each+ audit-log metadata blob stamps it — a request can be traced end-to-end. A valid client-supplied+ `X-Request-ID` (alphanumeric + dash, ≤128 chars) is echoed; anything else (including a CRLF+ header-injection attempt) is replaced with a generated UUID. The id is also set on the response.+### Fixed- **Diagnosable failure for a stale browser profile after a binary-changing upgrade.** Upgradingdiff --git a/src/common/middleware/request-context.middleware.spec.ts b/src/common/middleware/request-context.middleware.spec.tsnew file mode 100644index 000000000..7e089fee9--- /dev/null+++ b/src/common/middleware/request-context.middleware.spec.ts@@ -0,0 +1,45 @@+import { requestContextMiddleware } from './request-context.middleware';+import { getRequestId } from '../services/request-context';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++function makeReqRes(headers: Record<string, string> = {}) {+ const req = { header: (name: string) => headers[name.toLowerCase()] };+ const setHeaders: Record<string, string> = {};+ const res = { setHeader: (name: string, value: string) => void (setHeaders[name] = value) };+ return { req, res, setHeaders };+}++describe('requestContextMiddleware', () => {+ it('generates a UUID when no X-Request-ID header is supplied', () => {+ const { req, res, setHeaders } = makeReqRes();+ requestContextMiddleware(req as never, res as never, () => undefined);+ expect(setHeaders['X-Request-ID']).toMatch(UUID_RE);+ });++ it('echoes a valid client-supplied X-Request-ID', () => {+ const { req, res, setHeaders } = makeReqRes({ 'x-request-id': 'trace-abc-123' });+ requestContextMiddleware(req as never, res as never, () => undefined);+ expect(setHeaders['X-Request-ID']).toBe('trace-abc-123');+ });++ it('replaces an invalid X-Request-ID (CRLF injection attempt) with a generated UUID', () => {+ const { req, res, setHeaders } = makeReqRes({ 'x-request-id': 'bad\r\nInject: yes' });+ requestContextMiddleware(req as never, res as never, () => undefined);+ expect(setHeaders['X-Request-ID']).not.toContain('\r');+ expect(setHeaders['X-Request-ID']).toMatch(UUID_RE);+ });++ it('runs downstream next() inside the request scope (getRequestId resolves the id)', () => {+ const { req, res } = makeReqRes({ 'x-request-id': 'trace-xyz' });+ let seen: string | undefined;+ requestContextMiddleware(req as never, res as never, () => void (seen = getRequestId()));+ expect(seen).toBe('trace-xyz');+ });++ it('clears the request scope after next() returns (no leak across requests)', () => {+ const { req, res } = makeReqRes({ 'x-request-id': 'trace-xyz' });+ requestContextMiddleware(req as never, res as never, () => undefined);+ expect(getRequestId()).toBeUndefined();+ });+});diff --git a/src/common/middleware/request-context.middleware.ts b/src/common/middleware/request-context.middleware.tsnew file mode 100644index 000000000..bbd8993c1--- /dev/null+++ b/src/common/middleware/request-context.middleware.ts@@ -0,0 +1,20 @@+import { Request, Response, NextFunction } from 'express';+import { randomUUID } from 'node:crypto';+import { runWithRequestId } from '../services/request-context';++/**+ * Functional Express middleware: assign a request id to every inbound request, echo it on the+ * `X-Request-ID` response header, and run the entire downstream chain inside the request scope so+ * every log line and audit record can carry it (see LoggerService / AuditService).+ *+ * Accepts a sane client-supplied id (alphanumeric + dash, ≤128 chars); anything else — including a+ * CRLF header-injection attempt — is ignored and a fresh UUID is generated instead.+ */+const CLIENT_REQUEST_ID_PATTERN = /^[A-Za-z0-9-]{1,128}$/;++export function requestContextMiddleware(req: Request, res: Response, next: NextFunction): void {+ const incoming = req.header('x-request-id');+ const requestId = incoming && CLIENT_REQUEST_ID_PATTERN.test(incoming) ? incoming : randomUUID();+ res.setHeader('X-Request-ID', requestId);+ runWithRequestId(requestId, next);+}diff --git a/src/common/services/logger.service.ts b/src/common/services/logger.service.tsindex f5aba2505..77056c4c2 100644--- a/src/common/services/logger.service.ts+++ b/src/common/services/logger.service.ts@@ -1,4 +1,5 @@import { Injectable, LoggerService as NestLoggerService, Scope } from '@nestjs/common';+import { getRequestId } from './request-context';export enum LogLevel {ERROR = 'error',@@ -119,12 +120,16 @@ export class LoggerService implements NestLoggerService {const metadata =typeof context === 'object' && context !== null ? (redactSecrets(context) as Record<string, unknown>) : {};+ // Stamp every log line with the active request id (set by requestContextMiddleware) so a request+ // can be traced across logs. Absent outside a request scope (boot, workers, cron).+ const requestId = getRequestId();const logEntry = {timestamp,level,context: contextName,message,...metadata,+ ...(requestId ? { requestId } : {}),};const output =diff --git a/src/common/services/request-context.spec.ts b/src/common/services/request-context.spec.tsnew file mode 100644index 000000000..3a6502848--- /dev/null+++ b/src/common/services/request-context.spec.ts@@ -0,0 +1,37 @@+import { runWithRequestId, getRequestId } from './request-context';++describe('request-context', () => {+ it('getRequestId is undefined outside any run scope', () => {+ expect(getRequestId()).toBeUndefined();+ });++ it('getRequestId returns the id inside runWithRequestId', () => {+ runWithRequestId('req-abc', () => {+ expect(getRequestId()).toBe('req-abc');+ });+ });++ it('getRequestId is undefined again after the run scope exits', () => {+ runWithRequestId('req-abc', () => {+ // scope active+ });+ expect(getRequestId()).toBeUndefined();+ });++ it('propagates the id into async work awaited inside the scope', async () => {+ await runWithRequestId('req-abc', async () => {+ await Promise.resolve();+ await new Promise(resolve => setTimeout(resolve, 0));+ expect(getRequestId()).toBe('req-abc');+ });+ });++ it('restores the enclosing scope after a nested run exits', () => {+ runWithRequestId('outer', () => {+ runWithRequestId('inner', () => {+ expect(getRequestId()).toBe('inner');+ });+ expect(getRequestId()).toBe('outer');+ });+ });+});diff --git a/src/common/services/request-context.ts b/src/common/services/request-context.tsnew file mode 100644index 000000000..2ed4c3ff4--- /dev/null+++ b/src/common/services/request-context.ts@@ -0,0 +1,18 @@+/**+ * Per-request async context (today: the X-Request-ID), propagated to every log line and audit+ * record produced while handling a request. Backed by a dedicated AsyncLocalStorage instance —+ * independent of the existing plugin/hook ALS instances (multiple ALS instances coexist fine).+ */+import { AsyncLocalStorage } from 'node:async_hooks';++const requestContextStorage = new AsyncLocalStorage<{ requestId: string }>();++/** Run `fn` (and every async continuation it starts) with `requestId` as the active context. */+export function runWithRequestId<T>(requestId: string, fn: () => T): T {+ return requestContextStorage.run({ requestId }, fn);+}++/** The active request id, or `undefined` when not running inside a request scope. */+export function getRequestId(): string | undefined {+ return requestContextStorage.getStore()?.requestId;+}diff --git a/src/main.ts b/src/main.tsindex 19a012af9..82e988b5e 100644--- a/src/main.ts+++ b/src/main.ts@@ -13,6 +13,7 @@ import { LoggerService, LogLevel, createLogger } from './common/services/logger.import { createSwaggerConfig, exemptPublicOperations } from './config/swagger.config';import { registerUncaughtExceptionMonitor } from './config/process-error-monitor';import { applyHttpTimeouts, HttpTimeoutConfig, HttpTimeoutSink } from './config/http-timeouts';+import { requestContextMiddleware } from './common/middleware/request-context.middleware';import {resolveCorsPolicy,isSwaggerEnabled,@@ -93,6 +94,10 @@ async function bootstrap() {);app.use(urlencoded({ extended: true, limit: bodyLimit }));+ // Assign a request id to every inbound request (X-Request-ID), echo it on the response, and run+ // the whole downstream chain inside its scope so every log line + audit row carries it.+ app.use(requestContextMiddleware);+// Let Nest own every shutdown signal EXCEPT SIGTERM/SIGINT — those we route through the bounded// drain below, so a load balancer / orchestrator observes readiness=503 and stops routing BEFORE// teardown begins. (enableShutdownHooks with an EMPTY array registers ALL signals; this filtereddiff --git a/src/modules/audit/audit.service.ts b/src/modules/audit/audit.service.tsindex fb8c23df5..26ea135b2 100644--- a/src/modules/audit/audit.service.ts+++ b/src/modules/audit/audit.service.ts@@ -4,6 +4,7 @@ import { Repository, Between, LessThan } from 'typeorm';import { AuditLog, AuditAction, AuditSeverity } from './entities/audit-log.entity';import { ApiKey } from '../auth/entities/api-key.entity';import { createLogger } from '../../common/services/logger.service';+import { getRequestId } from '../../common/services/request-context';/** Upper bound on a single audit-log page, so a large `limit` can't load the whole table at once. */export const MAX_AUDIT_PAGE_SIZE = 200;@@ -77,6 +78,11 @@ export class AuditService implements OnModuleInit, OnModuleDestroy {context: AuditContext = {},severity: AuditSeverity = AuditSeverity.INFO,): Promise<AuditLog | null> {+ // Stamp the active request id into metadata so an audit row traces back to the same request as+ // the log lines. Absent outside a request scope (so no metadata blob is created for worker/cron).+ const requestId = getRequestId();+ const metadata =+ context.metadata || requestId ? { ...(context.metadata ?? {}), ...(requestId ? { requestId } : {}) } : null;const auditLog = this.auditRepository.create({action,severity,@@ -89,7 +95,7 @@ export class AuditService implements OnModuleInit, OnModuleDestroy {method: context.method || null,path: context.path || null,statusCode: context.statusCode || null,- metadata: context.metadata || null,+ metadata,errorMessage: context.errorMessage || null,});