From fbff9ef9f825184a4334862b98817f90f374ed8f Mon Sep 17 00:00:00 2001 From: Charly Gomez Date: Mon, 23 Nov 2026 10:56:06 +0100 Subject: [PATCH 1/2] feat(core): Gate URL fragments behind urlQueryParams Fragments can carry the same secrets as query strings: OAuth and OIDC login redirects return tokens in the fragment (#access_token=...), and hash-based routing puts its query string there (#/callback?token=...). Following data collection spec 0.19.0, collected URLs and url.fragment now filter key=value pairs in the fragment like query params, and drop the fragment when urlQueryParams is off. Anchors and hash route paths are kept as-is. Co-Authored-By: Claude Opus 5.5 --- packages/astro/src/server/middleware.ts | 3 +- packages/browser/src/tracing/request.ts | 4 +- packages/core/src/fetch.ts | 8 +++- packages/core/src/index.ts | 6 ++- packages/core/src/integrations/fetch.ts | 4 +- .../http/add-outgoing-request-breadcrumb.ts | 4 +- .../integrations/http/server-subscription.ts | 8 +++- .../data-collection/filterCollectedUrl.ts | 14 +++++- .../data-collection/filterQueryParams.ts | 21 ++++++--- .../data-collection/filterUrlFragment.ts | 30 +++++++++++++ .../utils/data-collection/filterUrlQuery.ts | 32 +++++++------- packages/core/src/utils/url.ts | 8 +++- .../filterCollectedUrl.test.ts | 37 +++++++++++++++- .../data-collection/filterUrlFragment.test.ts | 43 +++++++++++++++++++ .../data-collection/filterUrlQuery.test.ts | 34 ++++++++++++--- .../src/rules/no-unfiltered-url-attributes.js | 17 +++++--- .../http/httpServerSpansIntegration.ts | 3 +- .../node-fetch/undici-instrumentation.ts | 3 +- .../node/src/utils/outgoingFetchRequest.ts | 3 +- 19 files changed, 228 insertions(+), 54 deletions(-) create mode 100644 packages/core/src/utils/data-collection/filterUrlFragment.ts create mode 100644 packages/core/test/lib/utils/data-collection/filterUrlFragment.test.ts diff --git a/packages/astro/src/server/middleware.ts b/packages/astro/src/server/middleware.ts index d6b9dfc2d4d1..625ce1919e4a 100644 --- a/packages/astro/src/server/middleware.ts +++ b/packages/astro/src/server/middleware.ts @@ -36,6 +36,7 @@ import { winterCGRequestToRequestData, withIsolationScope, filterCollectedUrl, + filterCollectedUrlFragment, filterCollectedUrlQuery, } from '@sentry/core'; import { @@ -233,7 +234,7 @@ async function instrumentRequestStartHttpServerSpan( } attributes[URL_QUERY] = filterCollectedUrlQuery(getUrlQuery(ctx.url.search)); - attributes[URL_FRAGMENT] = getUrlFragment(ctx.url.hash); + attributes[URL_FRAGMENT] = filterCollectedUrlFragment(getUrlFragment(ctx.url.hash)); const transactionName = `${method} ${parametrizedRoute || ctx.url.pathname}`; diff --git a/packages/browser/src/tracing/request.ts b/packages/browser/src/tracing/request.ts index 251cc55197db..a88b556aff44 100644 --- a/packages/browser/src/tracing/request.ts +++ b/packages/browser/src/tracing/request.ts @@ -23,7 +23,7 @@ import { } from '@sentry/core'; import { startInactiveSpan } from '@sentry/core/browser'; import type { HandlerDataXhr, SentryWrappedXMLHttpRequest, XhrHint } from '@sentry/browser-utils'; -import { filterCollectedUrl, filterCollectedUrlQuery } from '@sentry/core'; +import { filterCollectedUrl, filterCollectedUrlFragment, filterCollectedUrlQuery } from '@sentry/core'; import { addPerformanceInstrumentationHandler, addXhrInstrumentationHandler, @@ -428,7 +428,7 @@ function xhrCallback( [URL_PATH]: host ? parsedUrl?.path || '/' : undefined, [URL_SCHEME]: host ? parsedUrl?.protocol : undefined, [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(parsedUrl?.search)), - [URL_FRAGMENT]: getUrlFragment(parsedUrl?.hash), + [URL_FRAGMENT]: filterCollectedUrlFragment(getUrlFragment(parsedUrl?.hash)), }, }) : new SentryNonRecordingSpan(); diff --git a/packages/core/src/fetch.ts b/packages/core/src/fetch.ts index 1a94766aeae8..48137359a6f1 100644 --- a/packages/core/src/fetch.ts +++ b/packages/core/src/fetch.ts @@ -26,7 +26,11 @@ import type { HandlerDataFetch } from './types/instrument'; import type { ResponseHookInfo } from './types/request'; import type { Span, SpanAttributes, SpanOrigin } from './types/span'; import { SENTRY_BAGGAGE_KEY_PREFIX } from './utils/baggage'; -import { filterCollectedUrl, filterCollectedUrlQuery } from './utils/data-collection/filterCollectedUrl'; +import { + filterCollectedUrl, + filterCollectedUrlFragment, + filterCollectedUrlQuery, +} from './utils/data-collection/filterCollectedUrl'; import { hasSpansEnabled } from './utils/hasSpansEnabled'; import { isInstanceOf, isRequest } from './utils/is'; import { getActiveSpan } from './utils/spanUtils'; @@ -411,7 +415,7 @@ function getFetchSpanAttributes( } } attributes[URL_QUERY] = filterCollectedUrlQuery(getUrlQuery(parsedUrl.search), client); - attributes[URL_FRAGMENT] = getUrlFragment(parsedUrl.hash); + attributes[URL_FRAGMENT] = filterCollectedUrlFragment(getUrlFragment(parsedUrl.hash), client); } return attributes; } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 3e88558a3212..b0abda61d0b0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -83,7 +83,11 @@ export { export { filterKeyValueData as _INTERNAL_filterKeyValueData } from './utils/data-collection/filterKeyValueData'; export { filterCookies as _INTERNAL_filterCookies } from './utils/data-collection/filterCookies'; export { filterQueryParams as _INTERNAL_filterQueryParams } from './utils/data-collection/filterQueryParams'; -export { filterCollectedUrl, filterCollectedUrlQuery } from './utils/data-collection/filterCollectedUrl'; +export { + filterCollectedUrl, + filterCollectedUrlFragment, + filterCollectedUrlQuery, +} from './utils/data-collection/filterCollectedUrl'; export { envToBool } from './utils/envToBool'; export { getVercelEnv } from './utils/vercel'; export { applyScopeDataToEvent, mergeScopeData, getCombinedScopeData } from './utils/scopeData'; diff --git a/packages/core/src/integrations/fetch.ts b/packages/core/src/integrations/fetch.ts index 54c63ac12db2..4c47b890b311 100644 --- a/packages/core/src/integrations/fetch.ts +++ b/packages/core/src/integrations/fetch.ts @@ -11,7 +11,7 @@ import type { HandlerDataFetch } from '../types/instrument'; import type { Integration, IntegrationFn } from '../types/integration'; import type { Span, SpanOrigin } from '../types/span'; import { getBreadcrumbLogLevelFromHttpStatusCode } from '../utils/breadcrumb-log-level'; -import { filterCollectedUrlQuery } from '../utils/data-collection/filterCollectedUrl'; +import { filterCollectedUrlFragment, filterCollectedUrlQuery } from '../utils/data-collection/filterCollectedUrl'; import { isSentryRequestUrl } from '../utils/isSentryRequestUrl'; import { LRUMap } from '../utils/lru'; import { shouldPropagateTraceForUrl } from '../utils/tracePropagationTargets'; @@ -167,7 +167,7 @@ function createBreadcrumb(handlerData: HandlerDataFetch, client: Client): void { [HTTP_REQUEST_METHOD]: handlerData.fetchData.method, url: getSanitizedUrlString(parsedUrl), [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(parsedUrl.search), client), - [URL_FRAGMENT]: getUrlFragment(parsedUrl.hash), + [URL_FRAGMENT]: filterCollectedUrlFragment(getUrlFragment(parsedUrl.hash), client), }; if (handlerData.error) { diff --git a/packages/core/src/integrations/http/add-outgoing-request-breadcrumb.ts b/packages/core/src/integrations/http/add-outgoing-request-breadcrumb.ts index 1b365bf061ba..447f8be13bb7 100644 --- a/packages/core/src/integrations/http/add-outgoing-request-breadcrumb.ts +++ b/packages/core/src/integrations/http/add-outgoing-request-breadcrumb.ts @@ -1,7 +1,7 @@ import { HTTP_REQUEST_METHOD, URL_FRAGMENT, URL_QUERY } from '@sentry/conventions/attributes'; import { addBreadcrumb } from '../../breadcrumbs'; import { getBreadcrumbLogLevelFromHttpStatusCode } from '../../utils/breadcrumb-log-level'; -import { filterCollectedUrlQuery } from '../../utils/data-collection/filterCollectedUrl'; +import { filterCollectedUrlFragment, filterCollectedUrlQuery } from '../../utils/data-collection/filterCollectedUrl'; import { getSanitizedUrlString, getUrlFragment, getUrlQuery, parseUrl } from '../../utils/url'; import { getRequestUrlFromClientRequest } from './get-request-url'; import type { HttpClientRequest, HttpIncomingMessage } from './types'; @@ -28,7 +28,7 @@ export function addOutgoingRequestBreadcrumb( // eslint-disable-next-line typescript/no-deprecated [HTTP_REQUEST_METHOD]: request.method || 'GET', [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(parsedUrl.search)), - [URL_FRAGMENT]: getUrlFragment(parsedUrl.hash), + [URL_FRAGMENT]: filterCollectedUrlFragment(getUrlFragment(parsedUrl.hash)), }, type: 'http', level, diff --git a/packages/core/src/integrations/http/server-subscription.ts b/packages/core/src/integrations/http/server-subscription.ts index 7acf305b6a5c..85afb3c8692d 100644 --- a/packages/core/src/integrations/http/server-subscription.ts +++ b/packages/core/src/integrations/http/server-subscription.ts @@ -74,7 +74,11 @@ import { HTTP_RESPONSE_STATUS_TEXT, } from '@sentry/conventions/attributes'; import { HTTP_SERVER } from '@sentry/conventions/op'; -import { filterCollectedUrl, filterCollectedUrlQuery } from '../../utils/data-collection/filterCollectedUrl'; +import { + filterCollectedUrl, + filterCollectedUrlFragment, + filterCollectedUrlQuery, +} from '../../utils/data-collection/filterCollectedUrl'; import { getClientIPAddress } from '../../utils/clientIPAddress'; // Tree-shakable guard to remove all code related to tracing @@ -380,7 +384,7 @@ function buildServerSpanWrap( [URL_FULL]: filterCollectedUrl(fullUrl, client), [URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment, [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(urlObj?.search), client), - [URL_FRAGMENT]: getUrlFragment(urlObj?.hash), + [URL_FRAGMENT]: filterCollectedUrlFragment(getUrlFragment(urlObj?.hash), client), [HTTP_REQUEST_METHOD]: method, [NETWORK_PROTOCOL_NAME]: 'http', [NETWORK_PROTOCOL_VERSION]: httpVersion, diff --git a/packages/core/src/utils/data-collection/filterCollectedUrl.ts b/packages/core/src/utils/data-collection/filterCollectedUrl.ts index ef8930d97541..f1e9b1de9eff 100644 --- a/packages/core/src/utils/data-collection/filterCollectedUrl.ts +++ b/packages/core/src/utils/data-collection/filterCollectedUrl.ts @@ -2,6 +2,7 @@ import type { Client } from '../../client'; import { getClient } from '../../currentScopes'; import type { CollectBehavior } from '../../types/datacollection'; import { filterQueryParams } from './filterQueryParams'; +import { filterUrlFragment } from './filterUrlFragment'; import { filterUrlQuery } from './filterUrlQuery'; function urlQueryParamsBehavior(client: Client | undefined): CollectBehavior { @@ -10,7 +11,8 @@ function urlQueryParamsBehavior(client: Client | undefined): CollectBehavior { } /** - * Applies `dataCollection.urlQueryParams` to a URL the SDK collected itself, for use as `url.full`. + * Applies `dataCollection.urlQueryParams` to the query and fragment of a URL the SDK collected itself, for use + * as `url.full`. * * Call this at every site where instrumentation records a URL. Routing the SDK's own URLs through a * helper is what makes the filtering provenance-correct: a URL a user attaches themselves never passes @@ -34,3 +36,13 @@ export function filterCollectedUrl(url: string | undefined, client?: Client): st export function filterCollectedUrlQuery(query: string | undefined, client?: Client): string | undefined { return query ? filterQueryParams(query, urlQueryParamsBehavior(client)) : undefined; } + +/** + * Applies `dataCollection.urlQueryParams` to a URL fragment (without the leading `#`) the SDK collected + * itself, for use as `url.fragment`. Returns `undefined` when the fragment must not be collected at all. + * + * See {@link filterCollectedUrl} for why this is a helper and why passing `client` is preferred. + */ +export function filterCollectedUrlFragment(fragment: string | undefined, client?: Client): string | undefined { + return fragment ? filterUrlFragment(fragment, urlQueryParamsBehavior(client)) : undefined; +} diff --git a/packages/core/src/utils/data-collection/filterQueryParams.ts b/packages/core/src/utils/data-collection/filterQueryParams.ts index 6383f758aacd..141887a35a67 100644 --- a/packages/core/src/utils/data-collection/filterQueryParams.ts +++ b/packages/core/src/utils/data-collection/filterQueryParams.ts @@ -2,6 +2,19 @@ import type { CollectBehavior } from '../../types/datacollection'; import { FILTERED_VALUE } from './filtering-snippets'; import { shouldFilterDataKey } from './filterKeyValueData'; +/** + * Filters a single `key=value` (or bare `key`) query pair according to a `CollectBehavior`. + * + * The key is decoded for filtering, while the pair keeps its original encoding. + */ +export function filterQueryPair(pair: string, behavior: CollectBehavior): string { + const separatorIndex = pair.indexOf('='); + const encodedKey = separatorIndex === -1 ? pair : pair.slice(0, separatorIndex); + const key = new URLSearchParams(`${encodedKey}=`).keys().next().value; + + return key !== undefined && shouldFilterDataKey(key, behavior) ? `${encodedKey}=${FILTERED_VALUE}` : pair; +} + /** * Filters a query parameter string according to a `CollectBehavior`. * @@ -14,12 +27,6 @@ export function filterQueryParams(queryString: string, behavior: CollectBehavior return queryString .split('&') - .map(pair => { - const separatorIndex = pair.indexOf('='); - const encodedKey = separatorIndex === -1 ? pair : pair.slice(0, separatorIndex); - const key = new URLSearchParams(`${encodedKey}=`).keys().next().value; - - return key !== undefined && shouldFilterDataKey(key, behavior) ? `${encodedKey}=${FILTERED_VALUE}` : pair; - }) + .map(pair => filterQueryPair(pair, behavior)) .join('&'); } diff --git a/packages/core/src/utils/data-collection/filterUrlFragment.ts b/packages/core/src/utils/data-collection/filterUrlFragment.ts new file mode 100644 index 000000000000..b11a8ac017c7 --- /dev/null +++ b/packages/core/src/utils/data-collection/filterUrlFragment.ts @@ -0,0 +1,30 @@ +import type { CollectBehavior } from '../../types/datacollection'; +import { filterQueryPair } from './filterQueryParams'; + +/** + * Filters a URL fragment (without the leading `#`) according to a `CollectBehavior`. + * + * Fragments can carry the same secrets as query strings, e.g. OAuth implicit-flow redirects + * (`#access_token=...`) or hash-based routing (`#/callback?token=...`). `key=value` pairs are filtered like + * query params: after the first `?` if there is one, across the whole fragment otherwise. Segments without + * a `=`, such as an anchor (`details`) or a hash route path (`/settings`), are kept as-is so they stay useful + * for debugging. + * + * Returns `undefined` when the fragment must not be collected at all. + */ +export function filterUrlFragment(fragment: string, behavior: CollectBehavior): string | undefined { + if (!fragment || behavior === false) { + return undefined; + } + + const queryStart = fragment.indexOf('?'); + const prefix = queryStart === -1 ? '' : fragment.slice(0, queryStart + 1); + const pairs = queryStart === -1 ? fragment : fragment.slice(queryStart + 1); + + const filtered = pairs + .split('&') + .map(segment => (segment.includes('=') ? filterQueryPair(segment, behavior) : segment)) + .join('&'); + + return `${prefix}${filtered}`; +} diff --git a/packages/core/src/utils/data-collection/filterUrlQuery.ts b/packages/core/src/utils/data-collection/filterUrlQuery.ts index 712f3e8808c3..a0c475097658 100644 --- a/packages/core/src/utils/data-collection/filterUrlQuery.ts +++ b/packages/core/src/utils/data-collection/filterUrlQuery.ts @@ -1,31 +1,31 @@ import type { CollectBehavior } from '../../types/datacollection'; import { filterQueryParams } from './filterQueryParams'; +import { filterUrlFragment } from './filterUrlFragment'; /** - * Applies a `CollectBehavior` to the query string of a full URL, leaving every other URL component - * (scheme, host, path, fragment) untouched. + * Applies a `CollectBehavior` to the query string and fragment of a full URL, leaving every other URL + * component (scheme, host, path) untouched. * - * The query is located by string offsets rather than by parsing, so the URL is returned byte-for-byte - * apart from the query itself. This keeps relative URLs, non-HTTP schemes and unusual encodings intact, - * none of which survive a `URL` round-trip. + * The query and fragment are located by string offsets rather than by parsing, so the URL is returned + * byte-for-byte apart from those two parts. This keeps relative URLs, non-HTTP schemes and unusual encodings + * intact, none of which survive a `URL` round-trip. * - * Returns the URL with its query filtered, or with the query removed entirely when collection is off. + * Returns the URL with its query and fragment filtered, or with both removed entirely when collection is off. */ export function filterUrlQuery(url: string, behavior: CollectBehavior): string { // The fragment is delimited first: a `?` after a `#` belongs to the fragment, not the query. const fragmentStart = url.indexOf('#'); - const queryEnd = fragmentStart === -1 ? url.length : fragmentStart; + const beforeFragment = fragmentStart === -1 ? url : url.slice(0, fragmentStart); + const fragment = fragmentStart === -1 ? undefined : url.slice(fragmentStart + 1); - const queryStart = url.indexOf('?'); - if (queryStart === -1 || queryStart > queryEnd) { - return url; + const queryStart = beforeFragment.indexOf('?'); + let filteredUrl = beforeFragment; + if (queryStart !== -1) { + const filteredQuery = filterQueryParams(beforeFragment.slice(queryStart + 1), behavior); + filteredUrl = `${beforeFragment.slice(0, queryStart)}${filteredQuery ? `?${filteredQuery}` : ''}`; } - const prefix = url.slice(0, queryStart); - const query = url.slice(queryStart + 1, queryEnd); - const suffix = url.slice(queryEnd); + const filteredFragment = fragment === undefined ? undefined : filterUrlFragment(fragment, behavior); - const filtered = filterQueryParams(query, behavior); - - return filtered ? `${prefix}?${filtered}${suffix}` : `${prefix}${suffix}`; + return filteredFragment ? `${filteredUrl}#${filteredFragment}` : filteredUrl; } diff --git a/packages/core/src/utils/url.ts b/packages/core/src/utils/url.ts index 47d1776a1346..3aaa8f993285 100644 --- a/packages/core/src/utils/url.ts +++ b/packages/core/src/utils/url.ts @@ -16,7 +16,11 @@ import { import type { Client } from '../client'; import type { SpanAttributes } from '../types/span'; import type { TransactionSource } from '../types/transaction'; -import { filterCollectedUrl, filterCollectedUrlQuery } from './data-collection/filterCollectedUrl'; +import { + filterCollectedUrl, + filterCollectedUrlFragment, + filterCollectedUrlQuery, +} from './data-collection/filterCollectedUrl'; type PartialURL = { host?: string; @@ -233,7 +237,7 @@ export function getHttpSpanDetailsFromUrlObject( ); attributes[URL_QUERY] = filterCollectedUrlQuery(getUrlQuery(urlObject.search), client); - attributes[URL_FRAGMENT] = getUrlFragment(urlObject.hash); + attributes[URL_FRAGMENT] = filterCollectedUrlFragment(getUrlFragment(urlObject.hash), client); if (urlObject.pathname) { attributes[URL_PATH] = urlObject.pathname; if (urlObject.pathname === '/') { diff --git a/packages/core/test/lib/utils/data-collection/filterCollectedUrl.test.ts b/packages/core/test/lib/utils/data-collection/filterCollectedUrl.test.ts index 933254e83012..38dcb934bcad 100644 --- a/packages/core/test/lib/utils/data-collection/filterCollectedUrl.test.ts +++ b/packages/core/test/lib/utils/data-collection/filterCollectedUrl.test.ts @@ -1,7 +1,11 @@ import { describe, expect, it } from 'vitest'; import { withScope } from '../../../../src/currentScopes'; import type { CollectBehavior } from '../../../../src/types/datacollection'; -import { filterCollectedUrl, filterCollectedUrlQuery } from '../../../../src/utils/data-collection/filterCollectedUrl'; +import { + filterCollectedUrl, + filterCollectedUrlFragment, + filterCollectedUrlQuery, +} from '../../../../src/utils/data-collection/filterCollectedUrl'; import { getDefaultTestClientOptions, TestClient } from '../../../mocks/client'; function withUrlQueryParams(urlQueryParams: CollectBehavior | undefined, fn: () => T): T { @@ -33,6 +37,20 @@ describe('filterCollectedUrl', () => { expect(result).toBe('https://example.com/api'); }); + it('filters sensitive pairs in the fragment by default', () => { + const result = withUrlQueryParams(undefined, () => + filterCollectedUrl('https://example.com/callback#access_token=abc123&state=xyz'), + ); + + expect(result).toBe('https://example.com/callback#access_token=[Filtered]&state=xyz'); + }); + + it('strips the fragment when collection is off', () => { + const result = withUrlQueryParams(false, () => filterCollectedUrl('https://example.com/callback?a=1#details')); + + expect(result).toBe('https://example.com/callback'); + }); + it('honors allowList mode', () => { const result = withUrlQueryParams({ allow: ['page'] }, () => filterCollectedUrl('https://example.com/s?page=1&ref=x'), @@ -109,3 +127,20 @@ describe('filterCollectedUrlQuery', () => { ); }); }); + +describe('filterCollectedUrlFragment', () => { + it('filters sensitive pairs by default', () => { + expect(withUrlQueryParams(undefined, () => filterCollectedUrlFragment('access_token=abc&state=xyz'))).toBe( + 'access_token=[Filtered]&state=xyz', + ); + }); + + it('returns undefined when collection is off', () => { + expect(withUrlQueryParams(false, () => filterCollectedUrlFragment('details'))).toBeUndefined(); + }); + + it('returns undefined for an empty or missing fragment', () => { + expect(withUrlQueryParams(undefined, () => filterCollectedUrlFragment(''))).toBeUndefined(); + expect(withUrlQueryParams(undefined, () => filterCollectedUrlFragment(undefined))).toBeUndefined(); + }); +}); diff --git a/packages/core/test/lib/utils/data-collection/filterUrlFragment.test.ts b/packages/core/test/lib/utils/data-collection/filterUrlFragment.test.ts new file mode 100644 index 000000000000..04d1baa518aa --- /dev/null +++ b/packages/core/test/lib/utils/data-collection/filterUrlFragment.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest'; +import { filterUrlFragment } from '../../../../src/utils/data-collection/filterUrlFragment'; + +describe('filterUrlFragment', () => { + it('returns undefined when collection is off', () => { + expect(filterUrlFragment('access_token=abc&state=xyz', false)).toBeUndefined(); + expect(filterUrlFragment('details', false)).toBeUndefined(); + }); + + it('returns undefined for an empty fragment', () => { + expect(filterUrlFragment('', true)).toBeUndefined(); + }); + + it('filters sensitive key=value pairs across the whole fragment', () => { + expect(filterUrlFragment('access_token=abc&id_token=def&state=xyz', true)).toBe( + 'access_token=[Filtered]&id_token=[Filtered]&state=xyz', + ); + }); + + it('only treats pairs after the first `?` as params when there is one', () => { + expect(filterUrlFragment('/callback?token=abc&page=2', true)).toBe('/callback?token=[Filtered]&page=2'); + expect(filterUrlFragment('/a?token=abc?b', true)).toBe('/a?token=[Filtered]'); + }); + + it('keeps anchors and hash route paths as-is', () => { + expect(filterUrlFragment('details', true)).toBe('details'); + expect(filterUrlFragment('/settings', true)).toBe('/settings'); + expect(filterUrlFragment('token', true)).toBe('token'); + }); + + it('keeps segments without `=` next to filtered pairs', () => { + expect(filterUrlFragment('section&token=abc', true)).toBe('section&token=[Filtered]'); + }); + + it('honors allow and deny terms', () => { + expect(filterUrlFragment('page=1&ref=x', { allow: ['page'] })).toBe('page=1&ref=[Filtered]'); + expect(filterUrlFragment('page=1&utm_source=x', { deny: ['utm'] })).toBe('page=1&utm_source=[Filtered]'); + }); + + it('preserves value encoding', () => { + expect(filterUrlFragment('q=a%20b%26c&token=abc', true)).toBe('q=a%20b%26c&token=[Filtered]'); + }); +}); diff --git a/packages/core/test/lib/utils/data-collection/filterUrlQuery.test.ts b/packages/core/test/lib/utils/data-collection/filterUrlQuery.test.ts index 92be879fff90..84a62d30002c 100644 --- a/packages/core/test/lib/utils/data-collection/filterUrlQuery.test.ts +++ b/packages/core/test/lib/utils/data-collection/filterUrlQuery.test.ts @@ -43,13 +43,37 @@ describe('filterUrlQuery', () => { ); }); - it('removes the query but keeps the fragment', () => { - expect(filterUrlQuery('https://example.com/api?token=abc#results', false)).toBe( - 'https://example.com/api#results', + it('removes the query and the fragment', () => { + expect(filterUrlQuery('https://example.com/api?token=abc#results', false)).toBe('https://example.com/api'); + }); + + it('removes a fragment without a query', () => { + expect(filterUrlQuery('https://example.com/callback#access_token=abc123&state=xyz', false)).toBe( + 'https://example.com/callback', ); }); }); + describe('fragment', () => { + it('filters sensitive pairs in a login redirect fragment', () => { + const result = filterUrlQuery('https://example.com/callback#access_token=abc123&state=xyz', true); + + expect(result).toBe('https://example.com/callback#access_token=[Filtered]&state=xyz'); + }); + + it('filters pairs after the `?` of a hash route', () => { + const result = filterUrlQuery('https://example.com/#/callback?token=abc&page=2', true); + + expect(result).toBe('https://example.com/#/callback?token=[Filtered]&page=2'); + }); + + it('applies allowList mode to fragment pairs', () => { + const result = filterUrlQuery('https://example.com/#page=1&ref=x', { allow: ['page'] }); + + expect(result).toBe('https://example.com/#page=1&ref=[Filtered]'); + }); + }); + describe('allow / deny behaviors', () => { it('supports allowList mode', () => { const result = filterUrlQuery('https://example.com/s?page=1&ref=x&sort=name', { allow: ['page', 'sort'] }); @@ -76,9 +100,9 @@ describe('filterUrlQuery', () => { }); it('does not treat a `?` inside a fragment as a query', () => { - const result = filterUrlQuery('https://example.com/docs#/route?token=abc', true); + const result = filterUrlQuery('https://example.com/docs?page=1#/route?token=abc', true); - expect(result).toBe('https://example.com/docs#/route?token=abc'); + expect(result).toBe('https://example.com/docs?page=1#/route?token=[Filtered]'); }); }); }); diff --git a/packages/eslint-plugin-sdk/src/rules/no-unfiltered-url-attributes.js b/packages/eslint-plugin-sdk/src/rules/no-unfiltered-url-attributes.js index 168e9f3d80f9..db01cdf49644 100644 --- a/packages/eslint-plugin-sdk/src/rules/no-unfiltered-url-attributes.js +++ b/packages/eslint-plugin-sdk/src/rules/no-unfiltered-url-attributes.js @@ -1,28 +1,31 @@ 'use strict'; /** - * URL attributes carry the request query string, which `dataCollection.urlQueryParams` is supposed to - * gate. Filtering happens at the write site rather than centrally, so that a URL a user attaches - * themselves is left alone — which also means a site that forgets to filter leaks silently. + * URL attributes carry the request query string and fragment, which `dataCollection.urlQueryParams` is + * supposed to gate. Filtering happens at the write site rather than centrally, so that a URL a user + * attaches themselves is left alone — which also means a site that forgets to filter leaks silently. * * This rule requires every SDK-set URL attribute to go through `filterCollectedUrl` / - * `filterCollectedUrlQuery`. Values that cannot contain a query string (a bare pathname, a route - * template, a string literal) are fine — disable the rule on that line and say why. + * `filterCollectedUrlQuery` / `filterCollectedUrlFragment`. Values that cannot contain a query string + * (a bare pathname, a route template, a string literal) are fine — disable the rule on that line and say + * why. */ -// Attribute keys that carry a query string, by constant name and by literal value. +// Attribute keys that carry a query string or fragment, by constant name and by literal value. // `http.target` is not listed: the SDK no longer sets it, and its replacement `url.path` is a bare // pathname with nothing to filter. -const GUARDED_ATTRIBUTES = new Set(['URL_FULL', 'URL_QUERY', 'url.full', 'url.query']); +const GUARDED_ATTRIBUTES = new Set(['URL_FULL', 'URL_QUERY', 'URL_FRAGMENT', 'url.full', 'url.query', 'url.fragment']); // Helpers that apply `dataCollection.urlQueryParams`. const FILTER_FUNCTIONS = new Set([ 'filterCollectedUrl', 'filterCollectedUrlQuery', + 'filterCollectedUrlFragment', '_INTERNAL_filterCollectedUrl', '_INTERNAL_filterCollectedUrlQuery', 'filterUrlQuery', 'filterQueryParams', + 'filterUrlFragment', '_INTERNAL_filterQueryParams', 'normalizeAndFilterQueryString', ]); diff --git a/packages/node/src/integrations/http/httpServerSpansIntegration.ts b/packages/node/src/integrations/http/httpServerSpansIntegration.ts index e83205354efb..bf067c50e0da 100644 --- a/packages/node/src/integrations/http/httpServerSpansIntegration.ts +++ b/packages/node/src/integrations/http/httpServerSpansIntegration.ts @@ -53,6 +53,7 @@ import { getUrlFragment, getUrlQuery, filterCollectedUrl, + filterCollectedUrlFragment, filterCollectedUrlQuery, hasSpanStreamingEnabled, HTTP_SPAN_NAME_FALLBACK, @@ -183,7 +184,7 @@ const _httpServerSpansIntegration = ((options: HttpServerSpansIntegrationOptions [URL_FULL]: filterCollectedUrl(fullUrl, client), [URL_PATH]: urlObj?.pathname ?? httpTargetWithoutQueryFragment, [URL_QUERY]: filterCollectedUrlQuery(query, client), - [URL_FRAGMENT]: fragment, + [URL_FRAGMENT]: filterCollectedUrlFragment(fragment, client), [HTTP_REQUEST_METHOD]: normalizedRequest.method, [USER_AGENT_ORIGINAL]: userAgent, [URL_SCHEME]: scheme, diff --git a/packages/node/src/integrations/node-fetch/undici-instrumentation.ts b/packages/node/src/integrations/node-fetch/undici-instrumentation.ts index 83a8b31bbe39..dca3a5b8a095 100644 --- a/packages/node/src/integrations/node-fetch/undici-instrumentation.ts +++ b/packages/node/src/integrations/node-fetch/undici-instrumentation.ts @@ -38,6 +38,7 @@ import { getUrlFragment, getUrlQuery, filterCollectedUrl, + filterCollectedUrlFragment, filterCollectedUrlQuery, httpHeadersToSpanAttributes, } from '@sentry/core'; @@ -223,7 +224,7 @@ function onRequestCreated(config: NodeFetchOptions, { request }: RequestMessage) [URL_DOMAIN]: requestUrl.hostname || undefined, [URL_PATH]: requestUrl.pathname, [URL_QUERY]: filterCollectedUrlQuery(getUrlQuery(requestUrl.search)), - [URL_FRAGMENT]: getUrlFragment(requestUrl.hash), + [URL_FRAGMENT]: filterCollectedUrlFragment(getUrlFragment(requestUrl.hash)), [URL_SCHEME]: urlScheme, [SENTRY_ORIGIN]: 'auto.http.node_fetch', }; diff --git a/packages/node/src/utils/outgoingFetchRequest.ts b/packages/node/src/utils/outgoingFetchRequest.ts index af98b90a3f1d..892e9a1877d2 100644 --- a/packages/node/src/utils/outgoingFetchRequest.ts +++ b/packages/node/src/utils/outgoingFetchRequest.ts @@ -1,6 +1,7 @@ import { HTTP_REQUEST_METHOD, URL_FRAGMENT, URL_QUERY } from '@sentry/conventions/attributes'; import type { LRUMap, SanitizedRequestData, Span } from '@sentry/core'; import { + filterCollectedUrlFragment, filterCollectedUrlQuery, addBreadcrumb, getActiveSpan, @@ -261,7 +262,7 @@ function getBreadcrumbData(request: UndiciRequest): Partial Date: Mon, 23 Nov 2026 11:32:26 +0100 Subject: [PATCH 2/2] test(browser): Add integration tests for URL fragment filtering Cover the fetch span wiring end to end: sensitive fragment pairs are filtered by default, and the fragment is dropped when urlQueryParams is off. Co-Authored-By: Claude Opus 5.5 --- .../request/fetch-fragment-filtered/init.js | 10 ++++++ .../fetch-fragment-filtered/subject.js | 5 +++ .../fetch-fragment-filtered/template.html | 9 ++++++ .../request/fetch-fragment-filtered/test.ts | 31 +++++++++++++++++++ .../init.js | 11 +++++++ .../subject.js | 5 +++ .../template.html | 9 ++++++ .../test.ts | 31 +++++++++++++++++++ 8 files changed, 111 insertions(+) create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/init.js create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/subject.js create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/template.html create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/test.ts create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/init.js create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/subject.js create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/template.html create mode 100644 dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/test.ts diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/init.js b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/init.js new file mode 100644 index 000000000000..2469f6b6e191 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/init.js @@ -0,0 +1,10 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration({ instrumentPageLoad: false, instrumentNavigation: false })], + tracePropagationTargets: ['http://sentry-test-site.example'], + tracesSampleRate: 1, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/subject.js b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/subject.js new file mode 100644 index 000000000000..2a4292848938 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/subject.js @@ -0,0 +1,5 @@ +document.getElementById('btnFragment').addEventListener('click', async () => { + await Sentry.startSpan({ name: 'rootSpan' }, () => + fetch('http://sentry-test-site.example/callback?id=1#access_token=abc123&state=xyz'), + ); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/template.html b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/template.html new file mode 100644 index 000000000000..95dbd979befa --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/template.html @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/test.ts b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/test.ts new file mode 100644 index 000000000000..a8e165a935f8 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-filtered/test.ts @@ -0,0 +1,31 @@ +import { HTTP_CLIENT } from '@sentry/conventions/op'; +import { URL_FRAGMENT, URL_FULL, URL_QUERY } from '@sentry/conventions/attributes'; +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../utils/spanUtils'; + +sentryTest('filters sensitive pairs in the URL fragment of fetch request spans', async ({ getLocalTestUrl, page }) => { + if (shouldSkipTracingTest()) { + sentryTest.skip(); + } + + await page.route('http://sentry-test-site.example/*', route => route.fulfill({ body: 'ok' })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.goto(url); + + const requestPromise = waitForStreamedSpan(page, span => getSpanOp(span) === HTTP_CLIENT); + await page.locator('#btnFragment').click(); + const requestSpan = await requestPromise; + + expect(requestSpan.attributes).toMatchObject({ + [URL_FULL]: { + type: 'string', + value: 'http://sentry-test-site.example/callback?id=1#access_token=[Filtered]&state=xyz', + }, + [URL_QUERY]: { type: 'string', value: 'id=1' }, + [URL_FRAGMENT]: { type: 'string', value: 'access_token=[Filtered]&state=xyz' }, + }); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/init.js b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/init.js new file mode 100644 index 000000000000..45d551e5578f --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/init.js @@ -0,0 +1,11 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [Sentry.browserTracingIntegration({ instrumentPageLoad: false, instrumentNavigation: false })], + tracePropagationTargets: ['http://sentry-test-site.example'], + tracesSampleRate: 1, + dataCollection: { urlQueryParams: false }, +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/subject.js b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/subject.js new file mode 100644 index 000000000000..2a4292848938 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/subject.js @@ -0,0 +1,5 @@ +document.getElementById('btnFragment').addEventListener('click', async () => { + await Sentry.startSpan({ name: 'rootSpan' }, () => + fetch('http://sentry-test-site.example/callback?id=1#access_token=abc123&state=xyz'), + ); +}); diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/template.html b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/template.html new file mode 100644 index 000000000000..95dbd979befa --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/template.html @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/test.ts b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/test.ts new file mode 100644 index 000000000000..8b5abaa04b3c --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/tracing/request/fetch-fragment-url-query-params-off/test.ts @@ -0,0 +1,31 @@ +import { HTTP_CLIENT } from '@sentry/conventions/op'; +import { URL_FRAGMENT, URL_FULL, URL_QUERY } from '@sentry/conventions/attributes'; +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; +import { shouldSkipTracingTest } from '../../../../utils/helpers'; +import { getSpanOp, waitForStreamedSpan } from '../../../../utils/spanUtils'; + +sentryTest( + 'drops the URL fragment of fetch request spans when urlQueryParams is off', + async ({ getLocalTestUrl, page }) => { + if (shouldSkipTracingTest()) { + sentryTest.skip(); + } + + await page.route('http://sentry-test-site.example/*', route => route.fulfill({ body: 'ok' })); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.goto(url); + + const requestPromise = waitForStreamedSpan(page, span => getSpanOp(span) === HTTP_CLIENT); + await page.locator('#btnFragment').click(); + const requestSpan = await requestPromise; + + expect(requestSpan.attributes).toMatchObject({ + [URL_FULL]: { type: 'string', value: 'http://sentry-test-site.example/callback' }, + }); + expect(requestSpan.attributes).not.toHaveProperty([URL_QUERY]); + expect(requestSpan.attributes).not.toHaveProperty([URL_FRAGMENT]); + }, +);