Skip to content
Draft
Show file tree
Hide file tree
Changes from all 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
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Client, TransactionSource } from '@sentry/core';
import {
_INTERNAL_filterKeyValueData,
browserPerformanceTimeOrigin,
debug,
parseBaggageHeader,
Expand Down Expand Up @@ -129,7 +130,7 @@ export function pagesRouterInstrumentPageLoad(client: Client): void {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'pageload',
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.pageload.nextjs.pages_router_instrumentation',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: route ? 'route' : 'url',
...(params && client.getOptions().sendDefaultPii && { ...params }),
...(params && getFilteredRouteParams(params, client)),
},
},
{ sentryTrace, baggage },
Expand Down Expand Up @@ -185,6 +186,17 @@ function getNextRouteFromPathname(pathname: string): string | undefined {
});
}

function getFilteredRouteParams(params: ParsedUrlQuery, client: Client): Record<string, string> {
const { queryParams } = client.getDataCollectionOptions();
const stringParams: Record<string, string> = {};
for (const [key, value] of Object.entries(params)) {
if (typeof value === 'string') {
stringParams[key] = value;
}
}
return _INTERNAL_filterKeyValueData(stringParams, queryParams);
}

/**
* Converts a Next.js style route to a regular expression that matches on pathnames (no query params or URL fragments).
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,19 @@ export function addHeadersAsAttributes(
return {};
}

const client = getClient();
const { httpHeaders } = client?.getDataCollectionOptions() ?? { httpHeaders: { request: false, response: false } };

if (httpHeaders.request === false) {
return {};
}

const headersDict: Record<string, string | string[] | undefined> =
headers instanceof Headers || (typeof headers === 'object' && 'get' in headers)
? winterCGHeadersToDict(headers as Headers)
: headers;

const headerAttributes = httpHeadersToSpanAttributes(headersDict, getClient()?.getOptions().sendDefaultPii ?? false);
const headerAttributes = httpHeadersToSpanAttributes(headersDict, httpHeaders.request === true);

if (span) {
span.setAttributes(headerAttributes);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,13 @@ export function setUrlProcessingMetadata(event: Event): void {
return;
}

// Only add URL if sendDefaultPii is enabled, as URLs may contain PII
const client = getClient();
if (!client?.getOptions().sendDefaultPii) {
if (!client) {
return;
}

// todo(v11): Replace with a dataCollection gate once URL collection is covered by the spec.
if (!client.getOptions().sendDefaultPii) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ async function withServerActionInstrumentationImplementation<A extends (...args:
callback: A,
): Promise<ReturnType<A>> {
return withIsolationScope(async isolationScope => {
const sendDefaultPii = getClient()?.getOptions().sendDefaultPii;
const shouldRecordResponse = getClient()?.getDataCollectionOptions().httpBodies.includes('outgoingResponse');

let sentryTraceHeader;
let baggageHeader;
Expand Down Expand Up @@ -138,7 +138,7 @@ async function withServerActionInstrumentationImplementation<A extends (...args:
}
});

if (options.recordResponse !== undefined ? options.recordResponse : sendDefaultPii) {
if (options.recordResponse !== undefined ? options.recordResponse : shouldRecordResponse) {
getIsolationScope().setExtra('server_action_result', result);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,9 @@ describe('pagesRouterInstrumentPageLoad', () => {
'sentry.op': 'pageload',
'sentry.origin': 'auto.pageload.nextjs.pages_router_instrumentation',
'sentry.source': 'route',
user: 'lforst',
id: '1337',
q: '42',
},
},
],
Expand Down Expand Up @@ -190,6 +193,9 @@ describe('pagesRouterInstrumentPageLoad', () => {
const client = {
emit,
getOptions: () => ({}),
getDataCollectionOptions: () => ({
queryParams: { deny: [] },
}),
} as unknown as Client;

pagesRouterInstrumentPageLoad(client);
Expand Down
63 changes: 63 additions & 0 deletions packages/nextjs/test/utils/addHeadersAsAttributes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import * as SentryCore from '@sentry/core';
import { describe, expect, it, vi } from 'vitest';
import { addHeadersAsAttributes } from '../../src/common/utils/addHeadersAsAttributes';

describe('addHeadersAsAttributes', () => {
it('returns empty object when headers are undefined', () => {
expect(addHeadersAsAttributes(undefined)).toEqual({});
});

it('returns empty object when httpHeaders.request is false', () => {
vi.spyOn(SentryCore, 'getClient').mockReturnValue({
getDataCollectionOptions: () => ({
httpHeaders: { request: false, response: true },
}),
} as unknown as SentryCore.Client);

const result = addHeadersAsAttributes({ 'content-type': 'application/json' });
expect(result).toEqual({});
});

it('includes all headers with sensitive filtering when httpHeaders.request is true', () => {
vi.spyOn(SentryCore, 'getClient').mockReturnValue({
getDataCollectionOptions: () => ({
httpHeaders: { request: true, response: true },
}),
} as unknown as SentryCore.Client);

const result = addHeadersAsAttributes({
'content-type': 'application/json',
accept: 'text/html',
});

expect(result).toMatchObject({
'http.request.header.content_type': 'application/json',
'http.request.header.accept': 'text/html',
});
});

it('applies stricter PII filtering when httpHeaders.request is a deny list', () => {
vi.spyOn(SentryCore, 'getClient').mockReturnValue({
getDataCollectionOptions: () => ({
httpHeaders: { request: { deny: [] }, response: true },
}),
} as unknown as SentryCore.Client);

const result = addHeadersAsAttributes({
'content-type': 'application/json',
accept: 'text/html',
});

expect(result).toMatchObject({
'http.request.header.content_type': 'application/json',
'http.request.header.accept': 'text/html',
});
});

it('returns empty object when no client is available', () => {
vi.spyOn(SentryCore, 'getClient').mockReturnValue(undefined);

const result = addHeadersAsAttributes({ 'content-type': 'application/json' });
expect(result).toEqual({});
});
});
101 changes: 101 additions & 0 deletions packages/nextjs/test/utils/setUrlProcessingMetadata.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { Event } from '@sentry/core';
import * as SentryCore from '@sentry/core';
import { describe, expect, it, vi } from 'vitest';
import { setUrlProcessingMetadata } from '../../src/common/utils/setUrlProcessingMetadata';

function makeTransactionEvent(overrides?: Partial<Event>): Event {
return {
type: 'transaction',
contexts: {
trace: {
op: 'http.server',
data: {
'next.route': '/api/users/[id]',
'http.target': '/api/users/123',
},
},
},
sdkProcessingMetadata: {
capturedSpanIsolationScope: {
getScopeData: () => ({
sdkProcessingMetadata: {
normalizedRequest: {
headers: {
'x-forwarded-proto': 'https',
host: 'example.com',
},
},
},
}),
},
},
...overrides,
};
}

describe('setUrlProcessingMetadata', () => {
it('skips non-transaction events', () => {
const event = makeTransactionEvent({ type: undefined });
setUrlProcessingMetadata(event);
// No error thrown, nothing changed
});

it('skips when sendDefaultPii is false', () => {
vi.spyOn(SentryCore, 'getClient').mockReturnValue({
getOptions: () => ({ sendDefaultPii: false }),
} as unknown as SentryCore.Client);

const scopeData = {
sdkProcessingMetadata: {
normalizedRequest: {
headers: { host: 'example.com' },
},
},
};

const event = makeTransactionEvent({
sdkProcessingMetadata: {
capturedSpanIsolationScope: { getScopeData: () => scopeData },
},
});

setUrlProcessingMetadata(event);
expect(scopeData.sdkProcessingMetadata.normalizedRequest).not.toHaveProperty('url');
});

it('adds URL when sendDefaultPii is true', () => {
vi.spyOn(SentryCore, 'getClient').mockReturnValue({
getOptions: () => ({ sendDefaultPii: true }),
} as unknown as SentryCore.Client);

const scopeData = {
sdkProcessingMetadata: {
normalizedRequest: {
headers: {
'x-forwarded-proto': 'https',
host: 'example.com',
},
},
},
};

const event: Event = {
type: 'transaction',
contexts: {
trace: {
op: 'http.server',
data: {
'next.route': '/api/users/[id]',
'http.target': '/api/users/123',
},
},
},
sdkProcessingMetadata: {
capturedSpanIsolationScope: { getScopeData: () => scopeData },
},
};

setUrlProcessingMetadata(event);
expect(scopeData.sdkProcessingMetadata.normalizedRequest.url).toBe('https://example.com/api/users/123');
});
});
Loading