Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore: use isPathInside consistently (#40495)
Pavel Feldman3a47f3e5d50d
diff --git a/packages/playwright-core/src/cli/driver.ts b/packages/playwright-core/src/cli/driver.tsindex aac39382b4..05c28bc836 100644--- a/packages/playwright-core/src/cli/driver.ts+++ b/packages/playwright-core/src/cli/driver.ts@@ -72,6 +72,7 @@ export type RunServerOptions = {browserProxyMode?: 'client' | 'tether',ownedByTetherClient?: boolean,artifactsDir?: string,+ unsafe?: boolean,};export async function runServer(options: RunServerOptions) {@@ -82,8 +83,9 @@ export async function runServer(options: RunServerOptions) {maxConnections = Infinity,extension,artifactsDir,+ unsafe,} = options;- const server = new PlaywrightServer({ mode: extension ? 'extension' : 'default', path, maxConnections, artifactsDir });+ const server = new PlaywrightServer({ mode: extension ? 'extension' : 'default', path, maxConnections, artifactsDir, unsafe });const wsEndpoint = await server.listen(port, host);process.on('exit', () => server.close().catch(console.error));console.log('Listening on ' + wsEndpoint);diff --git a/packages/playwright-core/src/cli/program.ts b/packages/playwright-core/src/cli/program.tsindex 59a95c3b06..87d9735412 100644--- a/packages/playwright-core/src/cli/program.ts+++ b/packages/playwright-core/src/cli/program.ts@@ -177,6 +177,7 @@ export function decorateProgram(program: Command) {.option('--max-clients <maxClients>', 'Maximum clients').option('--mode <mode>', 'Server mode, either "default" or "extension"').option('--artifacts-dir <artifactsDir>', 'Artifacts directory')+ .option('--unsafe', 'Allow clients to set unsafe launch options (args, executablePath, ignoreAllDefaultArgs, etc)').action(async function(options) {runServer({port: options.port ? +options.port : undefined,@@ -185,6 +186,7 @@ export function decorateProgram(program: Command) {maxConnections: options.maxClients ? +options.maxClients : Infinity,extension: options.mode === 'extension' || !!process.env.PW_EXTENSION_MODE,artifactsDir: options.artifactsDir,+ unsafe: !!options.unsafe,}).catch(logErrorAndExit);});diff --git a/packages/playwright-core/src/remote/playwrightServer.ts b/packages/playwright-core/src/remote/playwrightServer.tsindex 7c45778cb9..7b8a30d2ca 100644--- a/packages/playwright-core/src/remote/playwrightServer.ts+++ b/packages/playwright-core/src/remote/playwrightServer.ts@@ -42,6 +42,7 @@ type ServerOptions = {preLaunchedAndroidDevice?: AndroidDevice;preLaunchedSocksProxy?: SocksProxy;artifactsDir?: string;+ unsafe?: boolean;};export class PlaywrightServer {@@ -106,8 +107,7 @@ export class PlaywrightServer {}const isExtension = this._options.mode === 'extension';- const allowFSPaths = isExtension;- launchOptions = filterLaunchOptions(launchOptions, allowFSPaths);+ launchOptions = filterLaunchOptions(launchOptions, isExtension || !!this._options.unsafe);// Always override artifacts dir with the one from server options.if (this._options.artifactsDir)@@ -363,21 +363,21 @@ function launchOptionsHash(options: LaunchOptionsWithTimeout) {return JSON.stringify(copy);}-function filterLaunchOptions(options: LaunchOptionsWithTimeout, allowFSPaths: boolean): LaunchOptionsWithTimeout {+function filterLaunchOptions(options: LaunchOptionsWithTimeout, allowUnsafe: boolean): LaunchOptionsWithTimeout {return {channel: options.channel,- args: options.args,- ignoreAllDefaultArgs: options.ignoreAllDefaultArgs,- ignoreDefaultArgs: options.ignoreDefaultArgs,+ args: allowUnsafe ? options.args : undefined,+ ignoreAllDefaultArgs: allowUnsafe ? options.ignoreAllDefaultArgs : undefined,+ ignoreDefaultArgs: allowUnsafe ? options.ignoreDefaultArgs : undefined,timeout: options.timeout,headless: options.headless,proxy: options.proxy,- chromiumSandbox: options.chromiumSandbox,- firefoxUserPrefs: options.firefoxUserPrefs,+ chromiumSandbox: allowUnsafe ? options.chromiumSandbox : undefined,+ firefoxUserPrefs: allowUnsafe ? options.firefoxUserPrefs : undefined,slowMo: options.slowMo,- executablePath: (isUnderTest() || allowFSPaths) ? options.executablePath : undefined,- downloadsPath: allowFSPaths ? options.downloadsPath : undefined,- artifactsDir: (isUnderTest() || allowFSPaths) ? options.artifactsDir : undefined,+ executablePath: (isUnderTest() || allowUnsafe) ? options.executablePath : undefined,+ downloadsPath: allowUnsafe ? options.downloadsPath : undefined,+ artifactsDir: (isUnderTest() || allowUnsafe) ? options.artifactsDir : undefined,};}diff --git a/packages/playwright-core/src/server/bidi/bidiPage.ts b/packages/playwright-core/src/server/bidi/bidiPage.tsindex 6637b0d46e..eb6fe320bd 100644--- a/packages/playwright-core/src/server/bidi/bidiPage.ts+++ b/packages/playwright-core/src/server/bidi/bidiPage.ts@@ -255,7 +255,7 @@ export class BidiPage implements PageDelegate {if (!originPage)return;- this._browserContext._browser.downloadCreated(originPage, event.navigation, event.url, event.suggestedFilename, event.suggestedFilename);+ this._browserContext._browser.downloadCreated(originPage, event.navigation, event.url, event.suggestedFilename);}private _onDownloadEnded(event: bidi.BrowsingContext.DownloadEndParams) {diff --git a/packages/playwright-core/src/server/harBackend.ts b/packages/playwright-core/src/server/harBackend.tsindex d85a07dc5f..bff11879e1 100644--- a/packages/playwright-core/src/server/harBackend.ts+++ b/packages/playwright-core/src/server/harBackend.ts@@ -18,6 +18,7 @@ import fs from 'fs';import path from 'path';import { createGuid } from '@utils/crypto';+import { isPathInside } from '@utils/fileUtils';import { ZipFile } from '@utils/zipFile';import type { HeadersArray } from '@isomorphic/types';@@ -78,10 +79,14 @@ export class HarBackend {const file = content._file;let buffer: Buffer;if (file) {- if (this._zipFile)+ if (this._zipFile) {buffer = await this._zipFile.read(file);- else- buffer = await fs.promises.readFile(path.resolve(this._baseDir!, file));+ } else {+ const resolved = path.resolve(this._baseDir!, file);+ if (!isPathInside(this._baseDir!, resolved))+ throw new Error(`HAR entry _file escapes base directory: ${file}`);+ buffer = await fs.promises.readFile(resolved);+ }} else {buffer = Buffer.from(content.text || '', content.encoding === 'base64' ? 'base64' : 'utf-8');}diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.tsindex 31e1b9cb90..c5bc0c8fc8 100644--- a/packages/playwright-core/src/server/registry/index.ts+++ b/packages/playwright-core/src/server/registry/index.ts@@ -1287,10 +1287,15 @@ export class Registry {} as any)[process.platform];const release = searchConfig ? product.releases.find((release: any) => release.platform === searchConfig.platform && release.architecture === searchConfig.arch && release.artifacts.length > 0) : null;const artifact = release ? release.artifacts.find((artifact: any) => artifact.artifactname === searchConfig.artifact) : null;- if (artifact)- scriptArgs.push(artifact.location /* url */);- else+ if (!artifact)throw new Error(`Cannot install ${channel} on ${process.platform}`);+ const location = String(artifact.location);+ if (!URL.canParse(location))+ throw new Error(`Cannot install ${channel}: invalid artifact url`);+ const parsed = new URL(location);+ if (parsed.protocol !== 'https:')+ throw new Error(`Cannot install ${channel}: artifact url must be https`);+ scriptArgs.push(location);}await this._installChromiumChannel(channel, scripts, scriptArgs);}@@ -1311,7 +1316,8 @@ export class Registry {if (code !== 0)throw new Error(`Failed to install ${channel}`);} else {- const { command, args, elevatedPermissions } = await transformCommandsForRoot([`bash "${path.join(BIN_PATH, scriptName)}" ${scriptArgs.join('')}`]);+ const shellArgs = scriptArgs.map(a => `'${a.replace(/'/g, `'\\''`)}'`).join(' ');+ const { command, args, elevatedPermissions } = await transformCommandsForRoot([`bash "${path.join(BIN_PATH, scriptName)}" ${shellArgs}`]);if (elevatedPermissions)console.log('Switching to root user to install dependencies...'); // eslint-disable-line no-consoleconst { code } = await spawnAsync(command, args, { cwd, stdio: 'inherit' });diff --git a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts b/packages/playwright-core/src/server/trace/viewer/traceViewer.tsindex bf26e56466..cd27f9b4cc 100644--- a/packages/playwright-core/src/server/trace/viewer/traceViewer.ts+++ b/packages/playwright-core/src/server/trace/viewer/traceViewer.ts@@ -16,12 +16,14 @@import fs from 'fs';import path from 'path';+import url from 'url';import open from 'open';import { HttpServer } from '@utils/httpServer';import { gracefullyProcessExitDoNotHang } from '@utils/processLauncher';import { isUnderTest } from '@utils/debug';import { isCodingAgent } from '@utils/env';+import { isPathInside } from '@utils/fileUtils';import { libPath } from '../../../package';import { syncLocalStorageWithSettings } from '../../launchApp';import { launchApp } from '../../launchApp';@@ -43,6 +45,7 @@ export type TraceViewerServerOptions = {port?: number;isServer?: boolean;transport?: Transport;+ allowedFileRoots?: string[];};export type TraceViewerRedirectOptions = {@@ -87,13 +90,20 @@ function validateTraceUrlOrPath(traceFileOrUrl: string | undefined): string | unexport async function startTraceViewerServer(options?: TraceViewerServerOptions): Promise<HttpServer> {const server = new HttpServer();+ const allowedRoots = (options?.allowedFileRoots ?? [process.cwd()]).map(r => path.resolve(r));+ const isAllowed = (filePath: string) => allowedRoots.some(root => isPathInside(root, filePath));const serveTraceDataRoute = (request: http.IncomingMessage, response: http.ServerResponse, relativePath: string): boolean => {if (!relativePath.startsWith('/file'))return false;const url = new URL('http://localhost' + request.url!);try {- const filePath = url.searchParams.get('path')!;+ const filePath = path.resolve(url.searchParams.get('path')!);+ if (!isAllowed(filePath)) {+ response.statusCode = 403;+ response.end();+ return true;+ }if (fs.existsSync(filePath))return server.serveFile(request, response, filePath);@@ -187,7 +197,7 @@ export async function installRootRedirect(server: HttpServer, traceUrl: string |export async function runTraceViewerApp(traceUrl: string | undefined, browserName: string, options: TraceViewerServerOptions & { headless?: boolean }) {traceUrl = validateTraceUrlOrPath(traceUrl);- const server = await startTraceViewerServer(options);+ const server = await startTraceViewerServer({ ...options, allowedFileRoots: traceFileRoots(traceUrl, options.allowedFileRoots) });await installRootRedirect(server, traceUrl, options);const page = await openTraceViewerApp(server.urlPrefix('precise'), browserName, options);page.on('close', () => gracefullyProcessExitDoNotHang(0));@@ -196,11 +206,23 @@ export async function runTraceViewerApp(traceUrl: string | undefined, browserNamexport async function runTraceInBrowser(traceUrl: string | undefined, options: TraceViewerServerOptions) {traceUrl = validateTraceUrlOrPath(traceUrl);- const server = await startTraceViewerServer(options);+ const server = await startTraceViewerServer({ ...options, allowedFileRoots: traceFileRoots(traceUrl, options.allowedFileRoots) });await installRootRedirect(server, traceUrl, options);await openTraceInBrowser(server.urlPrefix('human-readable'));}+function traceFileRoots(traceUrl: string | undefined, configured: string[] | undefined): string[] {+ if (configured)+ return configured;+ if (traceUrl?.startsWith('file://')) {+ try {+ return [path.dirname(url.fileURLToPath(traceUrl))];+ } catch {+ }+ }+ return [process.cwd()];+}+export async function openTraceViewerApp(url: string, browserName: string, options?: TraceViewerAppOptions): Promise<Page> {const traceViewerPlaywright = createPlaywright({ sdkLanguage: 'javascript', isInternalPlaywright: true });const traceViewerBrowser = isUnderTest() ? 'chromium' : browserName;diff --git a/packages/playwright-core/src/tools/backend/context.ts b/packages/playwright-core/src/tools/backend/context.tsindex a505652025..e0ba8dc3d4 100644--- a/packages/playwright-core/src/tools/backend/context.ts+++ b/packages/playwright-core/src/tools/backend/context.ts@@ -21,6 +21,7 @@ import debug from 'debug';import { escapeWithQuotes } from '@isomorphic/stringUtils';import { disposeAll } from '@isomorphic/disposable';import { eventsHelper } from '@utils/eventsHelper';+import { isPathInside } from '@utils/fileUtils';import { playwright } from '../../inprocess';import { Tab } from './tab';@@ -405,7 +406,6 @@ async function checkFile(options: ContextOptions, resolvedFilename: string, flag// Trust llm to use valid characters in file names.const output = outputDir(options);const workspace = options.cwd;- const withinDir = (root: string) => resolvedFilename === root || resolvedFilename.startsWith(root + path.sep);- if (!withinDir(output) && !withinDir(workspace))+ if (!isPathInside(output, resolvedFilename) && !isPathInside(workspace, resolvedFilename))throw new Error(`File access denied: ${resolvedFilename} is outside allowed roots. Allowed roots: ${output}, ${workspace}`);}diff --git a/packages/playwright/src/mcp/test/generatorTools.ts b/packages/playwright/src/mcp/test/generatorTools.tsindex 4b8e5cb12b..4552ae888f 100644--- a/packages/playwright/src/mcp/test/generatorTools.ts+++ b/packages/playwright/src/mcp/test/generatorTools.ts@@ -18,6 +18,8 @@ import fs from 'fs';import path from 'path';import * as z from 'zod';+import { isPathInside, resolveWithinRoot } from '@utils/fileUtils';+import { defineTestTool } from './testTool';import { GeneratorJournal } from './testContext';@@ -83,12 +85,11 @@ export const generatorWriteTest = defineTestTool({throw new Error('No test runner found, please setup page and perform actions first.');const config = await testRunner.loadConfig();+ const resolvedFile = resolveWithinRoot(context.rootPath, params.fileName);const dirs: string[] = [];for (const project of config.projects) {- const testDir = path.relative(context.rootPath, project.project.testDir).replace(/\\/g, '/');- const fileName = params.fileName.replace(/\\/g, '/');- if (fileName.startsWith(testDir)) {- const resolvedFile = path.resolve(context.rootPath, fileName);+ const projectTestDir = project.project.testDir;+ if (resolvedFile && isPathInside(projectTestDir, resolvedFile)) {await fs.promises.mkdir(path.dirname(resolvedFile), { recursive: true });await fs.promises.writeFile(resolvedFile, params.code);return {@@ -98,7 +99,7 @@ export const generatorWriteTest = defineTestTool({}]};}- dirs.push(testDir);+ dirs.push(path.relative(context.rootPath, projectTestDir).replace(/\\/g, '/'));}throw new Error(`Test file did not match any of the test dirs: ${dirs.join(', ')}`);},diff --git a/packages/playwright/src/mcp/test/plannerTools.ts b/packages/playwright/src/mcp/test/plannerTools.tsindex 1e6e9deaf8..800afd229e 100644--- a/packages/playwright/src/mcp/test/plannerTools.ts+++ b/packages/playwright/src/mcp/test/plannerTools.ts@@ -18,6 +18,8 @@ import fs from 'fs';import path from 'path';import * as z from 'zod';+import { resolveWithinRoot } from '@utils/fileUtils';+import { defineTestTool } from './testTool';export const setupPage = defineTestTool({@@ -117,7 +119,11 @@ export const saveTestPlan = defineTestTool({}}lines.push(``);- await fs.promises.writeFile(path.resolve(context.rootPath, params.fileName), lines.join('\n'));+ const resolvedFile = resolveWithinRoot(context.rootPath, params.fileName);+ if (!resolvedFile)+ throw new Error(`Plan file name must be a relative path inside the workspace: ${params.fileName}`);+ await fs.promises.mkdir(path.dirname(resolvedFile), { recursive: true });+ await fs.promises.writeFile(resolvedFile, lines.join('\n'));return {content: [{type: 'text',diff --git a/packages/playwright/src/reporters/merge.ts b/packages/playwright/src/reporters/merge.tsindex 9680bd5221..131985684f 100644--- a/packages/playwright/src/reporters/merge.ts+++ b/packages/playwright/src/reporters/merge.ts@@ -17,6 +17,7 @@import fs from 'fs';import path from 'path';+import { isPathInside } from '@utils/fileUtils';import { ZipFile } from '@utils/zipFile';import { currentBlobReportVersion } from './blob';@@ -68,7 +69,12 @@ export async function createMergedReport(config: FullConfigInternal, dir: string// a relative path on posix, and vice versa.// Therefore, we cannot use `path.resolve()` here - it will resolve relative-looking paths// against `process.cwd()`, while we just want to normalize ".." and "." segments.- resolvePath: (rootDir, relativePath) => stringPool.internString(pathPackage.normalize(pathPackage.join(rootDir, relativePath))),+ resolvePath: (rootDir, relativePath) => {+ const resolved = pathPackage.normalize(pathPackage.join(rootDir, relativePath));+ const escapes = pathPackage.isAbsolute(relativePath)+ || (resolved !== rootDir && !resolved.startsWith(rootDir + pathPackage.sep));+ return stringPool.internString(escapes ? pathPackage.join(rootDir, '<external>') : resolved);+ },configOverrides: config.config,});printStatus(`processing test events`);@@ -494,11 +500,16 @@ class AttachmentPathPatcher {}private _patchAttachments(attachments: JsonAttachment[]) {+ const resourceRoot = path.resolve(this._resourceDir);for (const attachment of attachments) {if (!attachment.path)continue;-- attachment.path = path.join(this._resourceDir, attachment.path);+ const joined = path.resolve(resourceRoot, attachment.path);+ if (!isPathInside(resourceRoot, joined)) {+ attachment.path = undefined;+ continue;+ }+ attachment.path = joined;}}}diff --git a/packages/utils/fileUtils.ts b/packages/utils/fileUtils.tsindex 9cca36eda6..fefe17a30b 100644--- a/packages/utils/fileUtils.ts+++ b/packages/utils/fileUtils.ts@@ -60,6 +60,21 @@ export function sanitizeForFilePath(s: string) {return s.replace(/[\x00-\x2C\x2E-\x2F\x3A-\x40\x5B-\x60\x7B-\x7F]+/g, '-');}+export function isPathInside(root: string, candidate: string): boolean {+ const resolvedRoot = path.resolve(root);+ const resolvedCandidate = path.resolve(candidate);+ if (resolvedCandidate === resolvedRoot)+ return true;+ return resolvedCandidate.startsWith(resolvedRoot + path.sep);+}++export function resolveWithinRoot(root: string, fileName: string): string | null {+ if (path.isAbsolute(fileName))+ return null;+ const resolvedFile = path.resolve(root, fileName);+ return isPathInside(root, resolvedFile) ? resolvedFile : null;+}+export function toPosixPath(aPath: string): string {return aPath.split(path.sep).join(path.posix.sep);}diff --git a/packages/utils/httpServer.ts b/packages/utils/httpServer.tsindex ca7599adc5..8691634ef4 100644--- a/packages/utils/httpServer.ts+++ b/packages/utils/httpServer.ts@@ -21,6 +21,7 @@ import mime from 'mime';import { WebSocketServer as wsServer } from 'ws';import { assert } from '@isomorphic/assert';import { createGuid } from './crypto';+import { isPathInside } from './fileUtils';import { createHttpServer, startHttpServer } from './network';import type http from 'http';@@ -51,6 +52,8 @@ export class HttpServer {private _started = false;private _routes: { prefix?: string, exact?: string, handler: ServerRouteHandler }[] = [];private _wsGuid: string | undefined;+ // Allowed Host headers; null disables the check (host bound to a public address).+ private _allowedHosts: Set<string> | null = null;constructor() {this._server = createHttpServer(this._onRequest.bind(this));@@ -169,6 +172,7 @@ export class HttpServer {const resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;this._urlPrefixPrecise = `http://${resolvedHost}:${address.port}`;this._urlPrefixHumanReadable = `http://${host ?? 'localhost'}:${address.port}`;+ this._allowedHosts = computeAllowedHosts(host, address.address, this._port);}}@@ -258,6 +262,15 @@ export class HttpServer {return;}+ if (this._allowedHosts) {+ const host = request.headers.host?.toLowerCase();+ if (!host || !this._allowedHosts.has(host)) {+ response.statusCode = 403;+ response.end();+ return;+ }+ }+request.on('error', () => response.end());try {if (!request.url) {@@ -279,14 +292,38 @@ export class HttpServer {}}+function computeAllowedHosts(requested: string | undefined, bound: string, port: number): Set<string> | null {+ const loopback = new Set(['127.0.0.1', '::1', 'localhost']);+ const isLoopback = (h: string | undefined) => h !== undefined && loopback.has(h.toLowerCase());+ if (!isLoopback(requested) && requested !== undefined)+ return null;+ if (!isLoopback(bound) && requested === undefined)+ return null;+ return new Set([+ `localhost:${port}`,+ `127.0.0.1:${port}`,+ `[::1]:${port}`,+ ]);+}+export function serveFolder(folder: string): HttpServer {const server = new HttpServer();+ const folderRoot = path.resolve(folder);server.routePrefix('/', (request, response) => {let relativePath = new URL('http://localhost' + request.url).pathname;if (relativePath.startsWith('/trace/file')) {const url = new URL('http://localhost' + request.url!);+ const requested = url.searchParams.get('path');+ if (!requested)+ return false;+ const resolved = path.resolve(requested);+ if (!isPathInside(folderRoot, resolved)) {+ response.statusCode = 403;+ response.end();+ return true;+ }try {- return server.serveFile(request, response, url.searchParams.get('path')!);+ return server.serveFile(request, response, resolved);} catch (e) {return false;}