From a399a5fccb63c018a4d9c8e33edf82fac5232588 Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Tue, 17 Nov 2026 15:22:21 +0100 Subject: [PATCH 1/3] test(node): Reuse Express servers and batch HTTP scenarios Co-Authored-By: OpenAI Codex --- .../suites/express/sentry-trace/scenario.mjs | 38 +- .../suites/express/sentry-trace/test.ts | 34 +- .../express/tracing/request-data/test.ts | 192 +++---- .../suites/express/tracing/routing/test.ts | 469 +++++++++--------- .../suites/express/tracing/updateName/test.ts | 88 ++-- .../maxIncomingRequestBodySize/test.ts | 358 +++---------- .../suites/tracing/continueTrace/scenario.mjs | 21 +- .../suites/tracing/continueTrace/test.ts | 94 ++-- .../suites/tracing/httpIntegration/test.ts | 22 +- 9 files changed, 507 insertions(+), 809 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/express/sentry-trace/scenario.mjs b/dev-packages/node-integration-tests/suites/express/sentry-trace/scenario.mjs index 260087b258b4..c0c63bf3c53a 100644 --- a/dev-packages/node-integration-tests/suites/express/sentry-trace/scenario.mjs +++ b/dev-packages/node-integration-tests/suites/express/sentry-trace/scenario.mjs @@ -4,6 +4,15 @@ import cors from 'cors'; import express from 'express'; import http from 'http'; +function getOutgoingHeaders(options) { + const request = http.get(options); + const headers = request.getHeaders(); + // Only header construction is under test; don't leave requests to the placeholder host running. + request.on('error', () => {}); + request.destroy(); + return headers; +} + const app = express(); // Set globally so we can assert user data is not leaked into propagated baggage. @@ -13,7 +22,7 @@ app.use(cors()); // Plain outgoing request — used to assert propagated `sentry-trace`/`baggage` headers. app.get('/test/express', (_req, res) => { - const headers = http.get('http://somewhere.not.sentry/').getHeaders(); + const headers = getOutgoingHeaders('http://somewhere.not.sentry/'); res.send({ test_data: headers }); }); @@ -22,7 +31,7 @@ app.get('/test/express', (_req, res) => { app.get('/test/express-replace-trace-id', (_req, res) => { const span = Sentry.getActiveSpan(); const traceId = span?.spanContext().traceId; - const headers = http.get('http://somewhere.not.sentry/').getHeaders(); + const headers = getOutgoingHeaders('http://somewhere.not.sentry/'); if (traceId) { headers['baggage'] = headers['baggage'].replace(traceId, '__SENTRY_TRACE_ID__'); } @@ -32,24 +41,23 @@ app.get('/test/express-replace-trace-id', (_req, res) => { // Sets a third-party baggage header on the outgoing request, which the SDK should // merge with the Sentry DSC entries. app.get('/test/express-third-party-baggage', (_req, res) => { - const headers = http - .get({ hostname: 'somewhere.not.sentry', headers: { baggage: 'other=vendor,foo=bar,third=party' } }) - .getHeaders(); + const headers = getOutgoingHeaders({ + hostname: 'somewhere.not.sentry', + headers: { baggage: 'other=vendor,foo=bar,third=party' }, + }); res.send({ test_data: headers }); }); // Sets a third-party baggage header that also contains sentry-* entries, which the // SDK should ignore/overwrite with the actual DSC. app.get('/test/express-third-party-baggage-with-sentry', (_req, res) => { - const headers = http - .get({ - hostname: 'somewhere.not.sentry', - headers: { - baggage: - 'other=vendor,foo=bar,third=party,sentry-release=9.9.9,sentry-environment=staging,sentry-sample_rate=0.54,last=item', - }, - }) - .getHeaders(); + const headers = getOutgoingHeaders({ + hostname: 'somewhere.not.sentry', + headers: { + baggage: + 'other=vendor,foo=bar,third=party,sentry-release=9.9.9,sentry-environment=staging,sentry-sample_rate=0.54,last=item', + }, + }); res.send({ test_data: headers }); }); @@ -57,7 +65,7 @@ app.get('/test/express-third-party-baggage-with-sentry', (_req, res) => { // property values with `=` signs are preserved during parsing & re-serialization. app.get('/test/express-property-values', (req, res) => { const incomingBaggage = req.headers.baggage; - const headers = http.get({ hostname: 'somewhere.not.sentry', headers: { baggage: incomingBaggage } }).getHeaders(); + const headers = getOutgoingHeaders({ hostname: 'somewhere.not.sentry', headers: { baggage: incomingBaggage } }); res.send({ test_data: headers }); }); diff --git a/dev-packages/node-integration-tests/suites/express/sentry-trace/test.ts b/dev-packages/node-integration-tests/suites/express/sentry-trace/test.ts index e790bfb7f3ff..dd4ed9defbc3 100644 --- a/dev-packages/node-integration-tests/suites/express/sentry-trace/test.ts +++ b/dev-packages/node-integration-tests/suites/express/sentry-trace/test.ts @@ -10,9 +10,13 @@ describe('express sentry-trace', () => { }); createCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + let started: ReturnType['start']> | undefined; + // These cases vary request headers, so the same initialized server can handle each one. + const getRunner = () => (started ??= createRunner().start()); + describe('baggage header assignment', () => { test('Should overwrite baggage if the incoming request already has Sentry baggage data but no sentry-trace', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express', { headers: { @@ -30,7 +34,7 @@ describe('express sentry-trace', () => { }); test('Should propagate sentry trace baggage data from an incoming to an outgoing request.', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express', { headers: { @@ -49,7 +53,7 @@ describe('express sentry-trace', () => { }); test('Should not propagate baggage data from an incoming to an outgoing request if sentry-trace is faulty.', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express', { headers: { @@ -68,7 +72,7 @@ describe('express sentry-trace', () => { }); test('Should not propagate baggage if sentry-trace header is present in incoming request but no baggage header', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express', { headers: { @@ -85,7 +89,7 @@ describe('express sentry-trace', () => { }); test('Should not propagate baggage and ignore original 3rd party baggage entries if sentry-trace header is present', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express', { headers: { @@ -103,7 +107,7 @@ describe('express sentry-trace', () => { }); test('Should populate and propagate sentry baggage if sentry-trace header does not exist', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express'); @@ -126,7 +130,7 @@ describe('express sentry-trace', () => { }); test('Should populate Sentry and ignore 3rd party content if sentry-trace header does not exist', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express', { headers: { @@ -153,7 +157,7 @@ describe('express sentry-trace', () => { }); test('should attach a baggage header to an outgoing request.', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express-replace-trace-id'); @@ -182,7 +186,7 @@ describe('express sentry-trace', () => { }); test('should merge `baggage` header of a third party vendor with the Sentry DSC baggage items', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express-third-party-baggage', { headers: { @@ -203,7 +207,7 @@ describe('express sentry-trace', () => { describe('third party baggage with sentry entries', () => { test('should ignore sentry-values in `baggage` header of a third party vendor and overwrite them with incoming DSC', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest( 'get', @@ -238,7 +242,7 @@ describe('express sentry-trace', () => { }); test('should ignore sentry-values in `baggage` header of a third party vendor and overwrite them with new DSC', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest( 'get', @@ -278,7 +282,7 @@ describe('express sentry-trace', () => { }); test('should preserve baggage property values with equal signs (W3C spec compliance)', async () => { - const runner = createRunner().start(); + const runner = getRunner(); // W3C spec example: https://www.w3.org/TR/baggage/#example const response = await runner.makeRequest('get', '/test/express-property-values', { @@ -299,7 +303,7 @@ describe('express sentry-trace', () => { }); test('Includes transaction in baggage if the transaction name is parameterized', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express'); @@ -313,7 +317,7 @@ describe('express sentry-trace', () => { }); test('Should assign `sentry-trace` header which sets parent trace id of an outgoing request.', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express', { headers: { @@ -333,7 +337,7 @@ describe('express sentry-trace', () => { }); test('should attach a `sentry-trace` header to an outgoing request.', async () => { - const runner = createRunner().start(); + const runner = getRunner(); const response = await runner.makeRequest('get', '/test/express'); diff --git a/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts index 098f9ae2595e..192160c40708 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts @@ -1,147 +1,77 @@ import { afterAll, describe, expect } from 'vitest'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; import { join } from 'node:path'; -import { findSegmentSpan } from '../helpers'; describe('express tracing', () => { afterAll(() => { cleanupChildProcesses(); }); createEsmAndCjsTests(join(__dirname, '..'), 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - describe('request data', () => { - test('correctly captures JSON request data', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'POST /test-post', - attributes: expect.objectContaining({ - 'url.full': { type: 'string', value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post$/) }, - 'http.request.method': { type: 'string', value: 'POST' }, - 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, - 'http.request.header.content-type': { type: 'array', value: ['application/json'] }, - 'http.request.body.data': { type: 'string', value: JSON.stringify({ foo: 'bar', other: 1 }) }, - }), - }); - }, - }) - .start(); + // With span streaming, child spans are sent as they end, before the response status code is + // known, so `ignoreStatusCodes` has no effect and these routes are captured like any other. - runner.makeRequest('post', '/test-post', { - headers: { - 'Content-Type': 'application/json', + describe('request data', () => { + test('captures and ignores request data for each content type', async () => { + const cases = [ + { + path: '/test-post', + contentType: 'application/json', + data: JSON.stringify({ foo: 'bar', other: 1 }), + expectedBody: JSON.stringify({ foo: 'bar', other: 1 }), }, - data: JSON.stringify({ foo: 'bar', other: 1 }), - }); - await runner.completed(); - }); - - test('correctly captures plain text request data', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'POST /test-post', - attributes: expect.objectContaining({ - 'url.full': { type: 'string', value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post$/) }, - 'http.request.method': { type: 'string', value: 'POST' }, - 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, - 'http.request.header.content-type': { type: 'array', value: ['text/plain'] }, - 'http.request.body.data': { type: 'string', value: 'some plain text' }, - }), - }); - }, - }) - .start(); - - runner.makeRequest('post', '/test-post', { - headers: { 'Content-Type': 'text/plain' }, - data: 'some plain text', - }); - await runner.completed(); - }); - - test('correctly captures text buffer request data', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'POST /test-post', - attributes: expect.objectContaining({ - 'url.full': { type: 'string', value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post$/) }, - 'http.request.method': { type: 'string', value: 'POST' }, - 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, - 'http.request.header.content-type': { type: 'array', value: ['application/octet-stream'] }, - 'http.request.body.data': { type: 'string', value: 'some plain text in buffer' }, - }), - }); - }, - }) - .start(); - - runner.makeRequest('post', '/test-post', { - headers: { 'Content-Type': 'application/octet-stream' }, - data: Buffer.from('some plain text in buffer'), - }); - await runner.completed(); - }); - - test('correctly captures non-text buffer request data', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'POST /test-post', - attributes: expect.objectContaining({ - 'url.full': { type: 'string', value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post$/) }, - 'http.request.method': { type: 'string', value: 'POST' }, - 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, - 'http.request.header.content-type': { type: 'array', value: ['application/octet-stream'] }, - // This is some non-ascii string representation - 'http.request.body.data': { type: 'string', value: expect.any(String) }, - }), - }); - }, - }) - .start(); - - const body = new Uint8Array([1, 2, 3, 4, 5]).buffer; - - runner.makeRequest('post', '/test-post', { - headers: { 'Content-Type': 'application/octet-stream' }, - data: body, - }); - await runner.completed(); - }); + { + path: '/test-post', + contentType: 'text/plain', + data: 'some plain text', + expectedBody: 'some plain text', + }, + { + path: '/test-post', + contentType: 'application/octet-stream', + data: Buffer.from('some plain text in buffer'), + expectedBody: 'some plain text in buffer', + }, + { + path: '/test-post', + contentType: 'application/octet-stream', + data: new Uint8Array([1, 2, 3, 4, 5]).buffer, + expectedBody: expect.any(String), + }, + { + path: '/test-post-ignore-body', + contentType: 'application/octet-stream', + data: Buffer.from('some plain text in buffer'), + expectedBody: undefined, + }, + ]; + const runner = createRunner().unordered(); + const spans = cases.map((_, index) => + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.query']?.value === `case=${index}`), + ); + const started = runner.start(); - test('correctly ignores request data', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = findSegmentSpan(container); - expect(serverSpan).toMatchObject({ - name: 'POST /test-post-ignore-body', - attributes: expect.objectContaining({ - 'url.full': { - type: 'string', - value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post-ignore-body$/), - }, - 'http.request.method': { type: 'string', value: 'POST' }, - 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, - 'http.request.header.content-type': { type: 'array', value: ['application/octet-stream'] }, - }), - }); - // Ensure the request body has been ignored - expect(serverSpan?.attributes['http.request.body.data']).toBeUndefined(); - }, - }) - .start(); + for (const [index, { path, contentType, data, expectedBody }] of cases.entries()) { + const url = `${path}?case=${index}`; + await started.makeRequest('post', url, { + headers: { 'Content-Type': contentType }, + data, + }); + const serverSpan = (await spans[index]!).find(span => span.is_segment); - runner.makeRequest('post', '/test-post-ignore-body', { - headers: { 'Content-Type': 'application/octet-stream' }, - data: Buffer.from('some plain text in buffer'), - }); - await runner.completed(); + expect(serverSpan, contentType).toMatchObject({ + name: `POST ${path}`, + attributes: expect.objectContaining({ + 'url.full': { type: 'string', value: `http://localhost:${started.getPort()}${url}` }, + 'http.request.method': { type: 'string', value: 'POST' }, + 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, + 'http.request.header.content-type': { type: 'array', value: [contentType] }, + }), + }); + expect(serverSpan?.attributes['http.request.body.data'], contentType).toEqual( + expectedBody === undefined ? undefined : { type: 'string', value: expectedBody }, + ); + } + await started.completed(); }); }); }); diff --git a/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts index 6ce2cd2b3f61..0d91f6cbfd00 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts @@ -8,267 +8,260 @@ describe('express tracing', () => { cleanupChildProcesses(); }); createEsmAndCjsTests(join(__dirname, '..'), 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + let scenario: ReturnType | undefined; + async function runScenario() { + const paths = [ + '/test/express', + '/test/router/user/123', + '/test/regex', + '/test/router/user/42', + '/test/version/v1/user', + '/', + ]; + const runner = createRunner(); + const collectors = paths.map( + path => + [path, runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === path)] as const, + ); + const started = runner.start(); + for (const path of paths) { + await started.makeRequest('get', path); + } + await started.completed(); + return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const))); + } + async function getSpans(path: string) { + scenario ??= runScenario(); + return (await scenario).get(path)!; + } + test('should create and send segment spans for Express routes and spans for middlewares.', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = findSegmentSpan(container); + const container = { items: await getSpans('/test/express') }; + + const serverSpan = findSegmentSpan(container); - expect(serverSpan).toMatchObject({ - name: 'GET /test/express', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'url.full': { type: 'string', value: expect.stringMatching(/\/test\/express$/) }, - 'http.response.status_code': { type: 'integer', value: 200 }, - }), - }); + expect(serverSpan).toMatchObject({ + name: 'GET /test/express', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'url.full': { type: 'string', value: expect.stringMatching(/\/test\/express$/) }, + 'http.response.status_code': { type: 'integer', value: 200 }, + }), + }); - expect(container.items).toContainEqual( - expect.objectContaining({ - name: 'corsMiddleware', - attributes: expect.objectContaining({ - 'express.name': { type: 'string', value: 'corsMiddleware' }, - 'express.type': { type: 'string', value: 'middleware' }, - 'sentry.op': { type: 'string', value: 'middleware' }, - 'sentry.origin': { type: 'string', value: 'auto.http.express' }, - }), - }), - ); + expect(container.items).toContainEqual( + expect.objectContaining({ + name: 'corsMiddleware', + attributes: expect.objectContaining({ + 'express.name': { type: 'string', value: 'corsMiddleware' }, + 'express.type': { type: 'string', value: 'middleware' }, + 'sentry.op': { type: 'string', value: 'middleware' }, + 'sentry.origin': { type: 'string', value: 'auto.http.express' }, + }), + }), + ); - expect(container.items).toContainEqual( - expect.objectContaining({ - name: '/test/express', - attributes: expect.objectContaining({ - 'express.name': { type: 'string', value: '/test/express' }, - 'express.type': { type: 'string', value: 'request_handler' }, - 'sentry.op': { type: 'string', value: 'handler' }, - 'sentry.origin': { type: 'string', value: 'auto.http.express' }, - }), - }), - ); - }, - }) - .start(); - runner.makeRequest('get', '/test/express'); - await runner.completed(); + expect(container.items).toContainEqual( + expect.objectContaining({ + name: '/test/express', + attributes: expect.objectContaining({ + 'express.name': { type: 'string', value: '/test/express' }, + 'express.type': { type: 'string', value: 'request_handler' }, + 'sentry.op': { type: 'string', value: 'handler' }, + 'sentry.origin': { type: 'string', value: 'auto.http.express' }, + }), + }), + ); }); - test('names router and request handler spans after their route', async () => { - const runner = createRunner() - .expect({ - span: container => { - const handlerSpan = findExpressSpan(container, 'request_handler'); - expect(handlerSpan?.name).toBe('/test/router/user/:id'); - // The name has to stay in step with the attribute it comes from. - expect(handlerSpan?.attributes['http.route']?.value).toBe('/test/router/user/:id'); - expect(handlerSpan?.attributes['sentry.op']?.value).toBe('handler'); - const routerSpan = findExpressSpan(container, 'router'); - expect(routerSpan?.name).toBe('/test/router/user'); + test('names router and request handler spans after their route', async () => { + const container = { items: await getSpans('/test/router/user/123') }; - // Spans of other layer types keep their names. - expect(container.items.find(item => item.name === 'corsMiddleware')?.attributes['express.type']).toEqual({ - type: 'string', - value: 'middleware', - }); - }, - }) - .start(); + const handlerSpan = findExpressSpan(container, 'request_handler'); + expect(handlerSpan?.name).toBe('/test/router/user/:id'); + // The name has to stay in step with the attribute it comes from. + expect(handlerSpan?.attributes['http.route']?.value).toBe('/test/router/user/:id'); + expect(handlerSpan?.attributes['sentry.op']?.value).toBe('handler'); - await runner.makeRequest('get', '/test/router/user/123'); + const routerSpan = findExpressSpan(container, 'router'); + expect(routerSpan?.name).toBe('/test/router/user'); - await runner.completed(); + // Spans of other layer types keep their names. + expect(container.items.find(item => item.name === 'corsMiddleware')?.attributes['express.type']).toEqual({ + type: 'string', + value: 'middleware', + }); }); + test('should set a correct segment name for routes specified in RegEx', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'GET /\\/test\\/regex/', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - 'url.full': { type: 'string', value: expect.stringMatching(/\/test\/regex$/) }, - 'http.response.status_code': { type: 'integer', value: 200 }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', '/test/regex'); - await runner.completed(); + const container = { items: await getSpans('/test/regex') }; + + expect(findSegmentSpan(container)).toMatchObject({ + name: 'GET /\\/test\\/regex/', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'url.full': { type: 'string', value: expect.stringMatching(/\/test\/regex$/) }, + 'http.response.status_code': { type: 'integer', value: 200 }, + }), + }); }); + test('nests a sub-router route handler span under the router span', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)?.name).toBe('GET /test/router/user/:id'); + const container = { items: await getSpans('/test/router/user/42') }; + + expect(findSegmentSpan(container)?.name).toBe('GET /test/router/user/:id'); - const routerSpan = findExpressSpan(container, 'router'); - const handlerSpan = findExpressSpan(container, 'request_handler'); + const routerSpan = findExpressSpan(container, 'router'); + const handlerSpan = findExpressSpan(container, 'request_handler'); - expect(routerSpan).toBeDefined(); - expect(handlerSpan).toBeDefined(); + expect(routerSpan).toBeDefined(); + expect(handlerSpan).toBeDefined(); - // The route handler nests under the router span in both instrumentations. - expect(handlerSpan?.parent_span_id).toBe(routerSpan?.span_id); + // The route handler nests under the router span in both instrumentations. + expect(handlerSpan?.parent_span_id).toBe(routerSpan?.span_id); - // The handler delays its response by ~100ms (see scenario). - const routerDurationMs = ((routerSpan?.end_timestamp ?? 0) - (routerSpan?.start_timestamp ?? 0)) * 1000; + // The handler delays its response by ~100ms (see scenario). + const routerDurationMs = ((routerSpan?.end_timestamp ?? 0) - (routerSpan?.start_timestamp ?? 0)) * 1000; - // The router span stays open until the response finishes, so it spans the - // whole sub-stack it dispatched (~the 100ms handler delay). - expect(routerDurationMs).toBeGreaterThan(50); - }, - }) - .start(); - runner.makeRequest('get', '/test/router/user/42'); - await runner.completed(); + // The router span stays open until the response finishes, so it spans the + // whole sub-stack it dispatched (~the 100ms handler delay). + expect(routerDurationMs).toBeGreaterThan(50); }); + test('keeps the parameter in a route mounted under a parameterized sub-router path', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = findSegmentSpan(container); - // The `:version` parameter must be preserved — using the concrete value - // (`/test/version/v1/user`) would explode route cardinality. - expect(serverSpan?.name).toBe('GET /test/version/:version/user'); - expect(serverSpan?.attributes['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' }); - }, - }) - .start(); - runner.makeRequest('get', '/test/version/v1/user'); - await runner.completed(); + const container = { items: await getSpans('/test/version/v1/user') }; + + const serverSpan = findSegmentSpan(container); + // The `:version` parameter must be preserved — using the concrete value + // (`/test/version/v1/user`) would explode route cardinality. + expect(serverSpan?.name).toBe('GET /test/version/:version/user'); + expect(serverSpan?.attributes['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' }); }); + test('handles root page correctly', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'GET /', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'http.response.status_code': { type: 'integer', value: 200 }, - 'http.request.method': { type: 'string', value: 'GET' }, - 'url.full': { type: 'string', value: expect.stringMatching(/\/$/) }, - 'http.route': { type: 'string', value: '/' }, - 'url.path': { type: 'string', value: '/' }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', '/'); - await runner.completed(); + const container = { items: await getSpans('/') }; + + expect(findSegmentSpan(container)).toMatchObject({ + name: 'GET /', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'http.response.status_code': { type: 'integer', value: 200 }, + 'http.request.method': { type: 'string', value: 'GET' }, + 'url.full': { type: 'string', value: expect.stringMatching(/\/$/) }, + 'http.route': { type: 'string', value: '/' }, + 'url.path': { type: 'string', value: '/' }, + }), + }); + }); + + // With span streaming, child spans are sent as they end, before the response status code is + // known, so `ignoreStatusCodes` has no effect and these routes are captured like any other. + test('captures error status and route attributes for all error routes', async () => { + const cases = [ + { status_code: 401, url: '/401', status_message: 'unauthenticated', name: 'GET /401', source: 'route' }, + { status_code: 402, url: '/402', status_message: 'invalid_argument', name: 'GET /402', source: 'route' }, + { status_code: 403, url: '/403', status_message: 'permission_denied', name: 'GET /403', source: 'route' }, + // Without a matching route the name must not carry the URL path. + { status_code: 404, url: '/does-not-exist', status_message: 'not_found', name: 'GET', source: 'url' }, + ]; + const runner = createRunner().unordered(); + const spans = cases.map(({ url }) => + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === url), + ); + const started = runner.start(); + + for (const [index, { status_code, url, status_message, name, source }] of cases.entries()) { + await started.makeRequest('get', url, { expectError: true }); + const container = { items: await spans[index]! }; + expect(findSegmentSpan(container), url).toMatchObject({ + name, + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'error', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: source }, + 'sentry.status.message': { type: 'string', value: status_message }, + 'http.response.status_code': { type: 'integer', value: status_code }, + 'http.request.method': { type: 'string', value: 'GET' }, + 'url.full': { type: 'string', value: expect.stringMatching(url) }, + 'url.path': { type: 'string', value: url }, + }), + }); + } + await started.completed(); }); - test.each([ - { status_code: 401, url: '/401', status_message: 'unauthenticated', name: 'GET /401', source: 'route' }, - { status_code: 402, url: '/402', status_message: 'invalid_argument', name: 'GET /402', source: 'route' }, - { status_code: 403, url: '/403', status_message: 'permission_denied', name: 'GET /403', source: 'route' }, - // Without a matching route the name must not carry the URL path. - { status_code: 404, url: '/does-not-exist', status_message: 'not_found', name: 'GET', source: 'url' }, - ])( - 'handles %s route correctly', - async ({ - status_code, - url, - status_message, - name, - source, - }: { - status_code: number; - url: string; - status_message: string; - name: string; - source: string; - }) => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name, - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'error', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: source }, - 'sentry.status.message': { type: 'string', value: status_message }, - 'http.response.status_code': { type: 'integer', value: status_code }, - 'http.request.method': { type: 'string', value: 'GET' }, - 'url.full': { type: 'string', value: expect.stringMatching(url) }, - 'url.path': { type: 'string', value: url }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', url, { expectError: true }); - await runner.completed(); - }, - ); - test.each([['array1'], ['array5']])( - 'should set a correct segment name for routes consisting of arrays of routes for %p', - async (segment: string) => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'GET /test/array1,/\\/test\\/array[2-9]/', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, - 'http.response.status_code': { type: 'integer', value: 200 }, - }), - }); - }, - }) - .start(); - await runner.makeRequest('get', `/test/${segment}`); - await runner.completed(); - }, - ); - test.each([ - ['arr/545'], - ['arr/required'], - ['arr/requiredPath'], - ['arr/required/lastParam'], - ['arr55/required/lastParam'], - ['arr/requiredPath/optionalPath/'], - ['arr/requiredPath/optionalPath/lastParam'], - ])('should handle more complex regexes in route arrays correctly for %p', async (segment: string) => { - const runner = createRunner() - .expect({ - span: container => { - expect(findSegmentSpan(container)).toMatchObject({ - name: 'GET /test/arr/:id,/\\/test\\/arr\\d*\\/required(path)?(\\/optionalPath)?\\/(lastParam)?/', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, - 'http.response.status_code': { type: 'integer', value: 200 }, - }), - }); - }, - }) - .start(); - await runner.makeRequest('get', `/test/${segment}`); - await runner.completed(); + + test('sets the segment name for each matching route in an array', async () => { + const segments = ['array1', 'array5']; + const runner = createRunner().unordered(); + const spans = segments.map(segment => + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === `/test/${segment}`), + ); + const started = runner.start(); + + for (const [index, segment] of segments.entries()) { + await started.makeRequest('get', `/test/${segment}`); + const container = { items: await spans[index]! }; + expect(findSegmentSpan(container), segment).toMatchObject({ + name: 'GET /test/array1,/\\/test\\/array[2-9]/', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, + 'http.response.status_code': { type: 'integer', value: 200 }, + }), + }); + } + await started.completed(); + }); + + test('sets the segment name for complex regexes in route arrays', async () => { + const segments = [ + 'arr/545', + 'arr/required', + 'arr/requiredPath', + 'arr/required/lastParam', + 'arr55/required/lastParam', + 'arr/requiredPath/optionalPath/', + 'arr/requiredPath/optionalPath/lastParam', + ]; + const runner = createRunner().unordered(); + const spans = segments.map(segment => + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === `/test/${segment}`), + ); + const started = runner.start(); + + for (const [index, segment] of segments.entries()) { + await started.makeRequest('get', `/test/${segment}`); + const container = { items: await spans[index]! }; + expect(findSegmentSpan(container), segment).toMatchObject({ + name: 'GET /test/arr/:id,/\\/test\\/arr\\d*\\/required(path)?(\\/optionalPath)?\\/(lastParam)?/', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, + 'http.response.status_code': { type: 'integer', value: 200 }, + }), + }); + } + await started.completed(); }); }); }); diff --git a/dev-packages/node-integration-tests/suites/express/tracing/updateName/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/updateName/test.ts index 30288eb58a25..3476b47efa7a 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/updateName/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/updateName/test.ts @@ -8,61 +8,63 @@ describe('express tracing - updateName', () => { }); createCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { + let scenario: ReturnType | undefined; + async function runScenario() { + const paths = ['/test/123/span-updateName', '/test/123/updateSpanName', '/test/123/updateSpanNameAndSource']; + const runner = createRunner(); + const collectors = paths.map( + path => + [path, runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === path)] as const, + ); + const started = runner.start(); + for (const path of paths) { + await started.makeRequest('get', path); + } + await started.completed(); + return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const))); + } + async function getSpans(path: string) { + scenario ??= runScenario(); + return (await scenario).get(path)!; + } + // This test documents the unfortunate behaviour of using `span.updateName` on the server-side. // For http.server root spans (which is the root span on the server 99% of the time), Otel's http instrumentation // calls `span.updateName` and overwrites whatever the name was set to before (by us or by users). test('calling just `span.updateName` updates the final name in express', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = container.items.find(item => item.is_segment); - expect(serverSpan?.name).toBe('new-name'); - expect(serverSpan?.attributes[SENTRY_SEGMENT_NAME_SOURCE]).toEqual({ type: 'string', value: 'custom' }); - }, - }) - .start(); - runner.makeRequest('get', '/test/123/span-updateName'); - await runner.completed(); + const container = { items: await getSpans('/test/123/span-updateName') }; + + const serverSpan = container.items.find(item => item.is_segment); + expect(serverSpan?.name).toBe('new-name'); + expect(serverSpan?.attributes[SENTRY_SEGMENT_NAME_SOURCE]).toEqual({ type: 'string', value: 'custom' }); }); // This test documents the correct way to update the span name (and implicitly the source) in Node: test('calling `Sentry.updateSpanName` updates the final name and source in express', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = container.items.find(item => item.is_segment); - expect(serverSpan).toMatchObject({ - name: 'new-name', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - [SENTRY_SEGMENT_NAME_SOURCE]: { type: 'string', value: 'custom' }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', '/test/123/updateSpanName'); - await runner.completed(); + const container = { items: await getSpans('/test/123/updateSpanName') }; + + const serverSpan = container.items.find(item => item.is_segment); + expect(serverSpan).toMatchObject({ + name: 'new-name', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + [SENTRY_SEGMENT_NAME_SOURCE]: { type: 'string', value: 'custom' }, + }), + }); }); // This test documents the correct way to update the span name (and implicitly the source) in Node: test('calling `Sentry.updateSpanName` and setting source subsequently updates the final name and sets correct source', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = container.items.find(item => item.is_segment); - expect(serverSpan).toMatchObject({ - name: 'new-name', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - [SENTRY_SEGMENT_NAME_SOURCE]: { type: 'string', value: 'component' }, - }), - }); - }, - }) - .start(); - runner.makeRequest('get', '/test/123/updateSpanNameAndSource'); - await runner.completed(); + const container = { items: await getSpans('/test/123/updateSpanNameAndSource') }; + + const serverSpan = container.items.find(item => item.is_segment); + expect(serverSpan).toMatchObject({ + name: 'new-name', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + [SENTRY_SEGMENT_NAME_SOURCE]: { type: 'string', value: 'component' }, + }), + }); }); }); }); diff --git a/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts b/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts index 6170a33ef97d..cfe5ff17ba25 100644 --- a/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts +++ b/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts @@ -12,299 +12,79 @@ const MAX_GENERAL = 1024 * 1024; // 1MB const MAX_MEDIUM = 10_000; const MAX_SMALL = 1000; -describe('express with httpIntegration and not defined maxRequestBodySize', () => { +interface BodyCase { + path?: string; + body: { data: string }; + expectedBody?: string; +} + +const configs: { name: string; instrument: string; cases: BodyCase[] }[] = [ + { + name: 'default (medium)', + instrument: 'instrument-default.mjs', + cases: [ + { body: generatePayload(MAX_MEDIUM), expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)) }, + { body: generatePayload(MAX_MEDIUM + 1), expectedBody: generatePayloadString(MAX_MEDIUM, true) }, + ], + }, + { + name: 'small (overrides disabled httpBodies)', + instrument: 'instrument-small.mjs', + cases: [ + { body: generatePayload(MAX_SMALL), expectedBody: JSON.stringify(generatePayload(MAX_SMALL)) }, + { body: generatePayload(MAX_SMALL + 1), expectedBody: generatePayloadString(MAX_SMALL, true) }, + { body: generateEmojiPayload(MAX_SMALL + 1), expectedBody: generateEmojiPayloadString(250, true) }, + ], + }, + { + name: 'none', + instrument: 'instrument-none.mjs', + cases: [{ body: generatePayload(500) }, { path: '/ignore-request-body', body: generatePayload(500) }], + }, + { + name: 'always', + instrument: 'instrument-always.mjs', + cases: [ + { body: generatePayload(MAX_GENERAL), expectedBody: JSON.stringify(generatePayload(MAX_GENERAL)) }, + { body: generatePayload(MAX_GENERAL + 1), expectedBody: generatePayloadString(MAX_GENERAL, true) }, + ], + }, + { + name: 'medium', + instrument: 'instrument-medium.mjs', + cases: [ + { body: generatePayload(MAX_MEDIUM), expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)) }, + { body: generatePayload(MAX_MEDIUM + 1), expectedBody: generatePayloadString(MAX_MEDIUM, true) }, + ], + }, +]; + +describe.each(configs)('maxRequestBodySize: $name', ({ instrument, cases }) => { afterAll(() => { cleanupChildProcesses(); }); - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-default.mjs', (createRunner, test) => { - test('captures medium request bodies with default setting (medium)', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_MEDIUM)) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_MEDIUM)), - }); - - await runner.completed(); - }); - - test('truncates large request bodies with default setting (medium)', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_MEDIUM, true) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_MEDIUM + 1)), - }); - - await runner.completed(); - }); - }); -}); - -describe('express with httpIntegration, disabled httpBodies, and explicit maxRequestBodySize', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-small.mjs', (createRunner, test) => { - test('captures request bodies because the explicit size overrides dataCollection.httpBodies', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_SMALL)) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_SMALL)), - }); - - await runner.completed(); - }); - }); -}); - -describe('express with httpIntegration and maxRequestBodySize: "none"', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-none.mjs', (createRunner, test) => { - test('does not capture any request bodies with "none" setting', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = container.items.find(item => item.is_segment); - expect(serverSpan?.name).toBe('POST /test-body-size'); - expect(serverSpan?.attributes['http.request.body.data']).toBeUndefined(); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(500)), - }); - - await runner.completed(); - }); - - test('does not capture any request bodies with "none" setting and "ignoreRequestBody"', async () => { - const runner = createRunner() - .expect({ - span: container => { - const serverSpan = container.items.find(item => item.is_segment); - expect(serverSpan?.name).toBe('POST /test-body-size'); - expect(serverSpan?.attributes['http.request.body.data']).toBeUndefined(); - }, - }) - .expect({ - span: container => { - const serverSpan = container.items.find(item => item.is_segment); - expect(serverSpan?.name).toBe('POST /ignore-request-body'); - expect(serverSpan?.attributes['http.request.body.data']).toBeUndefined(); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(500)), - }); - - await runner.makeRequest('post', '/ignore-request-body', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(500)), - }); - - await runner.completed(); - }); - }); -}); - -describe('express with httpIntegration and maxRequestBodySize: "always"', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-always.mjs', (createRunner, test) => { - test('captures maximum allowed request body length with "always" setting', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_GENERAL)) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_GENERAL)), - }); - - await runner.completed(); - }); - - test('captures large request bodies with "always" setting but respects maximum size limit', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_GENERAL, true) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_GENERAL + 1)), - }); - - await runner.completed(); - }); - }); -}); - -describe('express with httpIntegration and maxRequestBodySize: "small"', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-small.mjs', (createRunner, test) => { - test('truncates too large request bodies with "small" setting', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_SMALL, true) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_SMALL + 1)), - }); - - await runner.completed(); - }); - - test('truncates too large non-ASCII request bodies with "small" setting', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - // 250 emojis, each 4 bytes in UTF-8 (resulting in 1000 bytes --> MAX_SMALL) - 'http.request.body.data': { type: 'string', value: generateEmojiPayloadString(250, true) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generateEmojiPayload(MAX_SMALL + 1)), - }); - - await runner.completed(); - }); - }); -}); - -describe('express with httpIntegration and maxRequestBodySize: "medium"', () => { - afterAll(() => { - cleanupChildProcesses(); - }); - - createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-medium.mjs', (createRunner, test) => { - test('keeps medium request bodies with "medium" setting', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_MEDIUM)) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_MEDIUM)), - }); - - await runner.completed(); - }); - - test('truncates large request bodies with "medium" setting', async () => { - const runner = createRunner() - .expect({ - span: container => { - expect(container.items.find(item => item.is_segment)).toMatchObject({ - name: 'POST /test-body-size', - attributes: expect.objectContaining({ - 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_MEDIUM, true) }, - }), - }); - }, - }) - .start(); - - await runner.makeRequest('post', '/test-body-size', { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(generatePayload(MAX_MEDIUM + 1)), - }); - - await runner.completed(); + createEsmAndCjsTests(__dirname, 'scenario.mjs', instrument, (createRunner, test) => { + test('applies the request body limit to each payload', async () => { + const runner = createRunner().unordered(); + const spans = cases.map((_, index) => + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.query']?.value === `case=${index}`), + ); + const started = runner.start(); + + for (const [index, { path = '/test-body-size', body, expectedBody }] of cases.entries()) { + await started.makeRequest('post', `${path}?case=${index}`, { + headers: { 'Content-Type': 'application/json' }, + data: JSON.stringify(body), + }); + const serverSpan = (await spans[index]!).find(span => span.is_segment); + + expect(serverSpan?.name, `${path}, case ${index}`).toBe(`POST ${path}`); + expect(serverSpan?.attributes['http.request.body.data'], `${path}, case ${index}`).toEqual( + expectedBody === undefined ? undefined : { type: 'string', value: expectedBody }, + ); + } + await started.completed(); }); }); }); diff --git a/dev-packages/node-integration-tests/suites/tracing/continueTrace/scenario.mjs b/dev-packages/node-integration-tests/suites/tracing/continueTrace/scenario.mjs index e0f0845f30e7..57305262008f 100644 --- a/dev-packages/node-integration-tests/suites/tracing/continueTrace/scenario.mjs +++ b/dev-packages/node-integration-tests/suites/tracing/continueTrace/scenario.mjs @@ -1,13 +1,14 @@ import * as Sentry from '@sentry/node'; -// The incoming trace headers are injected per-runner via `.withEnv()`. Missing env vars become -// `undefined`, which exercises the "no incoming sentry-trace" variant. -const sentryTrace = process.env.INCOMING_SENTRY_TRACE || undefined; -const baggage = process.env.INCOMING_BAGGAGE || undefined; - -Sentry.continueTrace({ sentryTrace, baggage }, () => { - Sentry.startSpan({ name: 'continued-root-span' }, () => { - // Capture while the root span is active so the error carries its trace context. - Sentry.captureException(new Error('continued-trace-error')); +// Share SDK initialization without letting one variant's propagation context leak into the next. +for (const { key, sentryTrace, baggage } of JSON.parse(process.env.INCOMING_TRACE_VARIANTS)) { + Sentry.withIsolationScope(() => { + Sentry.getIsolationScope().setTag('test.variant', key); + Sentry.continueTrace({ sentryTrace, baggage }, () => { + Sentry.startSpan({ name: 'continued-root-span', attributes: { 'test.variant': key } }, () => { + // Capture while the root span is active so the error carries its trace context. + Sentry.captureException(new Error(`continued-trace-error: ${key}`)); + }); + }); }); -}); +} diff --git a/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts b/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts index aba1bdda43b7..5bfab5dc543a 100644 --- a/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts @@ -86,68 +86,62 @@ describe('continueTrace', () => { createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { describe.each(CONFIGS)('$name', config => { - test.each(VARIANTS)('continues the $key', async variant => { - const wantsSpan = expectsSpan(config.rate, variant); - - const runner = createRunner().withEnv({ - TRACES_SAMPLE_RATE: config.rate, - INCOMING_SENTRY_TRACE: variant.sentryTrace, - INCOMING_BAGGAGE: variant.baggage, - }); - - let observedErrorTraceId: string | undefined; - let observedSpanTraceId: string | undefined; - - // The error event is delayed by async enrichment (context lines, local variables) while the - // span buffer flushes after span end, so the two envelopes can arrive in either - // order. Match them by type rather than by position. - runner.unordered(); - - runner.expect({ - event: event => { - const trace = event.contexts?.trace; - observedErrorTraceId = trace?.trace_id; - - if (variant.traceId) { - expect(trace?.trace_id).toBe(variant.traceId); - } else { - expect(trace?.trace_id).toMatch(/^[a-f0-9]{32}$/); - } - expect(trace?.span_id).toMatch(/^[a-f0-9]{16}$/); - - // getTraceData() observed inside the callback carries the continued trace id. - const traceData = (event.contexts?.traceData ?? {}) as { 'sentry-trace'?: string; baggage?: string }; - expect(traceData['sentry-trace']).toMatch(new RegExp(`^${trace?.trace_id}-[a-f0-9]{16}`)); - if (variant.hasIncomingBaggage) { - expect(traceData.baggage).toContain(`sentry-trace_id=${variant.traceId}`); - } - }, - }); - - if (wantsSpan) { + test('continues each incoming-header variant with isolated scopes', async () => { + const runner = createRunner() + .withEnv({ + TRACES_SAMPLE_RATE: config.rate, + INCOMING_TRACE_VARIANTS: JSON.stringify(VARIANTS), + }) + .unordered(); + const observedErrorTraceIds = new Map(); + const spanCollections = new Map( + VARIANTS.filter(variant => expectsSpan(config.rate, variant)).map(variant => [ + variant.key, + runner.collectStreamedSpansUntilSegment(span => span.attributes['test.variant']?.value === variant.key), + ]), + ); + + for (const variant of VARIANTS) { runner.expect({ - span: container => { - const segment = container.items.find(span => span.is_segment); - observedSpanTraceId = segment?.trace_id; + event: event => { + expect(event.tags?.['test.variant']).toBe(variant.key); + expect(event.exception?.values?.[0]?.value).toBe(`continued-trace-error: ${variant.key}`); + const trace = event.contexts?.trace; + observedErrorTraceIds.set(variant.key, trace?.trace_id); if (variant.traceId) { - expect(segment?.trace_id).toBe(variant.traceId); + expect(trace?.trace_id).toBe(variant.traceId); } else { - expect(segment?.trace_id).toMatch(/^[a-f0-9]{32}$/); + expect(trace?.trace_id).toMatch(/^[a-f0-9]{32}$/); } - if (variant.parentSpanId) { - expect(segment?.parent_span_id).toBe(variant.parentSpanId); + expect(trace?.span_id).toMatch(/^[a-f0-9]{16}$/); + + // getTraceData() observed inside the callback carries the continued trace id. + const traceData = (event.contexts?.traceData ?? {}) as { 'sentry-trace'?: string; baggage?: string }; + expect(traceData['sentry-trace']).toMatch(new RegExp(`^${trace?.trace_id}-[a-f0-9]{16}`)); + if (variant.hasIncomingBaggage) { + expect(traceData.baggage).toContain(`sentry-trace_id=${variant.traceId}`); } - expect(segment?.name).toBe('continued-root-span'); }, }); } await runner.start().completed(); - if (wantsSpan) { - // Error and span share the (continued or freshly generated) trace id. - expect(observedSpanTraceId).toBe(observedErrorTraceId); + for (const variant of VARIANTS.filter(variant => expectsSpan(config.rate, variant))) { + const spans = await spanCollections.get(variant.key)!; + const segment = spans.find(span => span.is_segment); + + if (variant.traceId) { + expect(segment?.trace_id, variant.key).toBe(variant.traceId); + } else { + expect(segment?.trace_id, variant.key).toMatch(/^[a-f0-9]{32}$/); + } + if (variant.parentSpanId) { + expect(segment?.parent_span_id, variant.key).toBe(variant.parentSpanId); + } + expect(segment?.name, variant.key).toBe('continued-root-span'); + expect(segment?.trace_id, variant.key).toBe(observedErrorTraceIds.get(variant.key)); } }); }); diff --git a/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts b/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts index 70618d73671d..e27bf53da1dc 100644 --- a/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts @@ -211,7 +211,7 @@ describe('httpIntegration', () => { describe('http.server spans', () => { createEsmAndCjsTests(__dirname, 'server.mjs', 'instrument.mjs', (createRunner, test) => { - test('captures correct attributes for GET requests', async () => { + test('captures attributes for GET, POST and forwarded requests', async () => { const runner = createRunner() .expect({ transaction: transaction => { @@ -247,14 +247,6 @@ describe('httpIntegration', () => { }); }, }) - .start(); - - runner.makeRequest('get', '/test?a=1&b=2#hash'); - await runner.completed(); - }); - - test('captures correct attributes for POST requests', async () => { - const runner = createRunner() .expect({ transaction: transaction => { const port = runner.getPort(); @@ -292,14 +284,6 @@ describe('httpIntegration', () => { }); }, }) - .start(); - - runner.makeRequest('post', '/test?a=1&b=2#hash', { data: 'test body' }); - await runner.completed(); - }); - - test('prefers the forwarded client address, without the socket port', async () => { - const runner = createRunner() .expect({ transaction: transaction => { const data = transaction.contexts?.trace?.data; @@ -315,7 +299,9 @@ describe('httpIntegration', () => { }) .start(); - runner.makeRequest('get', '/test', { headers: { 'X-Forwarded-For': '203.0.113.7, 10.0.0.1' } }); + await runner.makeRequest('get', '/test?a=1&b=2#hash'); + await runner.makeRequest('post', '/test?a=1&b=2#hash', { data: 'test body' }); + await runner.makeRequest('get', '/test', { headers: { 'X-Forwarded-For': '203.0.113.7, 10.0.0.1' } }); await runner.completed(); }); }); From 07c250b41860ded3d462055963f6e764c4f9a53e Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Fri, 20 Nov 2026 14:11:36 +0100 Subject: [PATCH 2/3] test(node): Preserve individual Express and HTTP case reporting Keep shared scenario output while asserting each route, payload, and trace variant in its own named test. Co-Authored-By: OpenAI Codex --- .../express/tracing/request-data/test.ts | 94 +++++---- .../suites/express/tracing/routing/test.ts | 173 ++++++++--------- .../maxIncomingRequestBodySize/test.ts | 88 +++++++-- .../suites/tracing/continueTrace/test.ts | 68 ++++--- .../suites/tracing/httpIntegration/test.ts | 179 ++++++++++-------- 5 files changed, 350 insertions(+), 252 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts index 192160c40708..c74fc41c4267 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts @@ -11,57 +11,74 @@ describe('express tracing', () => { // known, so `ignoreStatusCodes` has no effect and these routes are captured like any other. describe('request data', () => { - test('captures and ignores request data for each content type', async () => { - const cases = [ - { - path: '/test-post', - contentType: 'application/json', - data: JSON.stringify({ foo: 'bar', other: 1 }), - expectedBody: JSON.stringify({ foo: 'bar', other: 1 }), - }, - { - path: '/test-post', - contentType: 'text/plain', - data: 'some plain text', - expectedBody: 'some plain text', - }, - { - path: '/test-post', - contentType: 'application/octet-stream', - data: Buffer.from('some plain text in buffer'), - expectedBody: 'some plain text in buffer', - }, - { - path: '/test-post', - contentType: 'application/octet-stream', - data: new Uint8Array([1, 2, 3, 4, 5]).buffer, - expectedBody: expect.any(String), - }, - { - path: '/test-post-ignore-body', - contentType: 'application/octet-stream', - data: Buffer.from('some plain text in buffer'), - expectedBody: undefined, - }, - ]; + const cases = [ + { + name: 'correctly captures JSON request data', + path: '/test-post', + contentType: 'application/json', + data: JSON.stringify({ foo: 'bar', other: 1 }), + expectedBody: JSON.stringify({ foo: 'bar', other: 1 }), + }, + { + name: 'correctly captures plain text request data', + path: '/test-post', + contentType: 'text/plain', + data: 'some plain text', + expectedBody: 'some plain text', + }, + { + name: 'correctly captures text buffer request data', + path: '/test-post', + contentType: 'application/octet-stream', + data: Buffer.from('some plain text in buffer'), + expectedBody: 'some plain text in buffer', + }, + { + name: 'correctly captures non-text buffer request data', + path: '/test-post', + contentType: 'application/octet-stream', + data: new Uint8Array([1, 2, 3, 4, 5]).buffer, + expectedBody: expect.any(String), + }, + { + name: 'correctly ignores request data', + path: '/test-post-ignore-body', + contentType: 'application/octet-stream', + data: Buffer.from('some plain text in buffer'), + expectedBody: undefined, + }, + ]; + let scenario: ReturnType | undefined; + async function runScenario() { const runner = createRunner().unordered(); const spans = cases.map((_, index) => runner.collectStreamedSpansUntilSegment(span => span.attributes['url.query']?.value === `case=${index}`), ); const started = runner.start(); - for (const [index, { path, contentType, data, expectedBody }] of cases.entries()) { + for (const [index, { path, contentType, data }] of cases.entries()) { const url = `${path}?case=${index}`; await started.makeRequest('post', url, { headers: { 'Content-Type': contentType }, data, }); - const serverSpan = (await spans[index]!).find(span => span.is_segment); + } + await started.completed(); + return { spans: await Promise.all(spans), port: started.getPort() }; + } + + test.each(cases.map((entry, index) => ({ ...entry, index })))( + '$name', + async ({ index, path, contentType, expectedBody }) => { + scenario ??= runScenario(); + const { spans, port } = await scenario; + const url = `${path}?case=${index}`; + const serverSpan = spans[index]!.find(span => span.is_segment); expect(serverSpan, contentType).toMatchObject({ name: `POST ${path}`, attributes: expect.objectContaining({ - 'url.full': { type: 'string', value: `http://localhost:${started.getPort()}${url}` }, + 'url.full': { type: 'string', value: `http://localhost:${port}${url}` }, 'http.request.method': { type: 'string', value: 'POST' }, 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, 'http.request.header.content-type': { type: 'array', value: [contentType] }, @@ -70,9 +87,8 @@ describe('express tracing', () => { expect(serverSpan?.attributes['http.request.body.data'], contentType).toEqual( expectedBody === undefined ? undefined : { type: 'string', value: expectedBody }, ); - } - await started.completed(); - }); + }, + ); }); }); }); diff --git a/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts index 0d91f6cbfd00..d22b404100e4 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts @@ -9,23 +9,25 @@ describe('express tracing', () => { }); createEsmAndCjsTests(join(__dirname, '..'), 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { let scenario: ReturnType | undefined; - async function runScenario() { - const paths = [ + async function runScenario( + paths = [ '/test/express', '/test/router/user/123', '/test/regex', '/test/router/user/42', '/test/version/v1/user', '/', - ]; - const runner = createRunner(); + ], + expectError = false, + ) { + const runner = createRunner().unordered(); const collectors = paths.map( path => [path, runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === path)] as const, ); const started = runner.start(); for (const path of paths) { - await started.makeRequest('get', path); + await started.makeRequest('get', path, { expectError }); } await started.completed(); return new Map(await Promise.all(collectors.map(async ([path, spans]) => [path, await spans] as const))); @@ -166,102 +168,81 @@ describe('express tracing', () => { // With span streaming, child spans are sent as they end, before the response status code is // known, so `ignoreStatusCodes` has no effect and these routes are captured like any other. - test('captures error status and route attributes for all error routes', async () => { - const cases = [ - { status_code: 401, url: '/401', status_message: 'unauthenticated', name: 'GET /401', source: 'route' }, - { status_code: 402, url: '/402', status_message: 'invalid_argument', name: 'GET /402', source: 'route' }, - { status_code: 403, url: '/403', status_message: 'permission_denied', name: 'GET /403', source: 'route' }, - // Without a matching route the name must not carry the URL path. - { status_code: 404, url: '/does-not-exist', status_message: 'not_found', name: 'GET', source: 'url' }, - ]; - const runner = createRunner().unordered(); - const spans = cases.map(({ url }) => - runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === url), + const cases = [ + { status_code: 401, url: '/401', status_message: 'unauthenticated', name: 'GET /401', source: 'route' }, + { status_code: 402, url: '/402', status_message: 'invalid_argument', name: 'GET /402', source: 'route' }, + { status_code: 403, url: '/403', status_message: 'permission_denied', name: 'GET /403', source: 'route' }, + // Without a matching route the name must not carry the URL path. + { status_code: 404, url: '/does-not-exist', status_message: 'not_found', name: 'GET', source: 'url' }, + ]; + let errorScenario: ReturnType | undefined; + test.each(cases)('handles $url route correctly', async ({ status_code, url, status_message, name, source }) => { + errorScenario ??= runScenario( + cases.map(({ url }) => url), + true, ); - const started = runner.start(); - - for (const [index, { status_code, url, status_message, name, source }] of cases.entries()) { - await started.makeRequest('get', url, { expectError: true }); - const container = { items: await spans[index]! }; - expect(findSegmentSpan(container), url).toMatchObject({ - name, - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'error', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: source }, - 'sentry.status.message': { type: 'string', value: status_message }, - 'http.response.status_code': { type: 'integer', value: status_code }, - 'http.request.method': { type: 'string', value: 'GET' }, - 'url.full': { type: 'string', value: expect.stringMatching(url) }, - 'url.path': { type: 'string', value: url }, - }), - }); - } - await started.completed(); + const container = { items: (await errorScenario).get(url)! }; + expect(findSegmentSpan(container), url).toMatchObject({ + name, + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'error', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: source }, + 'sentry.status.message': { type: 'string', value: status_message }, + 'http.response.status_code': { type: 'integer', value: status_code }, + 'http.request.method': { type: 'string', value: 'GET' }, + 'url.full': { type: 'string', value: expect.stringMatching(url) }, + 'url.path': { type: 'string', value: url }, + }), + }); }); - test('sets the segment name for each matching route in an array', async () => { - const segments = ['array1', 'array5']; - const runner = createRunner().unordered(); - const spans = segments.map(segment => - runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === `/test/${segment}`), - ); - const started = runner.start(); - - for (const [index, segment] of segments.entries()) { - await started.makeRequest('get', `/test/${segment}`); - const container = { items: await spans[index]! }; - expect(findSegmentSpan(container), segment).toMatchObject({ - name: 'GET /test/array1,/\\/test\\/array[2-9]/', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, - 'http.response.status_code': { type: 'integer', value: 200 }, - }), - }); - } - await started.completed(); + const segments = ['array1', 'array5']; + let arrayScenario: ReturnType | undefined; + test.each(segments)('sets the segment name for route arrays: %s', async segment => { + arrayScenario ??= runScenario(segments.map(segment => `/test/${segment}`)); + const container = { items: (await arrayScenario).get(`/test/${segment}`)! }; + expect(findSegmentSpan(container), segment).toMatchObject({ + name: 'GET /test/array1,/\\/test\\/array[2-9]/', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, + 'http.response.status_code': { type: 'integer', value: 200 }, + }), + }); }); - test('sets the segment name for complex regexes in route arrays', async () => { - const segments = [ - 'arr/545', - 'arr/required', - 'arr/requiredPath', - 'arr/required/lastParam', - 'arr55/required/lastParam', - 'arr/requiredPath/optionalPath/', - 'arr/requiredPath/optionalPath/lastParam', - ]; - const runner = createRunner().unordered(); - const spans = segments.map(segment => - runner.collectStreamedSpansUntilSegment(span => span.attributes['url.path']?.value === `/test/${segment}`), - ); - const started = runner.start(); - - for (const [index, segment] of segments.entries()) { - await started.makeRequest('get', `/test/${segment}`); - const container = { items: await spans[index]! }; - expect(findSegmentSpan(container), segment).toMatchObject({ - name: 'GET /test/arr/:id,/\\/test\\/arr\\d*\\/required(path)?(\\/optionalPath)?\\/(lastParam)?/', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, - 'http.response.status_code': { type: 'integer', value: 200 }, - }), - }); - } - await started.completed(); + const regexSegments = [ + 'arr/545', + 'arr/required', + 'arr/requiredPath', + 'arr/required/lastParam', + 'arr55/required/lastParam', + 'arr/requiredPath/optionalPath/', + 'arr/requiredPath/optionalPath/lastParam', + ]; + let regexScenario: ReturnType | undefined; + test.each(regexSegments)('handles complex regexes in route arrays: %s', async segment => { + regexScenario ??= runScenario(regexSegments.map(segment => `/test/${segment}`)); + const container = { items: (await regexScenario).get(`/test/${segment}`)! }; + expect(findSegmentSpan(container), segment).toMatchObject({ + name: 'GET /test/arr/:id,/\\/test\\/arr\\d*\\/required(path)?(\\/optionalPath)?\\/(lastParam)?/', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, + 'http.response.status_code': { type: 'integer', value: 200 }, + }), + }); }); }); }); diff --git a/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts b/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts index cfe5ff17ba25..a74499f18ddb 100644 --- a/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts +++ b/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts @@ -13,6 +13,7 @@ const MAX_MEDIUM = 10_000; const MAX_SMALL = 1000; interface BodyCase { + name: string; path?: string; body: { data: string }; expectedBody?: string; @@ -23,38 +24,81 @@ const configs: { name: string; instrument: string; cases: BodyCase[] }[] = [ name: 'default (medium)', instrument: 'instrument-default.mjs', cases: [ - { body: generatePayload(MAX_MEDIUM), expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)) }, - { body: generatePayload(MAX_MEDIUM + 1), expectedBody: generatePayloadString(MAX_MEDIUM, true) }, + { + name: 'captures medium request bodies with default setting (medium)', + body: generatePayload(MAX_MEDIUM), + expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)), + }, + { + name: 'truncates large request bodies with default setting (medium)', + body: generatePayload(MAX_MEDIUM + 1), + expectedBody: generatePayloadString(MAX_MEDIUM, true), + }, ], }, { name: 'small (overrides disabled httpBodies)', instrument: 'instrument-small.mjs', cases: [ - { body: generatePayload(MAX_SMALL), expectedBody: JSON.stringify(generatePayload(MAX_SMALL)) }, - { body: generatePayload(MAX_SMALL + 1), expectedBody: generatePayloadString(MAX_SMALL, true) }, - { body: generateEmojiPayload(MAX_SMALL + 1), expectedBody: generateEmojiPayloadString(250, true) }, + { + name: 'captures request bodies because the explicit size overrides dataCollection.httpBodies', + body: generatePayload(MAX_SMALL), + expectedBody: JSON.stringify(generatePayload(MAX_SMALL)), + }, + { + name: 'truncates too large request bodies with "small" setting', + body: generatePayload(MAX_SMALL + 1), + expectedBody: generatePayloadString(MAX_SMALL, true), + }, + { + name: 'truncates too large non-ASCII request bodies with "small" setting', + body: generateEmojiPayload(MAX_SMALL + 1), + expectedBody: generateEmojiPayloadString(250, true), + }, ], }, { name: 'none', instrument: 'instrument-none.mjs', - cases: [{ body: generatePayload(500) }, { path: '/ignore-request-body', body: generatePayload(500) }], + cases: [ + { name: 'does not capture any request bodies with "none" setting', body: generatePayload(500) }, + { + name: 'does not capture any request bodies with "none" setting and "ignoreRequestBody"', + path: '/ignore-request-body', + body: generatePayload(500), + }, + ], }, { name: 'always', instrument: 'instrument-always.mjs', cases: [ - { body: generatePayload(MAX_GENERAL), expectedBody: JSON.stringify(generatePayload(MAX_GENERAL)) }, - { body: generatePayload(MAX_GENERAL + 1), expectedBody: generatePayloadString(MAX_GENERAL, true) }, + { + name: 'captures maximum allowed request body length with "always" setting', + body: generatePayload(MAX_GENERAL), + expectedBody: JSON.stringify(generatePayload(MAX_GENERAL)), + }, + { + name: 'captures large request bodies with "always" setting but respects maximum size limit', + body: generatePayload(MAX_GENERAL + 1), + expectedBody: generatePayloadString(MAX_GENERAL, true), + }, ], }, { name: 'medium', instrument: 'instrument-medium.mjs', cases: [ - { body: generatePayload(MAX_MEDIUM), expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)) }, - { body: generatePayload(MAX_MEDIUM + 1), expectedBody: generatePayloadString(MAX_MEDIUM, true) }, + { + name: 'keeps medium request bodies with "medium" setting', + body: generatePayload(MAX_MEDIUM), + expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)), + }, + { + name: 'truncates large request bodies with "medium" setting', + body: generatePayload(MAX_MEDIUM + 1), + expectedBody: generatePayloadString(MAX_MEDIUM, true), + }, ], }, ]; @@ -65,26 +109,34 @@ describe.each(configs)('maxRequestBodySize: $name', ({ instrument, cases }) => { }); createEsmAndCjsTests(__dirname, 'scenario.mjs', instrument, (createRunner, test) => { - test('applies the request body limit to each payload', async () => { + let scenario: ReturnType | undefined; + async function runScenario() { const runner = createRunner().unordered(); const spans = cases.map((_, index) => runner.collectStreamedSpansUntilSegment(span => span.attributes['url.query']?.value === `case=${index}`), ); const started = runner.start(); - for (const [index, { path = '/test-body-size', body, expectedBody }] of cases.entries()) { + for (const [index, { path = '/test-body-size', body }] of cases.entries()) { await started.makeRequest('post', `${path}?case=${index}`, { headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(body), }); - const serverSpan = (await spans[index]!).find(span => span.is_segment); + } + await started.completed(); + return Promise.all(spans); + } - expect(serverSpan?.name, `${path}, case ${index}`).toBe(`POST ${path}`); - expect(serverSpan?.attributes['http.request.body.data'], `${path}, case ${index}`).toEqual( + test.each(cases.map((entry, index) => ({ ...entry, index })))( + '$name', + async ({ index, path = '/test-body-size', expectedBody }) => { + scenario ??= runScenario(); + const serverSpan = (await scenario)[index]!.find(span => span.is_segment); + expect(serverSpan?.name).toBe(`POST ${path}`); + expect(serverSpan?.attributes['http.request.body.data']).toEqual( expectedBody === undefined ? undefined : { type: 'string', value: expectedBody }, ); - } - await started.completed(); - }); + }, + ); }); }); diff --git a/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts b/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts index 5bfab5dc543a..cfd4744de409 100644 --- a/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/continueTrace/test.ts @@ -1,3 +1,4 @@ +import type { Event } from '@sentry/core'; import { afterAll, describe, expect } from 'vitest'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; @@ -86,14 +87,15 @@ describe('continueTrace', () => { createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { describe.each(CONFIGS)('$name', config => { - test('continues each incoming-header variant with isolated scopes', async () => { + let scenario: ReturnType | undefined; + async function runScenario() { const runner = createRunner() .withEnv({ TRACES_SAMPLE_RATE: config.rate, INCOMING_TRACE_VARIANTS: JSON.stringify(VARIANTS), }) .unordered(); - const observedErrorTraceIds = new Map(); + const events: Event[] = []; const spanCollections = new Map( VARIANTS.filter(variant => expectsSpan(config.rate, variant)).map(variant => [ variant.key, @@ -101,36 +103,52 @@ describe('continueTrace', () => { ]), ); - for (const variant of VARIANTS) { + for (const _variant of VARIANTS) { runner.expect({ event: event => { - expect(event.tags?.['test.variant']).toBe(variant.key); - expect(event.exception?.values?.[0]?.value).toBe(`continued-trace-error: ${variant.key}`); - const trace = event.contexts?.trace; - observedErrorTraceIds.set(variant.key, trace?.trace_id); - - if (variant.traceId) { - expect(trace?.trace_id).toBe(variant.traceId); - } else { - expect(trace?.trace_id).toMatch(/^[a-f0-9]{32}$/); - } - expect(trace?.span_id).toMatch(/^[a-f0-9]{16}$/); - - // getTraceData() observed inside the callback carries the continued trace id. - const traceData = (event.contexts?.traceData ?? {}) as { 'sentry-trace'?: string; baggage?: string }; - expect(traceData['sentry-trace']).toMatch(new RegExp(`^${trace?.trace_id}-[a-f0-9]{16}`)); - if (variant.hasIncomingBaggage) { - expect(traceData.baggage).toContain(`sentry-trace_id=${variant.traceId}`); - } + events.push(event); }, }); } await runner.start().completed(); - for (const variant of VARIANTS.filter(variant => expectsSpan(config.rate, variant))) { - const spans = await spanCollections.get(variant.key)!; - const segment = spans.find(span => span.is_segment); + return { + events, + spans: new Map( + await Promise.all([...spanCollections].map(async ([key, spans]) => [key, await spans] as const)), + ), + }; + } + + test.each(VARIANTS)('continues the $key', async variant => { + scenario ??= runScenario(); + const { events, spans } = await scenario; + const event = events.find( + event => event.exception?.values?.[0]?.value === `continued-trace-error: ${variant.key}`, + ); + expect(event).toBeDefined(); + expect(event!.tags?.['test.variant']).toBe(variant.key); + expect(event!.exception?.values?.[0]?.value).toBe(`continued-trace-error: ${variant.key}`); + const trace = event!.contexts?.trace; + + if (variant.traceId) { + expect(trace?.trace_id).toBe(variant.traceId); + } else { + expect(trace?.trace_id).toMatch(/^[a-f0-9]{32}$/); + } + expect(trace?.span_id).toMatch(/^[a-f0-9]{16}$/); + + // getTraceData() observed inside the callback carries the continued trace id. + const traceData = (event!.contexts?.traceData ?? {}) as { 'sentry-trace'?: string; baggage?: string }; + expect(traceData['sentry-trace']).toMatch(new RegExp(`^${trace?.trace_id}-[a-f0-9]{16}`)); + if (variant.hasIncomingBaggage) { + expect(traceData.baggage).toContain(`sentry-trace_id=${variant.traceId}`); + } + + if (expectsSpan(config.rate, variant)) { + const collectedSpans = spans.get(variant.key)!; + const segment = collectedSpans.find(span => span.is_segment); if (variant.traceId) { expect(segment?.trace_id, variant.key).toBe(variant.traceId); @@ -141,7 +159,7 @@ describe('continueTrace', () => { expect(segment?.parent_span_id, variant.key).toBe(variant.parentSpanId); } expect(segment?.name, variant.key).toBe('continued-root-span'); - expect(segment?.trace_id, variant.key).toBe(observedErrorTraceIds.get(variant.key)); + expect(segment?.trace_id, variant.key).toBe(trace?.trace_id); } }); }); diff --git a/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts b/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts index e27bf53da1dc..6efc7928f9cb 100644 --- a/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/httpIntegration/test.ts @@ -35,7 +35,7 @@ import { USER_AGENT_ORIGINAL, USER_IP_ADDRESS, } from '@sentry/conventions/attributes'; -import { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE } from '@sentry/core'; +import { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, type TransactionEvent } from '@sentry/core'; import { afterAll, describe, expect, test } from 'vitest'; import { cleanupChildProcesses, createEsmAndCjsTests, createRunner } from '../../../utils/runner'; import { EXPECTED_SDK_NAME, supports } from '../../../utils'; @@ -211,90 +211,23 @@ describe('httpIntegration', () => { describe('http.server spans', () => { createEsmAndCjsTests(__dirname, 'server.mjs', 'instrument.mjs', (createRunner, test) => { - test('captures attributes for GET, POST and forwarded requests', async () => { + let scenario: ReturnType | undefined; + async function runScenario() { + const transactions: TransactionEvent[] = []; const runner = createRunner() .expect({ transaction: transaction => { - const port = runner.getPort(); - expect(transaction.transaction).toBe('GET /test'); - expect(transaction.contexts?.trace?.data).toEqual({ - 'http.request.method': 'GET', - 'url.query': 'a=1&b=2', - 'http.response.status_code': 200, - 'http.route': '/test', - 'url.scheme': 'http', - 'http.response.status_text': 'OK', - 'user_agent.original': 'node', - 'client.address': '::1', - 'client.port': expect.any(Number), - 'network.local.address': '::1', - 'server.address': 'localhost', - 'server.port': port, - 'network.local.port': port, - 'network.peer.address': '::1', - 'network.peer.port': expect.any(Number), - 'network.protocol.name': 'http', - 'network.protocol.version': '1.1', - 'network.transport': 'tcp', - 'sentry.kind': 'server', - 'sentry.op': 'http.server', - 'sentry.origin': 'auto.http.http_server', - 'sentry.sample_rate': 1, - 'sentry.segment.name.source': 'route', - [URL_FULL]: `http://localhost:${port}/test?a=1&b=2`, - [URL_PATH]: '/test', - ...getCommonHttpRequestHeaders(), - }); + transactions.push(transaction); }, }) .expect({ transaction: transaction => { - const port = runner.getPort(); - expect(transaction.transaction).toBe('POST /test'); - expect(transaction.contexts?.trace?.data).toEqual({ - 'http.request.method': 'POST', - 'url.query': 'a=1&b=2', - 'http.request.body.size': 9, - 'http.response.status_code': 200, - 'http.route': '/test', - 'url.scheme': 'http', - 'http.response.status_text': 'OK', - 'user_agent.original': 'node', - 'client.address': '::1', - 'client.port': expect.any(Number), - 'network.local.address': '::1', - 'server.address': 'localhost', - 'server.port': port, - 'network.local.port': port, - 'network.peer.address': '::1', - 'network.peer.port': expect.any(Number), - 'network.protocol.name': 'http', - 'network.protocol.version': '1.1', - 'network.transport': 'tcp', - 'sentry.kind': 'server', - 'sentry.op': 'http.server', - 'sentry.origin': 'auto.http.http_server', - 'sentry.sample_rate': 1, - 'sentry.segment.name.source': 'route', - [URL_FULL]: `http://localhost:${port}/test?a=1&b=2`, - [URL_PATH]: '/test', - 'http.request.header.content-length': ['9'], - 'http.request.header.content-type': ['text/plain;charset=UTF-8'], - ...getCommonHttpRequestHeaders(), - }); + transactions.push(transaction); }, }) .expect({ transaction: transaction => { - const data = transaction.contexts?.trace?.data; - expect(data).toEqual( - expect.objectContaining({ - 'client.address': '203.0.113.7', - 'network.peer.address': '::1', - 'network.peer.port': expect.any(Number), - }), - ); - expect(data).not.toHaveProperty('client.port'); + transactions.push(transaction); }, }) .start(); @@ -303,6 +236,104 @@ describe('httpIntegration', () => { await runner.makeRequest('post', '/test?a=1&b=2#hash', { data: 'test body' }); await runner.makeRequest('get', '/test', { headers: { 'X-Forwarded-For': '203.0.113.7, 10.0.0.1' } }); await runner.completed(); + return { transactions, port: runner.getPort() }; + } + + test('captures correct attributes for GET requests', async () => { + scenario ??= runScenario(); + const { transactions, port } = await scenario; + const transaction = transactions.find( + transaction => + transaction.contexts?.trace?.data?.['http.request.method'] === 'GET' && + transaction.contexts?.trace?.data?.['url.query'] === 'a=1&b=2', + ); + expect(transaction).toBeDefined(); + expect(transaction!.transaction).toBe('GET /test'); + expect(transaction!.contexts?.trace?.data).toEqual({ + 'http.request.method': 'GET', + 'url.query': 'a=1&b=2', + 'http.response.status_code': 200, + 'http.route': '/test', + 'url.scheme': 'http', + 'http.response.status_text': 'OK', + 'user_agent.original': 'node', + 'client.address': '::1', + 'client.port': expect.any(Number), + 'network.local.address': '::1', + 'server.address': 'localhost', + 'server.port': port, + 'network.local.port': port, + 'network.peer.address': '::1', + 'network.peer.port': expect.any(Number), + 'network.protocol.name': 'http', + 'network.protocol.version': '1.1', + 'network.transport': 'tcp', + 'sentry.kind': 'server', + 'sentry.op': 'http.server', + 'sentry.origin': 'auto.http.http_server', + 'sentry.sample_rate': 1, + 'sentry.segment.name.source': 'route', + [URL_FULL]: `http://localhost:${port}/test?a=1&b=2`, + [URL_PATH]: '/test', + ...getCommonHttpRequestHeaders(), + }); + }); + test('captures correct attributes for POST requests', async () => { + scenario ??= runScenario(); + const { transactions, port } = await scenario; + const transaction = transactions.find( + transaction => transaction.contexts?.trace?.data?.['http.request.method'] === 'POST', + ); + expect(transaction).toBeDefined(); + expect(transaction!.transaction).toBe('POST /test'); + expect(transaction!.contexts?.trace?.data).toEqual({ + 'http.request.method': 'POST', + 'url.query': 'a=1&b=2', + 'http.request.body.size': 9, + 'http.response.status_code': 200, + 'http.route': '/test', + 'url.scheme': 'http', + 'http.response.status_text': 'OK', + 'user_agent.original': 'node', + 'client.address': '::1', + 'client.port': expect.any(Number), + 'network.local.address': '::1', + 'server.address': 'localhost', + 'server.port': port, + 'network.local.port': port, + 'network.peer.address': '::1', + 'network.peer.port': expect.any(Number), + 'network.protocol.name': 'http', + 'network.protocol.version': '1.1', + 'network.transport': 'tcp', + 'sentry.kind': 'server', + 'sentry.op': 'http.server', + 'sentry.origin': 'auto.http.http_server', + 'sentry.sample_rate': 1, + 'sentry.segment.name.source': 'route', + [URL_FULL]: `http://localhost:${port}/test?a=1&b=2`, + [URL_PATH]: '/test', + 'http.request.header.content-length': ['9'], + 'http.request.header.content-type': ['text/plain;charset=UTF-8'], + ...getCommonHttpRequestHeaders(), + }); + }); + test('prefers the forwarded client address, without the socket port', async () => { + scenario ??= runScenario(); + const { transactions, port } = await scenario; + const transaction = transactions.find( + transaction => transaction.contexts?.trace?.data?.[URL_FULL] === `http://localhost:${port}/test`, + ); + expect(transaction).toBeDefined(); + const data = transaction!.contexts?.trace?.data; + expect(data).toEqual( + expect.objectContaining({ + 'client.address': '203.0.113.7', + 'network.peer.address': '::1', + 'network.peer.port': expect.any(Number), + }), + ); + expect(data).not.toHaveProperty('client.port'); }); }); From ae50276f02498425dca892c9c56fea28517a8a5d Mon Sep 17 00:00:00 2001 From: Nicolas Hrubec Date: Fri, 20 Nov 2026 16:57:07 +0100 Subject: [PATCH 3/3] test(node): Keep original Express assertions and case structure Remove optional assertion-table refactors and restore routing case names while retaining shared scenario execution. Co-Authored-By: OpenAI Codex --- .../express/tracing/request-data/test.ts | 177 ++++++---- .../suites/express/tracing/routing/test.ts | 149 +++++---- .../maxIncomingRequestBodySize/test.ts | 312 +++++++++++------- 3 files changed, 381 insertions(+), 257 deletions(-) diff --git a/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts index c74fc41c4267..8f3dd4196e7c 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/request-data/test.ts @@ -1,94 +1,137 @@ import { afterAll, describe, expect } from 'vitest'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; import { join } from 'node:path'; +import { findSegmentSpan } from '../helpers'; describe('express tracing', () => { afterAll(() => { cleanupChildProcesses(); }); createEsmAndCjsTests(join(__dirname, '..'), 'scenario.mjs', 'instrument.mjs', (createRunner, test) => { - // With span streaming, child spans are sent as they end, before the response status code is - // known, so `ignoreStatusCodes` has no effect and these routes are captured like any other. - describe('request data', () => { - const cases = [ - { - name: 'correctly captures JSON request data', - path: '/test-post', - contentType: 'application/json', - data: JSON.stringify({ foo: 'bar', other: 1 }), - expectedBody: JSON.stringify({ foo: 'bar', other: 1 }), - }, - { - name: 'correctly captures plain text request data', - path: '/test-post', - contentType: 'text/plain', - data: 'some plain text', - expectedBody: 'some plain text', - }, - { - name: 'correctly captures text buffer request data', - path: '/test-post', - contentType: 'application/octet-stream', - data: Buffer.from('some plain text in buffer'), - expectedBody: 'some plain text in buffer', - }, - { - name: 'correctly captures non-text buffer request data', - path: '/test-post', - contentType: 'application/octet-stream', - data: new Uint8Array([1, 2, 3, 4, 5]).buffer, - expectedBody: expect.any(String), - }, - { - name: 'correctly ignores request data', - path: '/test-post-ignore-body', - contentType: 'application/octet-stream', - data: Buffer.from('some plain text in buffer'), - expectedBody: undefined, - }, - ]; let scenario: ReturnType | undefined; async function runScenario() { + const requests = [ + { path: '/test-post', contentType: 'application/json', data: JSON.stringify({ foo: 'bar', other: 1 }) }, + { path: '/test-post', contentType: 'text/plain', data: 'some plain text' }, + { + path: '/test-post', + contentType: 'application/octet-stream', + data: Buffer.from('some plain text in buffer'), + }, + { path: '/test-post', contentType: 'application/octet-stream', data: new Uint8Array([1, 2, 3, 4, 5]).buffer }, + { + path: '/test-post-ignore-body', + contentType: 'application/octet-stream', + data: Buffer.from('some plain text in buffer'), + }, + ]; const runner = createRunner().unordered(); - const spans = cases.map((_, index) => + const spans = requests.map((_, index) => runner.collectStreamedSpansUntilSegment(span => span.attributes['url.query']?.value === `case=${index}`), ); const started = runner.start(); - - for (const [index, { path, contentType, data }] of cases.entries()) { - const url = `${path}?case=${index}`; - await started.makeRequest('post', url, { + for (const [index, { path, contentType, data }] of requests.entries()) { + await started.makeRequest('post', `${path}?case=${index}`, { headers: { 'Content-Type': contentType }, data, }); } await started.completed(); - return { spans: await Promise.all(spans), port: started.getPort() }; + return Promise.all(spans); + } + async function getContainer(index: number) { + scenario ??= runScenario(); + return { items: (await scenario)[index]! }; } - test.each(cases.map((entry, index) => ({ ...entry, index })))( - '$name', - async ({ index, path, contentType, expectedBody }) => { - scenario ??= runScenario(); - const { spans, port } = await scenario; - const url = `${path}?case=${index}`; - const serverSpan = spans[index]!.find(span => span.is_segment); + test('correctly captures JSON request data', async () => { + const container = await getContainer(0); + expect(findSegmentSpan(container)).toMatchObject({ + name: 'POST /test-post', + attributes: expect.objectContaining({ + 'url.full': { + type: 'string', + value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post\?case=0$/), + }, + 'http.request.method': { type: 'string', value: 'POST' }, + 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, + 'http.request.header.content-type': { type: 'array', value: ['application/json'] }, + 'http.request.body.data': { type: 'string', value: JSON.stringify({ foo: 'bar', other: 1 }) }, + }), + }); + }); - expect(serverSpan, contentType).toMatchObject({ - name: `POST ${path}`, - attributes: expect.objectContaining({ - 'url.full': { type: 'string', value: `http://localhost:${port}${url}` }, - 'http.request.method': { type: 'string', value: 'POST' }, - 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, - 'http.request.header.content-type': { type: 'array', value: [contentType] }, - }), - }); - expect(serverSpan?.attributes['http.request.body.data'], contentType).toEqual( - expectedBody === undefined ? undefined : { type: 'string', value: expectedBody }, - ); - }, - ); + test('correctly captures plain text request data', async () => { + const container = await getContainer(1); + expect(findSegmentSpan(container)).toMatchObject({ + name: 'POST /test-post', + attributes: expect.objectContaining({ + 'url.full': { + type: 'string', + value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post\?case=1$/), + }, + 'http.request.method': { type: 'string', value: 'POST' }, + 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, + 'http.request.header.content-type': { type: 'array', value: ['text/plain'] }, + 'http.request.body.data': { type: 'string', value: 'some plain text' }, + }), + }); + }); + + test('correctly captures text buffer request data', async () => { + const container = await getContainer(2); + expect(findSegmentSpan(container)).toMatchObject({ + name: 'POST /test-post', + attributes: expect.objectContaining({ + 'url.full': { + type: 'string', + value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post\?case=2$/), + }, + 'http.request.method': { type: 'string', value: 'POST' }, + 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, + 'http.request.header.content-type': { type: 'array', value: ['application/octet-stream'] }, + 'http.request.body.data': { type: 'string', value: 'some plain text in buffer' }, + }), + }); + }); + + test('correctly captures non-text buffer request data', async () => { + const container = await getContainer(3); + expect(findSegmentSpan(container)).toMatchObject({ + name: 'POST /test-post', + attributes: expect.objectContaining({ + 'url.full': { + type: 'string', + value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post\?case=3$/), + }, + 'http.request.method': { type: 'string', value: 'POST' }, + 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, + 'http.request.header.content-type': { type: 'array', value: ['application/octet-stream'] }, + // This is some non-ascii string representation + 'http.request.body.data': { type: 'string', value: expect.any(String) }, + }), + }); + }); + + test('correctly ignores request data', async () => { + const container = await getContainer(4); + const serverSpan = findSegmentSpan(container); + expect(serverSpan).toMatchObject({ + name: 'POST /test-post-ignore-body', + attributes: expect.objectContaining({ + 'url.full': { + type: 'string', + value: expect.stringMatching(/^http:\/\/localhost:(\d+)\/test-post-ignore-body\?case=4$/), + }, + 'http.request.method': { type: 'string', value: 'POST' }, + 'http.request.header.user-agent': { type: 'array', value: [expect.stringContaining('')] }, + 'http.request.header.content-type': { type: 'array', value: ['application/octet-stream'] }, + }), + }); + // Ensure the request body has been ignored + expect(serverSpan?.attributes['http.request.body.data']).toBeUndefined(); + }); }); }); }); diff --git a/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts b/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts index d22b404100e4..3607b4fb5a7a 100644 --- a/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts +++ b/dev-packages/node-integration-tests/suites/express/tracing/routing/test.ts @@ -37,9 +37,12 @@ describe('express tracing', () => { return (await scenario).get(path)!; } + let errorScenario: ReturnType | undefined; + let arrayScenario: ReturnType | undefined; + let regexScenario: ReturnType | undefined; + test('should create and send segment spans for Express routes and spans for middlewares.', async () => { const container = { items: await getSpans('/test/express') }; - const serverSpan = findSegmentSpan(container); expect(serverSpan).toMatchObject({ @@ -78,10 +81,8 @@ describe('express tracing', () => { }), ); }); - test('names router and request handler spans after their route', async () => { const container = { items: await getSpans('/test/router/user/123') }; - const handlerSpan = findExpressSpan(container, 'request_handler'); expect(handlerSpan?.name).toBe('/test/router/user/:id'); // The name has to stay in step with the attribute it comes from. @@ -97,10 +98,8 @@ describe('express tracing', () => { value: 'middleware', }); }); - test('should set a correct segment name for routes specified in RegEx', async () => { const container = { items: await getSpans('/test/regex') }; - expect(findSegmentSpan(container)).toMatchObject({ name: 'GET /\\/test\\/regex/', span_id: expect.stringMatching(/[a-f\d]{16}/), @@ -114,10 +113,8 @@ describe('express tracing', () => { }), }); }); - test('nests a sub-router route handler span under the router span', async () => { const container = { items: await getSpans('/test/router/user/42') }; - expect(findSegmentSpan(container)?.name).toBe('GET /test/router/user/:id'); const routerSpan = findExpressSpan(container, 'router'); @@ -136,20 +133,16 @@ describe('express tracing', () => { // whole sub-stack it dispatched (~the 100ms handler delay). expect(routerDurationMs).toBeGreaterThan(50); }); - test('keeps the parameter in a route mounted under a parameterized sub-router path', async () => { const container = { items: await getSpans('/test/version/v1/user') }; - const serverSpan = findSegmentSpan(container); // The `:version` parameter must be preserved — using the concrete value // (`/test/version/v1/user`) would explode route cardinality. expect(serverSpan?.name).toBe('GET /test/version/:version/user'); expect(serverSpan?.attributes['sentry.segment.name.source']).toEqual({ type: 'string', value: 'route' }); }); - test('handles root page correctly', async () => { const container = { items: await getSpans('/') }; - expect(findSegmentSpan(container)).toMatchObject({ name: 'GET /', span_id: expect.stringMatching(/[a-f\d]{16}/), @@ -165,73 +158,87 @@ describe('express tracing', () => { }), }); }); - - // With span streaming, child spans are sent as they end, before the response status code is - // known, so `ignoreStatusCodes` has no effect and these routes are captured like any other. - const cases = [ + test.each([ { status_code: 401, url: '/401', status_message: 'unauthenticated', name: 'GET /401', source: 'route' }, { status_code: 402, url: '/402', status_message: 'invalid_argument', name: 'GET /402', source: 'route' }, { status_code: 403, url: '/403', status_message: 'permission_denied', name: 'GET /403', source: 'route' }, // Without a matching route the name must not carry the URL path. { status_code: 404, url: '/does-not-exist', status_message: 'not_found', name: 'GET', source: 'url' }, - ]; - let errorScenario: ReturnType | undefined; - test.each(cases)('handles $url route correctly', async ({ status_code, url, status_message, name, source }) => { - errorScenario ??= runScenario( - cases.map(({ url }) => url), - true, - ); - const container = { items: (await errorScenario).get(url)! }; - expect(findSegmentSpan(container), url).toMatchObject({ + ])( + 'handles %s route correctly', + async ({ + status_code, + url, + status_message, name, - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'error', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: source }, - 'sentry.status.message': { type: 'string', value: status_message }, - 'http.response.status_code': { type: 'integer', value: status_code }, - 'http.request.method': { type: 'string', value: 'GET' }, - 'url.full': { type: 'string', value: expect.stringMatching(url) }, - 'url.path': { type: 'string', value: url }, - }), - }); - }); - - const segments = ['array1', 'array5']; - let arrayScenario: ReturnType | undefined; - test.each(segments)('sets the segment name for route arrays: %s', async segment => { - arrayScenario ??= runScenario(segments.map(segment => `/test/${segment}`)); - const container = { items: (await arrayScenario).get(`/test/${segment}`)! }; - expect(findSegmentSpan(container), segment).toMatchObject({ - name: 'GET /test/array1,/\\/test\\/array[2-9]/', - span_id: expect.stringMatching(/[a-f\d]{16}/), - trace_id: expect.stringMatching(/[a-f\d]{32}/), - status: 'ok', - attributes: expect.objectContaining({ - 'sentry.op': { type: 'string', value: 'http.server' }, - 'sentry.segment.name.source': { type: 'string', value: 'route' }, - 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, - 'http.response.status_code': { type: 'integer', value: 200 }, - }), - }); - }); - - const regexSegments = [ - 'arr/545', - 'arr/required', - 'arr/requiredPath', - 'arr/required/lastParam', - 'arr55/required/lastParam', - 'arr/requiredPath/optionalPath/', - 'arr/requiredPath/optionalPath/lastParam', - ]; - let regexScenario: ReturnType | undefined; - test.each(regexSegments)('handles complex regexes in route arrays: %s', async segment => { - regexScenario ??= runScenario(regexSegments.map(segment => `/test/${segment}`)); + source, + }: { + status_code: number; + url: string; + status_message: string; + name: string; + source: string; + }) => { + errorScenario ??= runScenario(['/401', '/402', '/403', '/does-not-exist'], true); + const container = { items: (await errorScenario).get(url)! }; + expect(findSegmentSpan(container)).toMatchObject({ + name, + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'error', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: source }, + 'sentry.status.message': { type: 'string', value: status_message }, + 'http.response.status_code': { type: 'integer', value: status_code }, + 'http.request.method': { type: 'string', value: 'GET' }, + 'url.full': { type: 'string', value: expect.stringMatching(url) }, + 'url.path': { type: 'string', value: url }, + }), + }); + }, + ); + test.each([['array1'], ['array5']])( + 'should set a correct segment name for routes consisting of arrays of routes for %p', + async (segment: string) => { + arrayScenario ??= runScenario(['/test/array1', '/test/array5']); + const container = { items: (await arrayScenario).get(`/test/${segment}`)! }; + expect(findSegmentSpan(container)).toMatchObject({ + name: 'GET /test/array1,/\\/test\\/array[2-9]/', + span_id: expect.stringMatching(/[a-f\d]{16}/), + trace_id: expect.stringMatching(/[a-f\d]{32}/), + status: 'ok', + attributes: expect.objectContaining({ + 'sentry.op': { type: 'string', value: 'http.server' }, + 'sentry.segment.name.source': { type: 'string', value: 'route' }, + 'url.full': { type: 'string', value: expect.stringMatching(`/test/${segment}$`) }, + 'http.response.status_code': { type: 'integer', value: 200 }, + }), + }); + }, + ); + test.each([ + ['arr/545'], + ['arr/required'], + ['arr/requiredPath'], + ['arr/required/lastParam'], + ['arr55/required/lastParam'], + ['arr/requiredPath/optionalPath/'], + ['arr/requiredPath/optionalPath/lastParam'], + ])('should handle more complex regexes in route arrays correctly for %p', async (segment: string) => { + regexScenario ??= runScenario( + [ + 'arr/545', + 'arr/required', + 'arr/requiredPath', + 'arr/required/lastParam', + 'arr55/required/lastParam', + 'arr/requiredPath/optionalPath/', + 'arr/requiredPath/optionalPath/lastParam', + ].map(segment => `/test/${segment}`), + ); const container = { items: (await regexScenario).get(`/test/${segment}`)! }; - expect(findSegmentSpan(container), segment).toMatchObject({ + expect(findSegmentSpan(container)).toMatchObject({ name: 'GET /test/arr/:id,/\\/test\\/arr\\d*\\/required(path)?(\\/optionalPath)?\\/(lastParam)?/', span_id: expect.stringMatching(/[a-f\d]{16}/), trace_id: expect.stringMatching(/[a-f\d]{32}/), diff --git a/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts b/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts index a74499f18ddb..b024fa5eb162 100644 --- a/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts +++ b/dev-packages/node-integration-tests/suites/express/with-http/maxIncomingRequestBodySize/test.ts @@ -1,5 +1,5 @@ import { afterAll, describe, expect } from 'vitest'; -import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../../utils/runner'; +import { cleanupChildProcesses, createEsmAndCjsTests, type createRunner } from '../../../../utils/runner'; import { generateEmojiPayload, generateEmojiPayloadString, @@ -12,131 +12,205 @@ const MAX_GENERAL = 1024 * 1024; // 1MB const MAX_MEDIUM = 10_000; const MAX_SMALL = 1000; -interface BodyCase { - name: string; - path?: string; - body: { data: string }; - expectedBody?: string; +function createBodyScenario( + runnerFactory: () => ReturnType, + bodies: { data: string }[], + paths = bodies.map(() => '/test-body-size'), +) { + let scenario: ReturnType | undefined; + async function runScenario() { + const runner = runnerFactory().unordered(); + const spans = bodies.map((_, index) => + runner.collectStreamedSpansUntilSegment(span => span.attributes['url.query']?.value === `case=${index}`), + ); + const started = runner.start(); + for (const [index, body] of bodies.entries()) { + await started.makeRequest('post', `${paths[index]}?case=${index}`, { + headers: { 'Content-Type': 'application/json' }, + data: JSON.stringify(body), + }); + } + await started.completed(); + return Promise.all(spans); + } + return async (index: number) => { + scenario ??= runScenario(); + return { items: (await scenario)[index]! }; + }; } -const configs: { name: string; instrument: string; cases: BodyCase[] }[] = [ - { - name: 'default (medium)', - instrument: 'instrument-default.mjs', - cases: [ - { - name: 'captures medium request bodies with default setting (medium)', - body: generatePayload(MAX_MEDIUM), - expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)), - }, - { - name: 'truncates large request bodies with default setting (medium)', - body: generatePayload(MAX_MEDIUM + 1), - expectedBody: generatePayloadString(MAX_MEDIUM, true), - }, - ], - }, - { - name: 'small (overrides disabled httpBodies)', - instrument: 'instrument-small.mjs', - cases: [ - { - name: 'captures request bodies because the explicit size overrides dataCollection.httpBodies', - body: generatePayload(MAX_SMALL), - expectedBody: JSON.stringify(generatePayload(MAX_SMALL)), - }, - { - name: 'truncates too large request bodies with "small" setting', - body: generatePayload(MAX_SMALL + 1), - expectedBody: generatePayloadString(MAX_SMALL, true), - }, - { - name: 'truncates too large non-ASCII request bodies with "small" setting', - body: generateEmojiPayload(MAX_SMALL + 1), - expectedBody: generateEmojiPayloadString(250, true), - }, - ], - }, - { - name: 'none', - instrument: 'instrument-none.mjs', - cases: [ - { name: 'does not capture any request bodies with "none" setting', body: generatePayload(500) }, - { - name: 'does not capture any request bodies with "none" setting and "ignoreRequestBody"', - path: '/ignore-request-body', - body: generatePayload(500), - }, - ], - }, - { - name: 'always', - instrument: 'instrument-always.mjs', - cases: [ - { - name: 'captures maximum allowed request body length with "always" setting', - body: generatePayload(MAX_GENERAL), - expectedBody: JSON.stringify(generatePayload(MAX_GENERAL)), - }, - { - name: 'captures large request bodies with "always" setting but respects maximum size limit', - body: generatePayload(MAX_GENERAL + 1), - expectedBody: generatePayloadString(MAX_GENERAL, true), - }, - ], - }, - { - name: 'medium', - instrument: 'instrument-medium.mjs', - cases: [ - { - name: 'keeps medium request bodies with "medium" setting', - body: generatePayload(MAX_MEDIUM), - expectedBody: JSON.stringify(generatePayload(MAX_MEDIUM)), - }, - { - name: 'truncates large request bodies with "medium" setting', - body: generatePayload(MAX_MEDIUM + 1), - expectedBody: generatePayloadString(MAX_MEDIUM, true), - }, - ], - }, -]; - -describe.each(configs)('maxRequestBodySize: $name', ({ instrument, cases }) => { +describe('express with httpIntegration and not defined maxRequestBodySize', () => { afterAll(() => { cleanupChildProcesses(); }); - createEsmAndCjsTests(__dirname, 'scenario.mjs', instrument, (createRunner, test) => { - let scenario: ReturnType | undefined; - async function runScenario() { - const runner = createRunner().unordered(); - const spans = cases.map((_, index) => - runner.collectStreamedSpansUntilSegment(span => span.attributes['url.query']?.value === `case=${index}`), - ); - const started = runner.start(); - - for (const [index, { path = '/test-body-size', body }] of cases.entries()) { - await started.makeRequest('post', `${path}?case=${index}`, { - headers: { 'Content-Type': 'application/json' }, - data: JSON.stringify(body), - }); - } - await started.completed(); - return Promise.all(spans); - } + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-default.mjs', (createRunner, test) => { + const getContainer = createBodyScenario(createRunner, [ + generatePayload(MAX_MEDIUM), + generatePayload(MAX_MEDIUM + 1), + ]); + + test('captures medium request bodies with default setting (medium)', async () => { + const container = await getContainer(0); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_MEDIUM)) }, + }), + }); + }); + + test('truncates large request bodies with default setting (medium)', async () => { + const container = await getContainer(1); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_MEDIUM, true) }, + }), + }); + }); + }); +}); + +describe('express with httpIntegration and maxRequestBodySize: "none"', () => { + afterAll(() => { + cleanupChildProcesses(); + }); - test.each(cases.map((entry, index) => ({ ...entry, index })))( - '$name', - async ({ index, path = '/test-body-size', expectedBody }) => { - scenario ??= runScenario(); - const serverSpan = (await scenario)[index]!.find(span => span.is_segment); - expect(serverSpan?.name).toBe(`POST ${path}`); - expect(serverSpan?.attributes['http.request.body.data']).toEqual( - expectedBody === undefined ? undefined : { type: 'string', value: expectedBody }, - ); - }, + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-none.mjs', (createRunner, test) => { + const getContainer = createBodyScenario( + createRunner, + [generatePayload(500), generatePayload(500)], + ['/test-body-size', '/ignore-request-body'], ); + + test('does not capture any request bodies with "none" setting', async () => { + const container = await getContainer(0); + const serverSpan = container.items.find(item => item.is_segment); + expect(serverSpan?.name).toBe('POST /test-body-size'); + expect(serverSpan?.attributes['http.request.body.data']).toBeUndefined(); + }); + + test('does not capture any request bodies with "none" setting and "ignoreRequestBody"', async () => { + const container = await getContainer(0); + const serverSpan = container.items.find(item => item.is_segment); + expect(serverSpan?.name).toBe('POST /test-body-size'); + expect(serverSpan?.attributes['http.request.body.data']).toBeUndefined(); + const ignoredContainer = await getContainer(1); + const ignoredServerSpan = ignoredContainer.items.find(item => item.is_segment); + expect(ignoredServerSpan?.name).toBe('POST /ignore-request-body'); + expect(ignoredServerSpan?.attributes['http.request.body.data']).toBeUndefined(); + }); + }); +}); + +describe('express with httpIntegration and maxRequestBodySize: "always"', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-always.mjs', (createRunner, test) => { + const getContainer = createBodyScenario(createRunner, [ + generatePayload(MAX_GENERAL), + generatePayload(MAX_GENERAL + 1), + ]); + + test('captures maximum allowed request body length with "always" setting', async () => { + const container = await getContainer(0); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_GENERAL)) }, + }), + }); + }); + + test('captures large request bodies with "always" setting but respects maximum size limit', async () => { + const container = await getContainer(1); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_GENERAL, true) }, + }), + }); + }); + }); +}); + +describe('express with httpIntegration and maxRequestBodySize: "small"', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-small.mjs', (createRunner, test) => { + const getContainer = createBodyScenario(createRunner, [ + generatePayload(MAX_SMALL), + generatePayload(MAX_SMALL + 1), + generateEmojiPayload(MAX_SMALL + 1), + ]); + + test('captures request bodies because the explicit size overrides dataCollection.httpBodies', async () => { + const container = await getContainer(0); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_SMALL)) }, + }), + }); + }); + + test('truncates too large request bodies with "small" setting', async () => { + const container = await getContainer(1); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_SMALL, true) }, + }), + }); + }); + + test('truncates too large non-ASCII request bodies with "small" setting', async () => { + const container = await getContainer(2); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + // 250 emojis, each 4 bytes in UTF-8 (resulting in 1000 bytes --> MAX_SMALL) + 'http.request.body.data': { type: 'string', value: generateEmojiPayloadString(250, true) }, + }), + }); + }); + }); +}); + +describe('express with httpIntegration and maxRequestBodySize: "medium"', () => { + afterAll(() => { + cleanupChildProcesses(); + }); + + createEsmAndCjsTests(__dirname, 'scenario.mjs', 'instrument-medium.mjs', (createRunner, test) => { + const getContainer = createBodyScenario(createRunner, [ + generatePayload(MAX_MEDIUM), + generatePayload(MAX_MEDIUM + 1), + ]); + + test('keeps medium request bodies with "medium" setting', async () => { + const container = await getContainer(0); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: JSON.stringify(generatePayload(MAX_MEDIUM)) }, + }), + }); + }); + + test('truncates large request bodies with "medium" setting', async () => { + const container = await getContainer(1); + expect(container.items.find(item => item.is_segment)).toMatchObject({ + name: 'POST /test-body-size', + attributes: expect.objectContaining({ + 'http.request.body.data': { type: 'string', value: generatePayloadString(MAX_MEDIUM, true) }, + }), + }); + }); }); });