Repository navigation
feat(browser): Support Trusted Types when loading scripts and workers #26764
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
09cb348
af491ce
5db81cd
31a5705
8b5b5c4
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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: [], | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| window._testLazyLoadIntegration = async function run() { | ||
| const integration = await window.Sentry.lazyLoadIntegration('httpClientIntegration'); | ||
|
|
||
| window.Sentry.getClient()?.addIntegration(integration()); | ||
|
|
||
| window._integrationLoaded = true; | ||
| }; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| <!doctype html> | ||
| <html> | ||
| <head> | ||
| <meta charset="utf-8" /> | ||
| <meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types sentry-sdk" /> | ||
| </head> | ||
| <body></body> | ||
| </html> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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([]); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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; |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| <!doctype html> | ||
| <html> | ||
| <head> | ||
| <meta charset="utf-8" /> | ||
| <meta | ||
| http-equiv="Content-Security-Policy" | ||
| content="require-trusted-types-for 'script'; trusted-types other-policy" | ||
| /> | ||
| </head> | ||
| <body></body> | ||
| </html> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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', | ||
| ); | ||
| }, | ||
| ); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| window._reportDialogLoaded = false; | ||
| Sentry.showReportDialog({ | ||
| eventId: 'test_id', | ||
| onLoad: () => { | ||
| window._reportDialogLoaded = true; | ||
| }, | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| <!doctype html> | ||
| <html> | ||
| <head> | ||
| <meta charset="utf-8" /> | ||
| <meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types sentry-sdk" /> | ||
| </head> | ||
| <body></body> | ||
| </html> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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([]); | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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], | ||
| }); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| <!doctype html> | ||
| <html> | ||
| <head> | ||
| <meta charset="utf-8" /> | ||
| <meta http-equiv="Content-Security-Policy" content="require-trusted-types-for 'script'; trusted-types sentry-sdk" /> | ||
| </head> | ||
| <body></body> | ||
| </html> |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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([]); | ||
| }, | ||
| ); |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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]}?`); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Policy looks up the current clientLow Severity This is more an “is this necessary” check than a hard violation: Additional Locations (1)Triggered by project rule: PR Review Guidelines for Cursor Bot Reviewed by Cursor Bugbot for commit 7e5046b. Configure here.
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. both callers build the URL and pass it here synchronously, so i don't think it can happen that it's a different client here |
||
| } | ||
|
|
||
| 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`); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. m/q: Would our SDK throw an error to the user application if we throw here? If so, is this expected behavior for policies?
Member
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, throwing is how policies should reject invalid values (example). Since we only call this with URLs we build ourselves, it should never happen in practice though. If it does, it's either 1) a bug on our side, where we changed a URL so it no longer matches, or 2) something untrusted got into the URL or is calling our policy directly (e.g. XSS), in which case we want to reject it. I added a test that checks all lazy-loaded bundle URLs against the policy to catch 1) better.
|
||
| } | ||
| 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; | ||
| } | ||


There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
m: above in
ScriptURLPolicy,createScriptURLreturnsunknown. Here it returnsstring. Is the divergence intentional?Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
our policy returns a string, which the browser then wraps in a
TrustedScriptURL, theunknownwas sort of hiding that. Added a named type to make it more clear.