diff --git a/server/src/middleware/globalMiddleware.ts b/server/src/middleware/globalMiddleware.ts index 4b9a05d61..d1f9a5afd 100644 --- a/server/src/middleware/globalMiddleware.ts +++ b/server/src/middleware/globalMiddleware.ts @@ -158,7 +158,10 @@ export function applyGlobalMiddleware( // Request correlation comes first, so the whole pipeline and every line the // request logs run under its id. An X-Request-Id set by the proxy in front is // kept when it looks like an id, so its logs and ours line up; anything else - // is replaced. The response always says which id it got. + // is replaced. The response always says which id it got. The body parsers + // bootstrap.ts registers later resume from stream events, but raw-body and + // multer bind their callbacks with AsyncResource, so a handler reached after + // a body still runs under this id (REQID-007, REQID-008). app.use((req: Request, res: Response, next: NextFunction) => { const id = acceptRequestId(req.headers['x-request-id']) ?? newCorrelationId(); res.setHeader(REQUEST_ID_HEADER, id); diff --git a/server/tests/unit/middleware/globalMiddleware.correlation.test.ts b/server/tests/unit/middleware/globalMiddleware.correlation.test.ts index da5e1f4a6..6cbe2c575 100644 --- a/server/tests/unit/middleware/globalMiddleware.correlation.test.ts +++ b/server/tests/unit/middleware/globalMiddleware.correlation.test.ts @@ -2,7 +2,7 @@ * Request correlation in the global middleware: every response says which id * its request ran under, a well-formed X-Request-Id from the proxy is kept, * and the access log writes a 5xx with that id and the stack the exception - * filter left behind, as one entry. REQID-001 through REQID-006. + * filter left behind, as one entry. REQID-001 through REQID-008. */ import { describe, it, expect, vi, beforeEach } from 'vitest'; @@ -16,6 +16,8 @@ const log = vi.hoisted(() => ({ vi.mock('../../../src/nest/audit/audit-log.logger', () => log); import express, { type Request, type Response } from 'express'; +import http from 'node:http'; +import type { AddressInfo } from 'node:net'; import request from 'supertest'; import { applyGlobalMiddleware } from '../../../src/middleware/globalMiddleware'; import { httpConfig } from '../../../src/nest/app-config/tokens'; @@ -40,6 +42,13 @@ function app() { await new Promise((resolve) => setTimeout(resolve, 1)); res.json({ id: currentCorrelation()?.id ?? null }); }); + // bootstrap.ts registers the body parsers after the global middleware, so a + // handler with a body is reached from the parser's stream callback. + a.use(express.json()); + a.use(express.urlencoded({ extended: true })); + a.post('/api/with-body', (req: Request, res: Response) => { + res.json({ id: currentCorrelation()?.id ?? null, body: req.body as unknown }); + }); a.get('/api/boom', (_req: Request, res: Response) => { // What TrekExceptionFilter does for a 5xx when the access log watches the response. expect(res.locals[ACCESS_LOG_ATTACHED]).toBe(true); @@ -87,6 +96,59 @@ describe('X-Request-Id', () => { }); }); +describe('requests with a body', () => { + it('REQID-007: a JSON body parsed by express.json() keeps the id in the handler', async () => { + const res = await request(app()).post('/api/with-body').send({ a: 1 }); + expect(res.body).toEqual({ id: res.headers['x-request-id'], body: { a: 1 } }); + }); + + it('REQID-008: so does a body that arrives in several chunks after the middleware returned', async () => { + const server = app().listen(0); + try { + const { port } = server.address() as AddressInfo; + const answer = await new Promise<{ header: unknown; payload: { id: string | null; body: unknown } }>( + (resolve, reject) => { + const req = http.request( + { + port, + path: '/api/with-body', + method: 'POST', + headers: { 'content-type': 'application/json', 'transfer-encoding': 'chunked' }, + }, + (res) => { + let raw = ''; + res.setEncoding('utf8'); + res.on('data', (chunk: string) => (raw += chunk)); + res.on('end', () => + resolve({ + header: res.headers['x-request-id'], + payload: JSON.parse(raw) as { id: string | null; body: unknown }, + }), + ); + }, + ); + req.on('error', reject); + const chunks = ['{"a":', '1,"b"', ':2}']; + const writeNext = () => { + const chunk = chunks.shift(); + if (chunk === undefined) { + req.end(); + return; + } + req.write(chunk); + setTimeout(writeNext, 10); + }; + writeNext(); + }, + ); + expect(answer.header).toMatch(UUID); + expect(answer.payload).toEqual({ id: answer.header, body: { a: 1, b: 2 } }); + } finally { + await new Promise((resolve) => server.close(resolve)); + } + }); +}); + describe('the access log', () => { it('REQID-006: a 5xx is one entry with the request line, the stack and the request id', async () => { const res = await request(app()).get('/api/boom');