Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,31 @@ test('App router transactions should be attached to the pageload request span',
expect(pageloadTraceId).toBeTruthy();
expect(serverTransaction.contexts?.trace?.trace_id).toBe(pageloadTraceId);
});

test('extracts HTTP request headers as span attributes', async ({ baseURL }) => {
const serverTransactionPromise = waitForTransaction('nextjs-15', async transactionEvent => {
return transactionEvent?.transaction === 'GET /pageload-tracing';
});

await fetch(`${baseURL}/pageload-tracing`, {
headers: {
'User-Agent': 'Custom-NextJS-Agent/15.0',
'Content-Type': 'text/html',
'X-NextJS-Test': 'nextjs-header-value',
Accept: 'text/html, application/xhtml+xml',
'X-Framework': 'Next.js',
},
});

const serverTransaction = await serverTransactionPromise;

expect(serverTransaction.contexts?.trace?.data).toEqual(
expect.objectContaining({
'http.request.header.user_agent': ['Custom-NextJS-Agent/15.0'],
'http.request.header.content_type': ['text/html'],
'http.request.header.x_nextjs_test': ['nextjs-header-value'],
'http.request.header.accept': ['text/html, application/xhtml+xml'],
'http.request.header.x_framework': ['Next.js'],
}),
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -208,3 +208,34 @@ test('Sends an API route transaction for an errored route', async ({ baseURL })
measurements: {},
});
});

test('Extracts HTTP request headers as span attributes', async ({ baseURL }) => {
const transactionEventPromise = waitForTransaction('node-express', transactionEvent => {
return (
transactionEvent?.contexts?.trace?.op === 'http.server' &&
transactionEvent?.transaction === 'GET /test-transaction'
);
});

await fetch(`${baseURL}/test-transaction`, {
headers: {
'User-Agent': 'Custom-Agent/1.0 (Test)',
'Content-Type': 'application/json',
'X-Custom-Header': 'test-value',
Accept: 'application/json, text/plain',
Authorization: 'Bearer test-token-123',
},
});

const transactionEvent = await transactionEventPromise;

expect(transactionEvent.contexts?.trace?.data).toEqual(
expect.objectContaining({
'http.request.header.user_agent': ['Custom-Agent/1.0 (Test)'],
'http.request.header.content_type': ['application/json'],
'http.request.header.x_custom_header': ['test-value'],
'http.request.header.accept': ['application/json, text/plain'],
'http.request.header.authorization': ['Bearer test-token-123'],
}),
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,31 @@ test('does not send transactions for build asset folder "_nuxt"', async ({ page

expect(transactionEvent.transaction).toBe('GET /test-param/:param()');
});

test('extracts HTTP request headers as span attributes', async ({ baseURL }) => {
const transactionPromise = waitForTransaction('nuxt-3', transactionEvent => {
return transactionEvent.transaction.includes('GET /api/test-param/');
});

await fetch(`${baseURL}/api/test-param/headers-test`, {
headers: {
'User-Agent': 'Custom-Nuxt-Agent/3.0',
'Content-Type': 'application/json',
'X-Nuxt-Test': 'nuxt-header-value',
Accept: 'application/json, text/html',
'X-Framework': 'Nuxt',
},
});

const transaction = await transactionPromise;

expect(transaction.contexts?.trace?.data).toEqual(
expect.objectContaining({
'http.request.header.user_agent': ['Custom-Nuxt-Agent/3.0'],
'http.request.header.content_type': ['application/json'],
'http.request.header.x_nuxt_test': ['nuxt-header-value'],
'http.request.header.accept': ['application/json, text/html'],
'http.request.header.x_framework': ['Nuxt'],
}),
);
});
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,31 @@ test('server pageload request span has nested request span for sub request', asy
]),
);
});

test('extracts HTTP request headers as span attributes', async ({ page, baseURL }) => {
const serverTxnEventPromise = waitForTransaction('sveltekit-2', txnEvent => {
return txnEvent?.transaction === 'GET /api/users';
});

await fetch(`${baseURL}/api/users`, {
headers: {
'User-Agent': 'Custom-SvelteKit-Agent/1.0',
'Content-Type': 'application/json',
'X-Test-Header': 'sveltekit-test-value',
Accept: 'application/json',
'X-Framework': 'SvelteKit',
},
});

const serverTxnEvent = await serverTxnEventPromise;

expect(serverTxnEvent.contexts?.trace?.data).toEqual(
expect.objectContaining({
'http.request.header.user_agent': ['Custom-SvelteKit-Agent/1.0'],
'http.request.header.content_type': ['application/json'],
'http.request.header.x_test_header': ['sveltekit-test-value'],
'http.request.header.accept': ['application/json'],
'http.request.header.x_framework': ['SvelteKit'],
}),
);
});
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran prettier fix and that's why this and the following three files are included in the diff.

Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,5 @@ Sentry.init({
tracesSampleRate: 1.0,
sendDefaultPii: true,
transport: loggingTransport,
integrations: [
Sentry.anthropicAIIntegration(),
nodeContextIntegration(),
],
integrations: [Sentry.anthropicAIIntegration(), nodeContextIntegration()],
});
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,5 @@ Sentry.init({
sendDefaultPii: false,
transport: loggingTransport,
// Force include the integration
integrations: [
Sentry.anthropicAIIntegration(),
nodeContextIntegration(),
],
integrations: [Sentry.anthropicAIIntegration(), nodeContextIntegration()],
});
Original file line number Diff line number Diff line change
Expand Up @@ -101,5 +101,3 @@ async function run() {
}

run();


Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ class MockAnthropic {
// Create messages object with create and countTokens methods
this.messages = {
create: this._messagesCreate.bind(this),
countTokens: this._messagesCountTokens.bind(this)
countTokens: this._messagesCountTokens.bind(this),
};

this.models = {
Expand Down Expand Up @@ -56,8 +56,8 @@ class MockAnthropic {

// For countTokens, just return input_tokens
return {
input_tokens: 15
}
input_tokens: 15,
};
}

async _modelsRetrieve(modelId) {
Expand All @@ -69,7 +69,7 @@ class MockAnthropic {
id: modelId,
name: modelId,
created_at: 1715145600,
model: modelId, // Add model field to match the check in addResponseAttributes
model: modelId, // Add model field to match the check in addResponseAttributes
};
}
}
Expand All @@ -86,9 +86,7 @@ async function run() {
await client.messages.create({
model: 'claude-3-haiku-20240307',
system: 'You are a helpful assistant.',
messages: [
{ role: 'user', content: 'What is the capital of France?' },
],
messages: [{ role: 'user', content: 'What is the capital of France?' }],
temperature: 0.7,
max_tokens: 100,
});
Expand All @@ -106,9 +104,7 @@ async function run() {
// Third test: count tokens with cached tokens
await client.messages.countTokens({
model: 'claude-3-haiku-20240307',
messages: [
{ role: 'user', content: 'What is the capital of France?' },
],
messages: [{ role: 'user', content: 'What is the capital of France?' }],
});

// Fourth test: models.retrieve
Expand Down
2 changes: 2 additions & 0 deletions packages/astro/src/index.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ export {
getSpanStatusFromHttpCode,
getTraceData,
getTraceMetaTags,
httpHeadersToSpanAttributes,
winterCGHeadersToDict,
graphqlIntegration,
hapiIntegration,
httpIntegration,
Expand Down
3 changes: 3 additions & 0 deletions packages/astro/src/server/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ import {
getClient,
getCurrentScope,
getTraceMetaTags,
httpHeadersToSpanAttributes,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
setHttpStatus,
startSpan,
winterCGHeadersToDict,
withIsolationScope,
} from '@sentry/node';
import type { APIContext, MiddlewareResponseHandler, RoutePart } from 'astro';
Expand Down Expand Up @@ -154,6 +156,7 @@ async function instrumentRequest(
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: source,
method,
url: stripUrlQueryAndFragment(ctx.url.href),
...httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers)),
};

if (ctx.url.search) {
Expand Down
44 changes: 44 additions & 0 deletions packages/astro/test/server/middleware.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,50 @@ describe('sentryMiddleware', () => {
expect(resultFromNext).toStrictEqual(nextResult);
});

it('includes HTTP request headers as span attributes', async () => {
const middleware = handleRequest();
const headers = new Headers({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Content-Type': 'application/json',
'X-Custom-Header': 'custom-value',
Accept: 'application/json, text/plain',
});

const ctx = {
request: {
method: 'POST',
url: '/api/data',
headers,
},
url: new URL('https://myDomain.io/api/data'),
params: {},
};
const next = vi.fn(() => nextResult);

// @ts-expect-error, a partial ctx object is fine here
await middleware(ctx, next);

expect(startSpanSpy).toHaveBeenCalledWith(
{
attributes: {
'sentry.origin': 'auto.http.astro',
method: 'POST',
url: 'https://mydomain.io/api/data',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',
'http.request.header.user_agent': ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'],
'http.request.header.content_type': ['application/json'],
'http.request.header.x_custom_header': ['custom-value'],
'http.request.header.accept': ['application/json, text/plain'],
},
name: 'POST /api/data',
op: 'http.server',
},
expect.any(Function),
);

expect(next).toHaveBeenCalled();
});

it("sets source route if the url couldn't be decoded correctly", async () => {
const middleware = handleRequest();
const ctx = {
Expand Down
3 changes: 3 additions & 0 deletions packages/bun/src/integrations/bunserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
captureException,
continueTrace,
defineIntegration,
httpHeadersToSpanAttributes,
isURLObjectRelative,
parseStringToURLObject,
SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD,
Expand Down Expand Up @@ -205,6 +206,8 @@ function wrapRequestHandler<T extends RouteHandler = RouteHandler>(
routeName = route;
}

Object.assign(attributes, httpHeadersToSpanAttributes(request.headers.toJSON()));

isolationScope.setSDKProcessingMetadata({
normalizedRequest: {
url: request.url,
Expand Down
50 changes: 50 additions & 0 deletions packages/bun/test/integrations/bunserver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
await server.stop();

expect(startSpanSpy).toHaveBeenCalledTimes(1);
expect(startSpanSpy).toHaveBeenLastCalledWith(

Check failure on line 38 in packages/bun/test/integrations/bunserver.test.ts

View workflow job for this annotation

GitHub Actions / Bun Unit Tests

error: expect(received).toHaveBeenLastCalledWith(...expected)

[ { "attributes": { + "http.request.header.accept": [ + "*/*", + ], + "http.request.header.accept_encoding": [ + "gzip, deflate, br, zstd", + ], + "http.request.header.connection": [ + "keep-alive", + ], + "http.request.header.host": [ + "localhost:22118", + ], + "http.request.header.user_agent": [ + "Bun/1.2.21", + ], "http.request.method": "GET", "sentry.origin": "auto.http.bun.serve", "sentry.source": "url", "url.domain": "localhost", "url.full": "http://localhost:22118/users?id=123", "url.path": "/users", "url.port": "22118", "url.query": "?id=123", "url.scheme": "http:", }, "name": "GET /users", "op": "http.server", }, - Any<Function>, + [Function: AsyncFunction], ] - Expected - 1 + Received + 16 at <anonymous> (/home/runner/work/sentry-javascript/sentry-javascript/packages/bun/test/integrations/bunserver.test.ts:38:26)
{
attributes: {
'sentry.origin': 'auto.http.bun.serve',
Expand Down Expand Up @@ -70,7 +70,7 @@
await server.stop();

expect(startSpanSpy).toHaveBeenCalledTimes(1);
expect(startSpanSpy).toHaveBeenLastCalledWith(

Check failure on line 73 in packages/bun/test/integrations/bunserver.test.ts

View workflow job for this annotation

GitHub Actions / Bun Unit Tests

error: expect(received).toHaveBeenLastCalledWith(...expected)

[ { "attributes": { + "http.request.header.accept": [ + "*/*", + ], + "http.request.header.accept_encoding": [ + "gzip, deflate, br, zstd", + ], + "http.request.header.connection": [ + "keep-alive", + ], + "http.request.header.content_length": [ + "0", + ], + "http.request.header.host": [ + "localhost:22119", + ], + "http.request.header.user_agent": [ + "Bun/1.2.21", + ], "http.request.method": "POST", "sentry.origin": "auto.http.bun.serve", "sentry.source": "url", "url.domain": "localhost", "url.full": "http://localhost:22119/", "url.path": "/", "url.port": "22119", "url.scheme": "http:", }, "name": "POST /", "op": "http.server", }, - Any<Function>, + [Function: AsyncFunction], ] - Expected - 1 + Received + 19 at <anonymous> (/home/runner/work/sentry-javascript/sentry-javascript/packages/bun/test/integrations/bunserver.test.ts:73:26)
{
attributes: {
'sentry.origin': 'auto.http.bun.serve',
Expand Down Expand Up @@ -128,6 +128,56 @@
expect(startSpanSpy).toHaveBeenCalledTimes(1);
});

test('includes HTTP request headers as span attributes', async () => {
const server = Bun.serve({
async fetch(_req) {
return new Response('Headers test!');
},
port,
});

// Make request with custom headers
await fetch(`http://localhost:${port}/api/test`, {
method: 'POST',
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Content-Type': 'application/json',
'X-Custom-Header': 'custom-value',
Accept: 'application/json, text/plain',
Authorization: 'Bearer token123',
},
body: JSON.stringify({ test: 'data' }),
});

await server.stop();

// Verify span was created with header attributes
expect(startSpanSpy).toHaveBeenCalledTimes(1);
expect(startSpanSpy).toHaveBeenLastCalledWith(
expect.objectContaining({
attributes: expect.objectContaining({
'sentry.origin': 'auto.http.bun.serve',
'http.request.method': 'POST',
'sentry.source': 'url',
'url.path': '/api/test',
'url.full': `http://localhost:${port}/api/test`,
'url.port': port.toString(),
'url.scheme': 'http:',
'url.domain': 'localhost',
// HTTP headers as span attributes following OpenTelemetry semantic conventions
'http.request.header.user_agent': ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'],
'http.request.header.content_type': ['application/json'],
'http.request.header.x_custom_header': ['custom-value'],
'http.request.header.accept': ['application/json, text/plain'],
'http.request.header.authorization': ['Bearer token123'],
}),
op: 'http.server',
name: 'POST /api/test',
}),
expect.any(Function),
);
});

test('skips span creation for OPTIONS and HEAD requests', async () => {
const server = Bun.serve({
async fetch(_req) {
Expand Down
4 changes: 4 additions & 0 deletions packages/cloudflare/src/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ import {
continueTrace,
flush,
getHttpSpanDetailsFromUrlObject,
httpHeadersToSpanAttributes,
parseStringToURLObject,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
setHttpStatus,
startSpan,
winterCGHeadersToDict,
withIsolationScope,
} from '@sentry/core';
import type { CloudflareOptions } from './client';
Expand Down Expand Up @@ -64,6 +66,8 @@ export function wrapRequestHandler(
attributes['user_agent.original'] = userAgentHeader;
}

Object.assign(attributes, httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers)));

attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP] = 'http.server';

addCloudResourceContext(isolationScope);
Expand Down
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ export {
httpRequestToRequestData,
extractQueryParamsFromUrl,
headersToDict,
httpHeadersToSpanAttributes,
} from './utils/request';
export { DEFAULT_ENVIRONMENT } from './constants';
export { addBreadcrumb } from './breadcrumbs';
Expand Down
Loading
Loading