Skip to content
Merged
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
11 changes: 10 additions & 1 deletion packages/playwright-core/src/server/trace/viewer/traceViewer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import path from 'path';
import url from 'url';

import open from 'open';
import { HttpServer } from '@utils/httpServer';
import { HttpServer, isFrameNavigation } from '@utils/httpServer';
import { gracefullyProcessExitDoNotHang } from '@utils/processLauncher';
import { isUnderTest } from '@utils/debug';
import { isCodingAgent } from '@utils/env';
Expand Down Expand Up @@ -94,6 +94,15 @@ export async function startTraceViewerServer(options: TraceViewerServerOptions &
const serveTraceDataRoute = (request: http.IncomingMessage, response: http.ServerResponse, relativePath: string): boolean => {
if (!relativePath.startsWith('/file'))
return false;
// These files can have content from the pages under test. Do not run them as pages in the trace viewer origin.
response.setHeader('Content-Security-Policy', 'sandbox');
response.setHeader('X-Content-Type-Options', 'nosniff');
// The trace viewer never shows these files in a frame. Only a snapshot that navigates itself does.
if (isFrameNavigation(request)) {
response.statusCode = 403;
response.end();
return true;
}
const url = new URL('http://localhost' + request.url!);
try {
const filePath = path.resolve(url.searchParams.get('path')!);
Expand Down
13 changes: 9 additions & 4 deletions packages/trace-viewer/src/sw/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,9 +228,12 @@ async function doFetch(event: FetchEvent): Promise<Response> {
}

if (relativePath.startsWith('/file/')) {
// The trace viewer never shows these files in a frame. Only a snapshot that navigates itself does.
if (['iframe', 'frame', 'embed', 'object'].includes(request.destination))
return new Response(null, { status: 403 });
const blob = await loadedTrace!.traceLoader.resourceEntry(relativePath.slice('/file/'.length));
if (blob)
return new Response(blob, { status: 200, headers: downloadHeaders(url.searchParams) });
return new Response(blob, { status: 200, headers: fileHeaders(url.searchParams) });
return new Response(null, { status: 404 });
}
}
Expand All @@ -251,12 +254,14 @@ function takeCoverage(): IstanbulCoverage {
return result;
}

function downloadHeaders(searchParams: URLSearchParams): Headers | undefined {
function fileHeaders(searchParams: URLSearchParams): Headers {
const headers = new Headers();
// Trace files can have content from the pages under test. Do not run them as pages in the trace viewer origin.
headers.set('Content-Security-Policy', 'sandbox');
const name = searchParams.get('dn');
const contentType = searchParams.get('dct');
if (!name)
return;
const headers = new Headers();
return headers;
headers.set('Content-Disposition', `attachment; filename="attachment"; filename*=UTF-8''${encodeURIComponent(name)}`);
if (contentType)
headers.set('Content-Type', contentType);
Expand Down
33 changes: 31 additions & 2 deletions packages/utils/httpServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ export class HttpServer {
socket.destroy();
return;
}
if (!isAllowedHost(request, this._allowedHosts)) {
if (!isAllowedHost(request, this._allowedHosts) || !isSameOriginUpgrade(request)) {
socket.write(`HTTP/${request.httpVersion} 403 Forbidden\r\n\r\n`);
socket.destroy();
return;
Expand Down Expand Up @@ -355,6 +355,29 @@ export function isAllowedHost(request: http.IncomingMessage, allowedHosts: Set<s
return !!hostname && allowedHosts.has(hostname);
}

// Browsers always send Origin with a WebSocket handshake, and a page cannot change it or add headers.
// Accept only pages of this server. This also rejects sandboxed pages, which have the "null" origin.
// Clients that are not browsers send no Origin. A proxy can pass the public host in X-Forwarded-Host.
function isSameOriginUpgrade(request: http.IncomingMessage): boolean {
const origin = request.headers.origin;
if (origin === undefined)
return true;
let originHost: string;
try {
originHost = new URL(origin).host.toLowerCase();
} catch {
return false;
}
const forwardedHost = request.headers['x-forwarded-host'];
const hosts = [request.headers.host, ...(Array.isArray(forwardedHost) ? forwardedHost : (forwardedHost ?? '').split(','))];
return !!originHost && hosts.some(host => host?.trim().toLowerCase() === originHost);
}

// A page must never show a file with content from the pages under test inside a frame.
export function isFrameNavigation(request: http.IncomingMessage): boolean {
return ['iframe', 'frame', 'embed', 'object'].includes(String(request.headers['sec-fetch-dest']));
}

// Bracket IPv6 literals so they can be used as the host part of a URL.
export function urlHostFromAddress(address: { address: string, family: string }): string {
return address.family === 'IPv6' ? `[${address.address}]` : address.address;
Expand All @@ -378,9 +401,15 @@ export function serveFolder(folder: string): HttpServer {
const requested = url.searchParams.get('path');
if (!requested)
return false;
if (isFrameNavigation(request)) {
response.statusCode = 403;
response.end();
return true;
}
const resolved = path.resolve(requested);
try {
return server.serveFile(request, response, resolved);
// These files can have content from the pages under test. Do not run them as pages in the trace viewer origin.
return server.serveFile(request, response, resolved, { 'Content-Security-Policy': 'sandbox', 'X-Content-Type-Options': 'nosniff' });
} catch (e) {
return false;
}
Expand Down
22 changes: 22 additions & 0 deletions tests/playwright-test/ui-mode-test-setup.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,28 @@ for (const useWeb of [true, false]) {
expect(root.headers.get('location')).toBe(`./${prefix}/trace/uiMode.html${url.search}`);
expect((await fetch(url.origin + '/trace/file?path=' + encodeURIComponent(test.info().outputPath('a.test.js')))).status).toBe(404);
expect((await fetch(`${url.origin}/${prefix}/trace/uiMode.html`)).status).toBe(200);

// Project files do not run as pages in the UI mode origin, and do not load in frames.
const fileUrl = `${url.origin}/${prefix}/trace/file?path=` + encodeURIComponent(test.info().outputPath('a.test.js'));
const fileResponse = await fetch(fileUrl);
expect(fileResponse.status).toBe(200);
expect(fileResponse.headers.get('content-security-policy')).toBe('sandbox');
expect((await fetch(fileUrl, { headers: { 'sec-fetch-dest': 'iframe' } })).status).toBe(403);

// A sandboxed page has the "null" origin and cannot connect to the WebSocket.
const sandboxedWebSocket = await page.evaluate(async () => {
const iframe = document.createElement('iframe');
iframe.setAttribute('sandbox', 'allow-scripts');
iframe.srcdoc = `<script>
const ws = new WebSocket(${JSON.stringify(new URL('../ws', location.href).toString().replace('http', 'ws'))});
ws.onopen = () => parent.postMessage('open', '*');
ws.onerror = () => parent.postMessage('error', '*');
</` + `script>`;
const result = new Promise(f => window.addEventListener('message', event => f(event.data), { once: true }));
document.body.appendChild(iframe);
return await result;
});
expect(sandboxedWebSocket).toBe('error');
});
});
}
Expand Down
Loading