Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

7.6 KB
Raw Blame
/**
 * Copyright (c) Microsoft Corporation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import { test, expect } from '@playwright/test';
import { SnapshotRenderer } from '../../packages/isomorphic/trace/snapshotRenderer';
import { LRUCache } from '../../packages/isomorphic/lruCache';
import { stripAnsiEscapes } from '../../packages/isomorphic/stringUtils';
import type { FrameSnapshot } from '../../packages/isomorphic/trace/trace';

function makeSnapshot(overrides: Partial<FrameSnapshot> = {}): FrameSnapshot {
  return {
    callId: 'call-1',
    pageId: 'page-1',
    frameId: 'frame-1',
    frameUrl: 'http://example.com/',
    timestamp: 0,
    collectionTime: 0,
    html: ['HTML', {}, ['BODY', {}]],
    resourceOverrides: [],
    viewport: { width: 1280, height: 720 },
    isMainFrame: true,
    ...overrides,
  };
}

for (const [name, overrides] of [
  ['callId', { callId: '</script><script>window.__pwned__=true;//' }],
  ['snapshotName', { callId: 'call-1', snapshotName: '</script><img src=x onerror=alert(1)>' }],
] as const) {
  test(`TV-123 snapshot renderer escapes attacker-controlled ${name} in script context`, () => {
    const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot(overrides)], [], 0);
    const { html } = renderer.render();
    expect(html.match(/<script[ >]/g)).toHaveLength(1);
    expect(html.match(/<\/script>/g)).toHaveLength(1);
  });
}

test('TV-124 snapshot renderer nonces the bootstrap script', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot()], [], 0);
  const { html, scriptNonce } = renderer.render();
  expect(scriptNonce).toMatch(/^[0-9a-f]{32}$/);
  expect(html).toContain(`<script nonce="${scriptNonce}">`);
  // The html is cached, so repeated renders must keep returning the nonce that is
  // baked into it - it is sent back in the Content-Security-Policy header.
  expect(renderer.render().scriptNonce).toBe(scriptNonce);
  // A different snapshot gets a different nonce.
  const other = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot()], [], 0);
  expect(other.render().scriptNonce).not.toBe(scriptNonce);
});

test('TV-125 snapshot renderer strips event handler attributes', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['IMG', { 'onerror': 'alert(1)', 'src': 'x' }]]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain('onerror="alert(1)"');
  expect(html).toContain('src="x"');
});

test('TV-126 snapshot renderer strips onclick attributes', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['DIV', { 'onClick': 'alert(1)' }, 'click me']]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain('onClick');
  expect(html).not.toContain('onclick');
  expect(html).toContain('click me');
});

test('TV-127 snapshot renderer neutralizes iframe srcdoc', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['IFRAME', { 'srcdoc': '<script>alert(1)</script>' }]]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain(' srcdoc=');
  expect(html).toContain('__playwright_srcdoc__');
});

test('TV-128 snapshot renderer neutralizes iframe sandbox', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['IFRAME', { 'sandbox': 'allow-scripts allow-top-navigation' }]]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain(' sandbox=');
  expect(html).toContain('__playwright_sandbox__');
});

test('TV-129 snapshot renderer neutralizes object data attribute', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['OBJECT', { 'data': '/sha1/malicious', 'type': 'text/html' }]]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain(' data=');
  expect(html).toContain('__playwright_data__');
});

test('TV-130 snapshot renderer neutralizes embed src attribute', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['EMBED', { 'src': '/sha1/malicious', 'type': 'text/html' }]]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain(' src=');
  expect(html).toContain('__playwright_src__');
});

test('TV-131 snapshot renderer handles case-insensitive iframe tag names', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['iframe', { 'srcdoc': '<script>alert(1)</script>', 'src': 'http://evil.com' }]]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain(' srcdoc=');
  expect(html).toContain('__playwright_srcdoc__');
  expect(html).toContain('__playwright_src__');
});

test('TV-132 snapshot renderer drops unsafe tag names that smuggle attributes', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {}, ['img src=x onerror=alert(1)', {}], 'safe']],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).not.toContain('onerror=alert(1)');
  expect(html).not.toContain('<img src=x');
  expect(html).toContain('safe');
});

test('TV-133 snapshot renderer still renders ordinary custom elements', () => {
  const renderer = new SnapshotRenderer(new LRUCache(1_000_000), [], [makeSnapshot({
    html: ['HTML', {}, ['BODY', {},
      ['MY-WIDGET', { 'id': 'w' }, 'hello'],
      ['MY-WIDGET_V2', { 'id': 'w2' }, 'v2'],
      ['MY-WIDGET.V2', { 'id': 'w3' }, 'dot'],
      ['math-α', { 'id': 'm' }, 'alpha'],
      ['my-élément', { 'id': 'e' }, 'elem'],
    ]],
  })], [], 0);
  const { html } = renderer.render();
  expect(html).toContain('<MY-WIDGET id="w">hello</MY-WIDGET>');
  expect(html).toContain('<MY-WIDGET_V2 id="w2">v2</MY-WIDGET_V2>');
  expect(html).toContain('<MY-WIDGET.V2 id="w3">dot</MY-WIDGET.V2>');
  expect(html).toContain('<math-α id="m">alpha</math-α>');
  expect(html).toContain('<my-élément id="e">elem</my-élément>');
});

test('TV-134 stripAnsiEscapes should not exhibit polynomial backtracking', () => {
  // \x1b[ + 50000 semicolons + non-terminal character.
  // Before the fix this took >3 seconds due to O(n^2) backtracking.
  const payload = '\x1b[' + ';'.repeat(50000) + '!';
  const result = stripAnsiEscapes(payload);
  // The ESC[ prefix is not a complete ANSI sequence, so it stays in the output.
  expect(result).toContain('!');
});

test('TV-135 stripAnsiEscapes handles common ANSI sequences after fix', () => {
  expect(stripAnsiEscapes('\x1b[31mred\x1b[0m')).toBe('red');
  expect(stripAnsiEscapes('\x1b[0;31mbold red\x1b[0m')).toBe('bold red');
  expect(stripAnsiEscapes('\x1b[;H')).toBe('');
  expect(stripAnsiEscapes('\x1b[2J')).toBe('');
  expect(stripAnsiEscapes('\x1b[38;2;255;0;0mcolored\x1b[0m')).toBe('colored');
  expect(stripAnsiEscapes('hello\x1b[32mworld\x1b[0m!')).toBe('helloworld!');
});