Skip to content

Commit 9c013a2

Browse files
authored
fix(trace-viewer): harden snapshot rendering (#44177)
1 parent 9efd7d3 commit 9c013a2

5 files changed

Lines changed: 48 additions & 10 deletions

File tree

‎packages/isomorphic/trace/snapshotRenderer.ts‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,11 @@ export class SnapshotRenderer {
166166
// we will be using the currentSrc instead.
167167
attrName = '_' + attrName;
168168
}
169+
if (upperName === 'TEMPLATE' && (attr.toLowerCase() === 'shadowrootmode' || attr.toLowerCase() === 'shadowroot')) {
170+
// The capture side never records declarative shadow roots. A closed shadow root
171+
// would hide its links from the click listener in the snapshot script.
172+
attrName = '_' + attr;
173+
}
169174
if (hasUnsafeHttpEquiv && (attr.toLowerCase() === 'http-equiv' || attr.toLowerCase() === 'content')) {
170175
// Neutralize the META directive by renaming the attribute so the browser ignores it.
171176
attrName = '_' + attr;
@@ -329,6 +334,17 @@ function snapshotScript(viewport: ViewportSize, ...targetIds: (string | undefine
329334
function applyPlaywrightAttributes(blankSnapshotUrl: string, viewport: ViewportSize, ...targetIds: (string | undefined)[]) {
330335
// eslint-disable-next-line no-restricted-globals
331336
const win = window;
337+
338+
// The snapshot must not navigate: the snapshot content could open a page from the trace viewer origin.
339+
// Install this listener first, so that snapshot content that makes the code below throw cannot skip it.
340+
// A middle click sends 'auxclick' and opens the link in a new tab.
341+
for (const eventName of ['click', 'auxclick']) {
342+
win.addEventListener(eventName, event => {
343+
if (event.composedPath().some(target => (target as Element).localName === 'a' || (target as Element).localName === 'area'))
344+
event.preventDefault();
345+
}, true);
346+
}
347+
332348
const searchParams = new URLSearchParams(win.location.search);
333349
const shouldPopulateCanvasFromScreenshot = searchParams.has('shouldPopulateCanvasFromScreenshot');
334350
const isUnderTest = searchParams.has('isUnderTest');
@@ -444,8 +460,13 @@ function snapshotScript(viewport: ViewportSize, ...targetIds: (string | undefine
444460
const body = root.querySelector(`body[__playwright_custom_elements__]`);
445461
if (body && win.customElements) {
446462
const customElements = (body.getAttribute('__playwright_custom_elements__') || '').split(',');
447-
for (const elementName of customElements)
448-
win.customElements.define(elementName, class extends HTMLElement {});
463+
for (const elementName of customElements) {
464+
try {
465+
win.customElements.define(elementName, class extends HTMLElement {});
466+
} catch {
467+
// The snapshot can have names that are not valid custom element names.
468+
}
469+
}
449470
}
450471
}
451472

@@ -457,9 +478,6 @@ function snapshotScript(viewport: ViewportSize, ...targetIds: (string | undefine
457478
visit(shadowRoot);
458479
}
459480

460-
for (const element of root.querySelectorAll('a'))
461-
element.addEventListener('click', event => { event.preventDefault(); });
462-
463481
if ('adoptedStyleSheets' in (root as any)) {
464482
const adoptedSheets: CSSStyleSheet[] = [...(root as any).adoptedStyleSheets];
465483
for (const element of root.querySelectorAll(`template[__playwright_style_sheet_]`)) {

‎packages/isomorphic/trace/snapshotServer.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@ export class SnapshotServer {
4040
status: 200,
4141
headers: {
4242
'Content-Type': 'text/html; charset=utf-8',
43-
// Only allow our own bootstrap script.
44-
'Content-Security-Policy': `script-src 'nonce-${renderedSnapshot.scriptNonce}'; object-src 'none'`,
43+
// Only allow our own bootstrap script. Do not submit forms: the popout window has no iframe sandbox.
44+
'Content-Security-Policy': `script-src 'nonce-${renderedSnapshot.scriptNonce}'; object-src 'none'; form-action 'none'`,
4545
},
4646
});
4747
}

‎tests/library/snapshot-renderer.spec.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,14 @@ test('TV-128 snapshot renderer neutralizes iframe sandbox', () => {
128128
expect(html).toContain('__playwright_sandbox__');
129129
});
130130

131+
test('TV-137 snapshot renderer neutralizes declarative shadow roots', () => {
132+
const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
133+
html: ['HTML', {}, ['BODY', {}, ['DIV', {}, ['TEMPLATE', { 'shadowrootmode': 'closed', 'SHADOWROOT': 'closed' }, ['A', { href: 'x' }, 'link']]]]],
134+
})], [], 0);
135+
const { html } = renderer.render();
136+
expect(html).toContain('<TEMPLATE _shadowrootmode="closed" _SHADOWROOT="closed">');
137+
});
138+
131139
test('TV-129 snapshot renderer neutralizes object data attribute', () => {
132140
const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
133141
html: ['HTML', {}, ['BODY', {}, ['OBJECT', { 'data': '/sha1/malicious', 'type': 'text/html' }]]],

‎tests/library/trace-viewer.spec.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2598,10 +2598,15 @@ test('TV-110 should survive service worker restart', async ({ page, runAndTrace,
25982598
test('TV-111 should not navigate on anchor clicks', async ({ runAndTrace, page, server }) => {
25992599
const url = server.EMPTY_PAGE;
26002600
const traceViewer = await runAndTrace(async () => {
2601+
// An invalid custom element name must not stop the snapshot script before it guards the links.
26012602
await page.setContent(`
2602-
<a href="${url}">link1</a>
2603-
<a href="${url}" target="_blank">link2</a>
2604-
<a href="${url}" target="_top">link3</a>
2603+
<body __playwright_custom_elements__="not a valid name">
2604+
<a href="${url}">link1</a>
2605+
<a href="${url}" target="_blank">link2</a>
2606+
<a href="${url}" target="_top">link3</a>
2607+
<map name="map"><area href="${url}" alt="link4" shape="default"></map>
2608+
<img usemap="#map" width="100" height="100">
2609+
</body>
26052610
`);
26062611
});
26072612
const snapshot = await traceViewer.snapshotFrame('Set content');
@@ -2613,6 +2618,8 @@ test('TV-111 should not navigate on anchor clicks', async ({ runAndTrace, page,
26132618
newPageOpened = true;
26142619
});
26152620
await snapshot.getByRole('link', { name }).click();
2621+
// A middle click opens a link in a new tab.
2622+
await snapshot.getByRole('link', { name }).click({ button: 'middle' });
26162623
await traceViewer.page.waitForTimeout(500);
26172624
await expect(traceViewer.page).not.toHaveURL(url, { timeout: 500 });
26182625
expect(frame.url()).not.toBe(url);
@@ -2622,6 +2629,10 @@ test('TV-111 should not navigate on anchor clicks', async ({ runAndTrace, page,
26222629
await checkLink('link1');
26232630
await checkLink('link2');
26242631
await checkLink('link3');
2632+
2633+
await snapshot.locator('area').dispatchEvent('click');
2634+
await traceViewer.page.waitForTimeout(500);
2635+
expect(frame.url()).not.toBe(url);
26252636
});
26262637

26272638
test('TV-112 should respect CSSOM changes', async ({ runAndTrace, page, server }) => {

‎tests/registry.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5255,6 +5255,7 @@ subsystem, add a row to the Subsystems table. Then update this file:
52555255
| `TV-134` | `library/snapshot-renderer.spec.ts` | stripAnsiEscapes should not exhibit polynomial backtracking |
52565256
| `TV-135` | `library/snapshot-renderer.spec.ts` | stripAnsiEscapes handles common ANSI sequences after fix |
52575257
| `TV-136` | `library/snapshot-renderer.spec.ts` | snapshot renderer selects the nearest out-of-order screencast frame |
5258+
| `TV-137` | `library/snapshot-renderer.spec.ts` | snapshot renderer neutralizes declarative shadow roots |
52585259

52595260
### TZ — Timezone
52605261

0 commit comments

Comments
 (0)