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
@@ -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,12 @@
window._violations = [];
document.addEventListener('securitypolicyviolation', event => {
window._violations.push(`${event.violatedDirective}: ${event.sample}`);
});

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,16 @@
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.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([]);
},
);
2 changes: 2 additions & 0 deletions packages/browser-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ export { isBotUserAgent } from './isBotUserAgent';

export { getLocationHref } from './getLocationHref';

export { getCdnBaseUrl, getTrustedScriptURL } from './trustedTypes';

export {
createCachedRouteProvider,
createUrlRouteProvider,
Expand Down
73 changes: 73 additions & 0 deletions packages/browser-utils/src/trustedTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
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';

// The DOM lib has no Trusted Types definitions.
interface ScriptURLPolicy {
createScriptURL(input: string): unknown;
}

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;
}
137 changes: 137 additions & 0 deletions packages/browser-utils/test/trustedTypes.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
3 changes: 2 additions & 1 deletion packages/browser/src/report-dialog.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -48,7 +49,7 @@ export function showReportDialog(options: ReportDialogOptions = {}): void {
const script = WINDOW.document.createElement('script');
script.async = true;
script.crossOrigin = 'anonymous';
script.src = getReportDialogEndpoint(dsn, mergedOptions);
script.src = getTrustedScriptURL(getReportDialogEndpoint(dsn, mergedOptions));

if (onLoad) {
script.onload = onLoad;
Expand Down
Loading
Loading