Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
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
11 changes: 6 additions & 5 deletions packages/bun/src/integrations/bunserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,9 @@ function wrapRequestHandler<T extends RouteHandler = RouteHandler>(
routeName = route;
}

Object.assign(
attributes,
httpHeadersToSpanAttributes(request.headers.toJSON(), getClient()?.getOptions().sendDefaultPii ?? false),
);
const sendDefaultPii = getClient()?.getOptions().sendDefaultPii ?? false;

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

isolationScope.setSDKProcessingMetadata({
normalizedRequest: {
Expand Down Expand Up @@ -238,10 +237,12 @@ function wrapRequestHandler<T extends RouteHandler = RouteHandler>(
const response = (await target.apply(thisArg, args)) as Response | undefined;
if (response?.status) {
setHttpStatus(span, response.status);

isolationScope.setContext('response', {
headers: response.headers.toJSON(),
status_code: response.status,
});

span.setAttributes(httpHeadersToSpanAttributes(response.headers.toJSON(), sendDefaultPii, 'response'));
}
return response;
} catch (e) {
Expand Down
15 changes: 13 additions & 2 deletions packages/bun/test/integrations/bunserver.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
import * as SentryCore from '@sentry/core';
import { afterEach, beforeAll, beforeEach, describe, expect, spyOn, test } from 'bun:test';
import { instrumentBunServe } from '../../src/integrations/bunserver';
import type { Span } from '@sentry/core';

describe('Bun Serve Integration', () => {
const mockSpan = SentryCore.startInactiveSpan({ name: 'test span' });
const setAttributesSpy = spyOn(mockSpan, 'setAttributes');
const continueTraceSpy = spyOn(SentryCore, 'continueTrace');
const startSpanSpy = spyOn(SentryCore, 'startSpan');
const startSpanSpy = spyOn(SentryCore, 'startSpan').mockImplementation((_opts, cb) => {
return cb(mockSpan as unknown as Span);
});

beforeAll(() => {
instrumentBunServe();
Expand All @@ -13,6 +18,7 @@ describe('Bun Serve Integration', () => {
beforeEach(() => {
startSpanSpy.mockClear();
continueTraceSpy.mockClear();
setAttributesSpy.mockClear();
});

// Fun fact: Bun = 2 21 14 :)
Expand All @@ -27,7 +33,7 @@ describe('Bun Serve Integration', () => {
test('generates a transaction around a request', async () => {
const server = Bun.serve({
async fetch(_req) {
return new Response('Bun!');
return new Response('Bun!', { headers: new Headers({ 'x-custom': 'value' }) });
},
port,
});
Expand All @@ -52,12 +58,17 @@ describe('Bun Serve Integration', () => {
'http.request.header.connection': 'keep-alive',
'http.request.header.host': expect.any(String),
'http.request.header.user_agent': expect.stringContaining('Bun'),
// 'http.response.header.x_bearer_token': '[Filtered]',
Comment thread
Lms24 marked this conversation as resolved.
Outdated
},
op: 'http.server',
name: 'GET /users',
},
expect.any(Function),
);

expect(setAttributesSpy).toHaveBeenCalledWith({
'http.response.header.x_custom': 'value',
});
});

test('generates a post transaction', async () => {
Expand Down
34 changes: 24 additions & 10 deletions packages/core/src/utils/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,22 @@ const SENSITIVE_HEADER_SNIPPETS = [
const PII_HEADER_SNIPPETS = ['x-forwarded-', '-user'];

/**
* Converts incoming HTTP request headers to OpenTelemetry span attributes following semantic conventions.
* Header names are converted to the format: http.request.header.<key>
* Converts incoming HTTP request or response headers to OpenTelemetry span attributes following semantic conventions.
* Header names are converted to the format: http.<request|response>.header.<key>
* where <key> is the header name in lowercase with dashes converted to underscores.
*
* @param lifecycle - The lifecycle of the headers, either 'request' or 'response'
*
* @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-request-header
* @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-response-header
*
* @see https://getsentry.github.io/sentry-conventions/attributes/http/#http-request-header-key
* @see https://getsentry.github.io/sentry-conventions/attributes/http/#http-response-header-key
*/
export function httpHeadersToSpanAttributes(
headers: Record<string, string | string[] | undefined>,
sendDefaultPii: boolean = false,
lifecycle: 'request' | 'response' = 'request',
): Record<string, string> {
const spanAttributes: Record<string, string> = {};

Expand Down Expand Up @@ -189,10 +196,17 @@ export function httpHeadersToSpanAttributes(

const lowerCasedCookieKey = cookieKey.toLowerCase();

addSpanAttribute(spanAttributes, lowerCasedHeaderKey, lowerCasedCookieKey, cookieValue, sendDefaultPii);
addSpanAttribute(
spanAttributes,
lowerCasedHeaderKey,
lowerCasedCookieKey,
cookieValue,
sendDefaultPii,
lifecycle,
);
}
} else {
addSpanAttribute(spanAttributes, lowerCasedHeaderKey, '', value, sendDefaultPii);
addSpanAttribute(spanAttributes, lowerCasedHeaderKey, '', value, sendDefaultPii, lifecycle);
}
});
} catch {
Expand All @@ -212,15 +226,15 @@ function addSpanAttribute(
cookieKey: string,
value: string | string[] | undefined,
sendPii: boolean,
lifecycle: 'request' | 'response',
): void {
const normalizedKey = cookieKey
? `http.request.header.${normalizeAttributeKey(headerKey)}.${normalizeAttributeKey(cookieKey)}`
: `http.request.header.${normalizeAttributeKey(headerKey)}`;

const headerValue = handleHttpHeader(cookieKey || headerKey, value, sendPii);
if (headerValue !== undefined) {
spanAttributes[normalizedKey] = headerValue;
if (headerValue == null) {
return;
}

const normalizedKey = `http.${lifecycle}.header.${normalizeAttributeKey(headerKey)}${cookieKey ? `.${normalizeAttributeKey(cookieKey)}` : ''}`;
spanAttributes[normalizedKey] = headerValue;
}

function handleHttpHeader(
Expand Down
40 changes: 40 additions & 0 deletions packages/core/test/lib/utils/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,46 @@ describe('request utils', () => {
'http.request.header.x_saml_token': '[Filtered]',
});
});

it('returns response header attributes if `lifecycle` is "response"', () => {
const headers = {
Host: 'example.com',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate',
Connection: 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'no-cache',
'X-Forwarded-For': '192.168.1.1',
Authorization: '[Filtered]',
'x-bearer-token': 'bearer',
'x-sso-token': 'sso',
'x-saml-token': 'saml',
'Set-Cookie': 'session=456',
Cookie: 'session=abc123',
};

const result = httpHeadersToSpanAttributes(headers, false, 'response');

expect(result).toEqual({
'http.response.header.host': 'example.com',
'http.response.header.user_agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'http.response.header.accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'http.response.header.accept_language': 'en-US,en;q=0.5',
'http.response.header.accept_encoding': 'gzip, deflate',
'http.response.header.connection': 'keep-alive',
'http.response.header.upgrade_insecure_requests': '1',
'http.response.header.cache_control': 'no-cache',
'http.response.header.x_forwarded_for': '[Filtered]',
'http.response.header.authorization': '[Filtered]',
'http.response.header.x_bearer_token': '[Filtered]',
'http.response.header.x_saml_token': '[Filtered]',
'http.response.header.x_sso_token': '[Filtered]',
'http.response.header.set_cookie.session': '[Filtered]',
'http.response.header.cookie.session': '[Filtered]',
});
});
});
});
});
8 changes: 7 additions & 1 deletion packages/deno/src/wrap-deno-request-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,9 +95,15 @@ export const wrapDenoRequestHandler = <Addr extends Deno.Addr = Deno.Addr>(
res = await handler();
setHttpStatus(span, res.status);
isolationScope.setContext('response', {
headers: Object.fromEntries(res.headers),
status_code: res.status,
});
span.setAttributes(
httpHeadersToSpanAttributes(
Object.fromEntries(res.headers),
client.getOptions().sendDefaultPii,
Comment thread
cursor[bot] marked this conversation as resolved.
Outdated
'response',
),
);
} catch (e) {
span.end();
captureException(e, {
Expand Down
5 changes: 2 additions & 3 deletions packages/deno/test/deno-serve.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,9 +317,8 @@ Deno.test('Deno.serve should capture request headers and set response context',

// Check response context
assertEquals(transaction?.contexts?.response?.status_code, 201);
assertExists(transaction?.contexts?.response?.headers);
assertEquals(transaction?.contexts?.response?.headers?.['content-type'], 'text/plain');
assertEquals(transaction?.contexts?.response?.headers?.['x-custom-header'], 'test');
assertEquals(transaction?.contexts?.trace?.data?.['http.response.header.content_type'], 'text/plain');
assertEquals(transaction?.contexts?.trace?.data?.['http.response.header.x_custom_header'], 'test');
});

Deno.test('Deno.serve should support distributed tracing with sentry-trace header', async () => {
Expand Down
Loading