diff --git a/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/init.js b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/init.js new file mode 100644 index 000000000000..eb75d30bf760 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/init.js @@ -0,0 +1,12 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = { + ...Sentry, + // Ensure this is _not_ set + httpClientIntegration: undefined, +}; + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + integrations: [], +}); diff --git a/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/subject.js b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/subject.js new file mode 100644 index 000000000000..6ce3c00ab277 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/subject.js @@ -0,0 +1,7 @@ +window._testLazyLoadIntegration = async function run() { + const integration = await window.Sentry.lazyLoadIntegration('httpClientIntegration'); + + window.Sentry.getClient()?.addIntegration(integration()); + + window._integrationLoaded = true; +}; diff --git a/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/template.html b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/template.html new file mode 100644 index 000000000000..c2cd7b0bbfad --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/template.html @@ -0,0 +1,8 @@ + + +
+ + + + + diff --git a/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/test.ts b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/test.ts new file mode 100644 index 000000000000..ed355ec04fdd --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/integrations/lazyLoad/trustedTypes/test.ts @@ -0,0 +1,29 @@ +import { expect } from '@playwright/test'; +import { SDK_VERSION } from '@sentry/browser'; +import { sentryTest } from '../../../../utils/fixtures'; + +sentryTest('lazy loads an integration on pages that enforce Trusted Types', async ({ getLocalTestUrl, page }) => { + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.route(`https://browser.sentry-cdn.com/${SDK_VERSION}/httpclient.min.js`, route => { + return route.fulfill({ + status: 200, + contentType: 'application/javascript;', + body: "window.Sentry.httpClientIntegration = () => ({ name: 'HttpClient' })", + }); + }); + + await page.addInitScript(() => { + (window as any)._violations = []; + document.addEventListener('securitypolicyviolation', event => { + (window as any)._violations.push(`${event.violatedDirective}: ${event.sample}`); + }); + }); + + await page.goto(url); + + await page.evaluate(() => (window as any)._testLazyLoadIntegration()); + + expect(await page.evaluate(() => (window as any)._integrationLoaded)).toBe(true); + expect(await page.evaluate(() => (window as any)._violations)).toEqual([]); +}); diff --git a/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/subject.js b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/subject.js new file mode 100644 index 000000000000..9fcf83f85069 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/subject.js @@ -0,0 +1,11 @@ +try { + Sentry.showReportDialog({ + eventId: 'test_id', + onError: error => { + window._reportDialogError = error.message; + }, + }); +} catch (error) { + window._thrownError = error.message; +} +window._subjectDone = true; diff --git a/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/template.html b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/template.html new file mode 100644 index 000000000000..b482ee774589 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/template.html @@ -0,0 +1,11 @@ + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/test.ts b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/test.ts new file mode 100644 index 000000000000..c196924f0bd9 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types-blocked/test.ts @@ -0,0 +1,19 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; + +sentryTest( + 'calls `onError` instead of throwing when the Trusted Types policy is not allowed', + async ({ browserName, getLocalTestUrl, page }) => { + sentryTest.skip(browserName !== 'chromium', 'Not all tested browser versions enforce Trusted Types'); + + const url = await getLocalTestUrl({ testDir: __dirname }); + + await page.goto(url); + await page.waitForFunction(() => (window as any)._subjectDone); + + expect(await page.evaluate(() => (window as any)._thrownError)).toBeUndefined(); + expect(await page.evaluate(() => (window as any)._reportDialogError)).toBe( + 'Failed to load the report dialog script', + ); + }, +); diff --git a/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/subject.js b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/subject.js new file mode 100644 index 000000000000..45e7901f593f --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/subject.js @@ -0,0 +1,7 @@ +window._reportDialogLoaded = false; +Sentry.showReportDialog({ + eventId: 'test_id', + onLoad: () => { + window._reportDialogLoaded = true; + }, +}); diff --git a/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/template.html b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/template.html new file mode 100644 index 000000000000..c2cd7b0bbfad --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/template.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/test.ts b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/test.ts new file mode 100644 index 000000000000..e99f82ffbcbf --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/public-api/showReportDialog/trusted-types/test.ts @@ -0,0 +1,23 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../../utils/fixtures'; + +sentryTest('loads the dialog script on pages that enforce Trusted Types', async ({ getLocalTestUrl, page }) => { + const url = await getLocalTestUrl({ testDir: __dirname }); + + // Registered after `getLocalTestUrl` so it takes precedence over the fixture's ingest route + await page.route(/\/api\/embed\/error-page\//, route => + route.fulfill({ contentType: 'text/javascript', body: '', headers: { 'Access-Control-Allow-Origin': '*' } }), + ); + + await page.addInitScript(() => { + (window as any)._violations = []; + document.addEventListener('securitypolicyviolation', event => { + (window as any)._violations.push(`${event.violatedDirective}: ${event.sample}`); + }); + }); + + await page.goto(url); + + await page.waitForFunction(() => (window as any)._reportDialogLoaded); + expect(await page.evaluate(() => (window as any)._violations)).toEqual([]); +}); diff --git a/dev-packages/browser-integration-tests/suites/replay/trustedTypes/init.js b/dev-packages/browser-integration-tests/suites/replay/trustedTypes/init.js new file mode 100644 index 000000000000..ab1e26f4490a --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/replay/trustedTypes/init.js @@ -0,0 +1,18 @@ +import * as Sentry from '@sentry/browser'; + +window.Sentry = Sentry; +window.Replay = Sentry.replayIntegration({ + flushMinDelay: 200, + flushMaxDelay: 200, + minReplayDuration: 0, + useCompression: true, +}); + +Sentry.init({ + dsn: 'https://public@dsn.ingest.sentry.io/1337', + sampleRate: 0, + replaysSessionSampleRate: 1.0, + replaysOnErrorSampleRate: 0.0, + + integrations: [window.Replay], +}); diff --git a/dev-packages/browser-integration-tests/suites/replay/trustedTypes/template.html b/dev-packages/browser-integration-tests/suites/replay/trustedTypes/template.html new file mode 100644 index 000000000000..c2cd7b0bbfad --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/replay/trustedTypes/template.html @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/dev-packages/browser-integration-tests/suites/replay/trustedTypes/test.ts b/dev-packages/browser-integration-tests/suites/replay/trustedTypes/test.ts new file mode 100644 index 000000000000..96be57a34343 --- /dev/null +++ b/dev-packages/browser-integration-tests/suites/replay/trustedTypes/test.ts @@ -0,0 +1,25 @@ +import { expect } from '@playwright/test'; +import { sentryTest } from '../../../utils/fixtures'; +import { replayEnvelopeIsCompressed, shouldSkipReplayTest, waitForReplayRequest } from '../../../utils/replayHelpers'; + +sentryTest( + 'compresses the recording on pages that enforce Trusted Types', + async ({ getLocalTestUrl, page, forceFlushReplay }) => { + sentryTest.skip(shouldSkipReplayTest()); + + await page.addInitScript(() => { + (window as any)._violations = []; + document.addEventListener('securitypolicyviolation', event => { + (window as any)._violations.push(`${event.violatedDirective}: ${event.sample}`); + }); + }); + + const reqPromise0 = waitForReplayRequest(page, 0); + + await page.goto(await getLocalTestUrl({ testDir: __dirname })); + await forceFlushReplay(); + + expect(replayEnvelopeIsCompressed(await reqPromise0)).toBe(true); + expect(await page.evaluate(() => (window as any)._violations)).toEqual([]); + }, +); diff --git a/packages/browser-utils/src/index.ts b/packages/browser-utils/src/index.ts index 376ee1c51ac6..ca4308dd1f78 100644 --- a/packages/browser-utils/src/index.ts +++ b/packages/browser-utils/src/index.ts @@ -31,6 +31,8 @@ export { isBotUserAgent } from './isBotUserAgent'; export { getLocationHref } from './getLocationHref'; +export { getCdnBaseUrl, getTrustedScriptURL } from './trustedTypes'; + export { createCachedRouteProvider, createUrlRouteProvider, diff --git a/packages/browser-utils/src/trustedTypes.ts b/packages/browser-utils/src/trustedTypes.ts new file mode 100644 index 000000000000..1e6c9e9582f7 --- /dev/null +++ b/packages/browser-utils/src/trustedTypes.ts @@ -0,0 +1,69 @@ +import type { ScriptURLPolicy } from '@sentry/core'; +import { debug, getClient, getGlobalSingleton, getReportDialogEndpoint, SDK_VERSION } from '@sentry/core'; +import { DEBUG_BUILD } from './debug-build'; +import { WINDOW } from './types'; + +// Part of the public contract: pages allow this name in their `trusted-types` CSP directive. +const POLICY_NAME = 'sentry-sdk'; + +interface TrustedTypesWindow { + trustedTypes?: { + createPolicy(name: string, rules: { createScriptURL(input: string): string }): ScriptURLPolicy; + }; +} + +/** The base URL that `lazyLoadIntegration` loads bundles from. */ +export function getCdnBaseUrl(): string { + const options = getClient()?.getOptions() as { cdnBaseUrl?: string } | undefined; + return options?.cdnBaseUrl || 'https://browser.sentry-cdn.com'; +} + +function isReportDialogURL(input: string): boolean { + const dsn = getClient()?.getDsn(); + // Matching up to and including the `?` pins the origin and the full path, so only the query can vary. + return !!dsn && input.startsWith(`${getReportDialogEndpoint(dsn, {}).split('?')[0]}?`); +} + +function isCdnBundleURL(input: string): boolean { + const prefix = new URL(`/${SDK_VERSION}/`, getCdnBaseUrl()).toString(); + return input.startsWith(prefix) && /^[a-z-]+\.min\.js$/.test(input.slice(prefix.length)); +} + +// The policy can't know which blob URLs the SDK created: they may come from another copy of the SDK that shares it. +// Creating one for this origin already requires running script in it. +function isBlobURL(input: string): boolean { + return input.startsWith(`blob:${WINDOW.origin}/`); +} + +function createScriptURL(input: string): string { + if (!isBlobURL(input) && !isReportDialogURL(input) && !isCdnBundleURL(input)) { + throw new TypeError(`Refusing to load ${input} as a Sentry SDK script`); + } + return input; +} + +function createPolicy(): ScriptURLPolicy { + try { + const policy = (WINDOW as TrustedTypesWindow).trustedTypes?.createPolicy(POLICY_NAME, { createScriptURL }); + if (policy) { + return policy; + } + } catch (error) { + DEBUG_BUILD && + debug.warn( + `Could not create the "${POLICY_NAME}" Trusted Types policy. Add it to your \`trusted-types\` CSP directive (with \`'allow-duplicates'\` if the policy is created more than once, e.g. by different SDK versions on the same page).`, + error, + ); + } + return { createScriptURL: input => input }; +} + +/** + * Returns `url` as a value for script URL sinks (`script.src`, `new Worker()`) on pages that enforce Trusted Types. + * + * This is a `TrustedScriptURL` (typed as `string`, like the sinks in the DOM lib) if the policy could be created, and + * the unchanged string otherwise. With a policy, it throws for URLs the SDK is not expected to load. + */ +export function getTrustedScriptURL(url: string): string { + return getGlobalSingleton('trustedTypesPolicy', createPolicy).createScriptURL(url) as string; +} diff --git a/packages/browser-utils/test/trustedTypes.test.ts b/packages/browser-utils/test/trustedTypes.test.ts new file mode 100644 index 000000000000..2b17caa82472 --- /dev/null +++ b/packages/browser-utils/test/trustedTypes.test.ts @@ -0,0 +1,137 @@ +/** + * @vitest-environment jsdom + */ + +import type { Client } from '@sentry/core'; +import { getCurrentScope, GLOBAL_OBJ, makeDsn, SDK_VERSION } from '@sentry/core'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { getTrustedScriptURL } from '../src/trustedTypes'; + +const REPORT_DIALOG_URL = 'https://sentry.example.com/api/embed/error-page/?dsn=abc'; + +type Rules = { createScriptURL(input: string): string }; + +function mockClient(dsn: string | undefined, options: { cdnBaseUrl?: string } = {}): void { + getCurrentScope().setClient({ + getDsn: () => dsn && makeDsn(dsn), + getOptions: () => options, + } as Client); +} + +function mockTrustedTypes(createPolicy = vi.fn((_name: string, rules: Rules): Rules => rules)) { + vi.stubGlobal('trustedTypes', { createPolicy }); + return createPolicy; +} + +describe('getTrustedScriptURL', () => { + beforeEach(() => { + delete GLOBAL_OBJ.__SENTRY__; + mockClient('https://public@sentry.example.com/1337'); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + delete GLOBAL_OBJ.__SENTRY__; + }); + + it('returns the url unchanged when Trusted Types is unavailable', () => { + expect(getTrustedScriptURL(REPORT_DIALOG_URL)).toBe(REPORT_DIALOG_URL); + }); + + it('returns the value minted by the policy', () => { + const trusted = { toString: () => REPORT_DIALOG_URL }; + const createPolicy = mockTrustedTypes(vi.fn(() => ({ createScriptURL: () => trusted as unknown as string }))); + + expect(getTrustedScriptURL(REPORT_DIALOG_URL)).toBe(trusted); + expect(createPolicy).toHaveBeenCalledWith('sentry-sdk', { createScriptURL: expect.any(Function) }); + }); + + it('creates the policy lazily and only once', () => { + const createPolicy = mockTrustedTypes(); + expect(createPolicy).not.toHaveBeenCalled(); + + getTrustedScriptURL(REPORT_DIALOG_URL); + getTrustedScriptURL(REPORT_DIALOG_URL); + + expect(createPolicy).toHaveBeenCalledTimes(1); + }); + + it('shares the policy between SDK copies of the same version', async () => { + const createPolicy = mockTrustedTypes(); + getTrustedScriptURL(REPORT_DIALOG_URL); + + vi.resetModules(); + const otherCopy = await import('../src/trustedTypes'); + + expect(otherCopy.getTrustedScriptURL).not.toBe(getTrustedScriptURL); + expect(otherCopy.getTrustedScriptURL(REPORT_DIALOG_URL)).toBe(REPORT_DIALOG_URL); + expect(createPolicy).toHaveBeenCalledTimes(1); + }); + + it('returns the url unchanged and does not retry when the policy cannot be created', () => { + const createPolicy = mockTrustedTypes( + vi.fn(() => { + throw new TypeError('Policy "sentry-sdk" disallowed'); + }), + ); + + expect(getTrustedScriptURL(REPORT_DIALOG_URL)).toBe(REPORT_DIALOG_URL); + expect(getTrustedScriptURL(REPORT_DIALOG_URL)).toBe(REPORT_DIALOG_URL); + expect(createPolicy).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['http://public@localhost:9000/1337', 'http://localhost:9000/api/embed/error-page/?dsn=abc'], + ['https://public@example.com/sentry/1337', 'https://example.com/sentry/api/embed/error-page/?dsn=abc'], + ])('accepts the report dialog for DSN %s', (dsn, url) => { + mockTrustedTypes(); + mockClient(dsn); + + expect(getTrustedScriptURL(url)).toBe(url); + }); + + it.each([ + [undefined, `https://browser.sentry-cdn.com/${SDK_VERSION}/feedback-modal.min.js`], + ['https://cdn.example.com', `https://cdn.example.com/${SDK_VERSION}/replay.min.js`], + ])('accepts CDN bundles for cdnBaseUrl %s', (cdnBaseUrl, url) => { + mockTrustedTypes(); + mockClient(undefined, { cdnBaseUrl }); + + expect(getTrustedScriptURL(url)).toBe(url); + }); + + it('accepts blob URLs of the own origin', () => { + mockTrustedTypes(); + const url = `blob:${window.origin}/7d9c8f1e`; + + expect(getTrustedScriptURL(url)).toBe(url); + }); + + it.each([ + 'https://evil.example/api/embed/error-page/?dsn=abc', + 'https://sentry.example.com.evil.example/api/embed/error-page/?dsn=abc', + 'https://sentry.example.com@evil.example/api/embed/error-page/?dsn=abc', + 'https://sentry.example.com/api/embed/error-page/../../evil.js?dsn=abc', + 'https://sentry.example.com/evil.js', + 'http://sentry.example.com/api/embed/error-page/?dsn=abc', + `https://evil.example/${SDK_VERSION}/replay.min.js`, + `https://browser.sentry-cdn.com/${SDK_VERSION}/../1.0.0/replay.min.js`, + 'https://browser.sentry-cdn.com/1.0.0/replay.min.js', + `https://browser.sentry-cdn.com/${SDK_VERSION}/replay.min.js?foo`, + 'blob:https://evil.example/7d9c8f1e', + 'javascript:alert(1)', + 'data:text/javascript,alert(1)', + '', + ])('refuses %j', url => { + mockTrustedTypes(); + + expect(() => getTrustedScriptURL(url)).toThrow(TypeError); + }); + + it('refuses the report dialog without a DSN', () => { + mockTrustedTypes(); + mockClient(undefined); + + expect(() => getTrustedScriptURL(REPORT_DIALOG_URL)).toThrow(TypeError); + }); +}); diff --git a/packages/browser/src/report-dialog.ts b/packages/browser/src/report-dialog.ts index 7abf68f5ea18..6c2f00c47661 100644 --- a/packages/browser/src/report-dialog.ts +++ b/packages/browser/src/report-dialog.ts @@ -1,3 +1,4 @@ +import { getTrustedScriptURL } from '@sentry/browser-utils'; import type { ReportDialogOptions } from '@sentry/core'; import { debug, getClient, getCurrentScope, getReportDialogEndpoint, lastEventId } from '@sentry/core'; import { DEBUG_BUILD } from './debug-build'; @@ -48,7 +49,15 @@ export function showReportDialog(options: ReportDialogOptions = {}): void { const script = WINDOW.document.createElement('script'); script.async = true; script.crossOrigin = 'anonymous'; - script.src = getReportDialogEndpoint(dsn, mergedOptions); + + // With Trusted Types enforced, the policy or the assignment itself can throw + try { + script.src = getTrustedScriptURL(getReportDialogEndpoint(dsn, mergedOptions)); + } catch (error) { + DEBUG_BUILD && debug.error('[showReportDialog] Script URL was blocked', error); + onError?.(new Error('Failed to load the report dialog script')); + return; + } if (onLoad) { script.onload = onLoad; diff --git a/packages/browser/src/utils/lazyLoadIntegration.ts b/packages/browser/src/utils/lazyLoadIntegration.ts index 6b260caeb2a7..ea56ffae821f 100644 --- a/packages/browser/src/utils/lazyLoadIntegration.ts +++ b/packages/browser/src/utils/lazyLoadIntegration.ts @@ -1,12 +1,13 @@ +import { getCdnBaseUrl, getTrustedScriptURL } from '@sentry/browser-utils'; import type { IntegrationFn } from '@sentry/core'; -import { getClient, SDK_VERSION } from '@sentry/core'; -import type { BrowserClient } from '../client'; +import { SDK_VERSION } from '@sentry/core'; import { WINDOW } from '../helpers'; // Single source of truth: as const array provides both the runtime list and the type. // Bundle file names are derived: strip 'Integration' suffix, lowercase. // Exceptions (hyphenated bundle names) are listed in HYPHENATED_BUNDLES. -const LAZY_LOADABLE_NAMES = [ +/** Exported only for tests. */ +export const LAZY_LOADABLE_NAMES = [ 'replayIntegration', 'replayCanvasIntegration', 'feedbackIntegration', @@ -72,7 +73,7 @@ export async function lazyLoadIntegration( const url = getScriptURL(bundle); const script = WINDOW.document.createElement('script'); - script.src = url; + script.src = getTrustedScriptURL(url); script.crossOrigin = 'anonymous'; script.referrerPolicy = 'strict-origin'; @@ -110,8 +111,5 @@ export async function lazyLoadIntegration( } function getScriptURL(bundle: string): string { - const client = getClient