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(mcp): restrict file uploads to workspace roots (#38657)
Yury Semikhatsky55168134e37e
diff --git a/packages/playwright-core/src/client/browserContext.ts b/packages/playwright-core/src/client/browserContext.tsindex 83f83c8114..7395c80e65 100644--- a/packages/playwright-core/src/client/browserContext.ts+++ b/packages/playwright-core/src/client/browserContext.ts@@ -78,6 +78,8 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>private _closeReason: string | undefined;private _harRouters: HarRouter[] = [];private _onRecorderEventSink: RecorderEventSink | undefined;+ private _allowedProtocols: string[] | undefined;+ private _allowedDirectories: string[] | undefined;static from(context: channels.BrowserContextChannel): BrowserContext {return (context as any)._object;@@ -94,6 +96,7 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>this.tracing = Tracing.from(initializer.tracing);this.request = APIRequestContext.from(initializer.requestContext);this.request._timeoutSettings = this._timeoutSettings;+ this.request._checkUrlAllowed = (url: string) => this._checkUrlAllowed(url);this.clock = new Clock(this);this._channel.on('bindingCall', ({ binding }) => this._onBinding(BindingCall.from(binding)));@@ -538,6 +541,41 @@ export class BrowserContext extends ChannelOwner<channels.BrowserContextChannel>this._onRecorderEventSink = undefined;await this._channel.disableRecorder();}++ _setAllowedProtocols(protocols: string[]) {+ this._allowedProtocols = protocols;+ }++ _checkUrlAllowed(url: string) {+ if (!this._allowedProtocols)+ return;+ let parsedURL;+ try {+ parsedURL = new URL(url);+ } catch (e) {+ throw new Error(`Access to ${url} is blocked. Invalid URL: ${e.message}`);+ }+ if (!this._allowedProtocols.includes(parsedURL.protocol))+ throw new Error(`Access to "${parsedURL.protocol}" URL is blocked. Allowed protocols: ${this._allowedProtocols.join(', ')}. Attempted URL: ${url}`);+ }++ _setAllowedDirectories(rootDirectories: string[]) {+ this._allowedDirectories = rootDirectories;+ }++ _checkFileAccess(filePath: string) {+ if (!this._allowedDirectories)+ return;+ const path = this._platform.path().resolve(filePath);+ const isInsideDir = (container: string, child: string): boolean => {+ const path = this._platform.path();+ const rel = path.relative(container, child);+ return !!rel && !rel.startsWith('..') && !path.isAbsolute(rel);+ };+ if (this._allowedDirectories.some(root => isInsideDir(root, path)))+ return;+ throw new Error(`File access denied: ${filePath} is outside allowed roots. Allowed roots: ${this._allowedDirectories.length ? this._allowedDirectories.join(', ') : 'none'}`);+ }}async function prepareStorageState(platform: Platform, storageState: string | SetStorageState): Promise<NonNullable<channels.BrowserNewContextParams['storageState']>> {diff --git a/packages/playwright-core/src/client/elementHandle.ts b/packages/playwright-core/src/client/elementHandle.tsindex 93a600336d..fe206241aa 100644--- a/packages/playwright-core/src/client/elementHandle.ts+++ b/packages/playwright-core/src/client/elementHandle.ts@@ -284,6 +284,10 @@ export async function convertInputFiles(platform: Platform, files: string | Fileconst [localPaths, localDirectory] = await resolvePathsAndDirectoryForInputFiles(platform, items);+ localPaths?.forEach(path => context._checkFileAccess(path));+ if (localDirectory)+ context._checkFileAccess(localDirectory);+if (context._connection.isRemote()) {const files = localDirectory ? (await platform.fs().promises.readdir(localDirectory, { withFileTypes: true, recursive: true })).filter(f => f.isFile()).map(f => platform.path().join(f.path, f.name)) : localPaths!;const { writableStreams, rootDir } = await context._wrapApiCall(async () => context._channel.createTempFiles({diff --git a/packages/playwright-core/src/client/fetch.ts b/packages/playwright-core/src/client/fetch.tsindex efdece2211..ec32805eed 100644--- a/packages/playwright-core/src/client/fetch.ts+++ b/packages/playwright-core/src/client/fetch.ts@@ -91,6 +91,7 @@ export class APIRequestContext extends ChannelOwner<channels.APIRequestContextChreadonly _tracing: Tracing;private _closeReason: string | undefined;_timeoutSettings: TimeoutSettings;+ _checkUrlAllowed?: (url: string) => void;static from(channel: channels.APIRequestContextChannel): APIRequestContext {return (channel as any)._object;@@ -177,6 +178,7 @@ export class APIRequestContext extends ChannelOwner<channels.APIRequestContextChassert(options.maxRedirects === undefined || options.maxRedirects >= 0, `'maxRedirects' must be greater than or equal to '0'`);assert(options.maxRetries === undefined || options.maxRetries >= 0, `'maxRetries' must be greater than or equal to '0'`);const url = options.url !== undefined ? options.url : options.request!.url();+ this._checkUrlAllowed?.(url);const method = options.method || options.request?.method();let encodedParams = undefined;if (typeof options.params === 'string')diff --git a/packages/playwright-core/src/client/frame.ts b/packages/playwright-core/src/client/frame.tsindex 9470ebc712..0d52541e4d 100644--- a/packages/playwright-core/src/client/frame.ts+++ b/packages/playwright-core/src/client/frame.ts@@ -110,6 +110,7 @@ export class Frame extends ChannelOwner<channels.FrameChannel> implements api.Frasync goto(url: string, options: channels.FrameGotoOptions & TimeoutOptions = {}): Promise<network.Response | null> {const waitUntil = verifyLoadState('waitUntil', options.waitUntil === undefined ? 'load' : options.waitUntil);+ this.page().context()._checkUrlAllowed(url);return network.Response.fromNullable((await this._channel.goto({ url, ...options, waitUntil, timeout: this._navigationTimeout(options) })).response);}diff --git a/packages/playwright/src/mcp/browser/config.ts b/packages/playwright/src/mcp/browser/config.tsindex 38745c0d6e..970ecb19bb 100644--- a/packages/playwright/src/mcp/browser/config.ts+++ b/packages/playwright/src/mcp/browser/config.ts@@ -32,6 +32,7 @@ type ViewportSize = { width: number; height: number };export type CLIOptions = {allowedHosts?: string[];allowedOrigins?: string[];+ allowUnrestrictedFileAccess?: boolean;blockedOrigins?: string[];blockServiceWorkers?: boolean;browser?: string;@@ -247,6 +248,7 @@ export function configFromCLIOptions(cliOptions: CLIOptions): Config {allowedOrigins: cliOptions.allowedOrigins,blockedOrigins: cliOptions.blockedOrigins,},+ allowUnrestrictedFileAccess: cliOptions.allowUnrestrictedFileAccess,saveSession: cliOptions.saveSession,saveTrace: cliOptions.saveTrace,saveVideo: cliOptions.saveVideo,@@ -269,6 +271,7 @@ function configFromEnv(): Config {const options: CLIOptions = {};options.allowedHosts = commaSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_HOSTNAMES);options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);+ options.allowUnrestrictedFileAccess = envToBoolean(process.env.PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS);options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);diff --git a/packages/playwright/src/mcp/browser/context.ts b/packages/playwright/src/mcp/browser/context.tsindex 55596700ef..5d823058e1 100644--- a/packages/playwright/src/mcp/browser/context.ts+++ b/packages/playwright/src/mcp/browser/context.ts@@ -19,6 +19,8 @@ import fs from 'fs';import { debug } from 'playwright-core/lib/utilsBundle';import { escapeWithQuotes } from 'playwright-core/lib/utils';import { selectors } from 'playwright-core';+import { fileURLToPath } from 'url';+import os from 'os';import { logUnhandledError } from '../log';import { Tab } from './tab';@@ -237,6 +239,10 @@ export class Context {selectors.setTestIdAttribute(this.config.testIdAttribute);const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, this._runningToolName);const { browserContext } = result;+ if (!this.config.allowUnrestrictedFileAccess) {+ (browserContext as any)._setAllowedProtocols(['http:', 'https:', 'about:', 'data:']);+ (browserContext as any)._setAllowedDirectories(allRootPaths(this._clientInfo));+ }await this._setupRequestInterception(browserContext);if (this.sessionLog)await InputRecorder.create(this, browserContext);@@ -264,6 +270,28 @@ export class Context {}}+function allRootPaths(clientInfo: ClientInfo): string[] {+ const paths: string[] = [];+ for (const root of clientInfo.roots) {+ const url = new URL(root.uri);+ let rootPath;+ try {+ rootPath = fileURLToPath(url);+ } catch (e) {+ // Support WSL paths on Windows.+ if (e.code === 'ERR_INVALID_FILE_URL_PATH' && os.platform() === 'win32')+ rootPath = decodeURIComponent(url.pathname);+ }+ if (!rootPath)+ continue;+ paths.push(rootPath);+ }+ if (paths.length === 0)+ paths.push(process.cwd());+ return paths;+}++function originOrHostGlob(originOrHost: string) {try {const url = new URL(originOrHost);diff --git a/packages/playwright/src/mcp/config.d.ts b/packages/playwright/src/mcp/config.d.tsindex 1f10ecdf34..98706d634c 100644--- a/packages/playwright/src/mcp/config.d.ts+++ b/packages/playwright/src/mcp/config.d.ts@@ -189,4 +189,10 @@ export type Config = {*/mode?: 'incremental' | 'full' | 'none';}++ /**+ * Whether to allow file uploads from anywhere on the file system.+ * By default (false), file uploads are restricted to paths within the MCP roots only.+ */+ allowUnrestrictedFileAccess?: boolean;};diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.tsindex d26c6fa803..7495dd9af5 100644--- a/packages/playwright/src/mcp/program.ts+++ b/packages/playwright/src/mcp/program.ts@@ -34,6 +34,7 @@ export function decorateCommand(command: Command, version: string) {command.option('--allowed-hosts <hosts...>', 'comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass \'*\' to disable the host check.', commaSeparatedList).option('--allowed-origins <origins>', 'semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all.\nImportant: *does not* serve as a security boundary and *does not* affect redirects. ', semicolonSeparatedList)+ .option('--allow-unrestricted-file-access', 'allow access to files outside of the workspace roots. Also allows unrestricted access to file:// URLs. By default access to file system is restricted to workspace root directories (or cwd if no roots are configured) only, and navigation to file:// URLs is blocked.').option('--blocked-origins <origins>', 'semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.\nImportant: *does not* serve as a security boundary and *does not* affect redirects.', semicolonSeparatedList).option('--block-service-workers', 'block service workers').option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')diff --git a/packages/playwright/src/mcp/sdk/server.ts b/packages/playwright/src/mcp/sdk/server.tsindex 596edf427e..574070a194 100644--- a/packages/playwright/src/mcp/sdk/server.ts+++ b/packages/playwright/src/mcp/sdk/server.ts@@ -207,6 +207,21 @@ export function firstRootPath(clientInfo: ClientInfo): string | undefined {}}+export function allRootPaths(clientInfo: ClientInfo): string[] {+ const paths: string[] = [];+ for (const root of clientInfo.roots) {+ try {+ const url = new URL(root.uri);+ const path = fileURLToPath(url);+ if (path)+ paths.push(path);+ } catch (error) {+ serverDebug(error);+ }+ }+ return paths;+}+function mergeTextParts(result: CallToolResult): CallToolResult {const content: CallToolResult['content'] = [];const testParts: string[] = [];diff --git a/tests/mcp/core.spec.ts b/tests/mcp/core.spec.tsindex 7714bfa18d..a02b31f179 100644--- a/tests/mcp/core.spec.ts+++ b/tests/mcp/core.spec.ts@@ -14,6 +14,8 @@* limitations under the License.*/+import fs from 'fs/promises';+import { pathToFileURL } from 'url';import { test, expect } from './fixtures';test('browser_navigate', async ({ client, server }) => {@@ -31,6 +33,74 @@ test('browser_navigate', async ({ client, server }) => {});});+test('browser_navigate blocks file:// URLs by default', async ({ client }) => {+ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: { url: 'file:///etc/passwd' },+ })).toHaveResponse({+ result: expect.stringContaining('Error: Access to "file:" URL is blocked. Allowed protocols: http:, https:, about:, data:. Attempted URL: file:///etc/passwd'),+ isError: true,+ });+});++test('browser_navigate allows about:, data: and javascript: protocols', async ({ client, server }) => {+ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: { url: 'about:blank' },+ })).toHaveResponse({+ code: `await page.goto('about:blank');`,+ pageState: `- Page URL: about:blank+- Page Title:+- Page Snapshot:+\`\`\`yaml++\`\`\``,+ });++ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: { url: 'data:text/html,<h1>Hello</h1>' },+ })).toHaveResponse({+ code: `await page.goto('data:text/html,<h1>Hello</h1>');`,+ pageState: `- Page URL: data:text/html,<h1>Hello</h1>+- Page Title:+- Page Snapshot:+\`\`\`yaml+- heading \"Hello\" [level=1] [ref=e2]+\`\`\``,+ });+});++test('browser_navigate can navigate to file:// URLs allowUnrestrictedFileAccess is true', async ({ startClient }, testInfo) => {+ const rootDir = testInfo.outputPath();+ const fileOutsideRoot = testInfo.outputPath('test.txt');+ await fs.writeFile(fileOutsideRoot, 'Test file content');+ const { client } = await startClient({+ config: {+ allowUnrestrictedFileAccess: true,+ },+ roots: [+ {+ name: 'workspace',+ uri: pathToFileURL(rootDir).href,+ }+ ],+ });++ const url = pathToFileURL(fileOutsideRoot).href;+ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: { url },+ })).toHaveResponse({+ pageState: `- Page URL: ${url}+- Page Title:+- Page Snapshot:+\`\`\`yaml+- generic [ref=e2]: Test file content+\`\`\``,+ });+});+test('browser_select_option', async ({ client, server }) => {server.setContent('/', `<title>Title</title>@@ -53,7 +123,6 @@ test('browser_select_option', async ({ client, server }) => {values: ['bar'],},})).toHaveResponse({- code: `await page.getByRole('combobox').selectOption(['bar']);`,pageState: `- Page URL: ${server.PREFIX}/- Page Title: Title- Page Snapshot:diff --git a/tests/mcp/files.spec.ts b/tests/mcp/files.spec.tsindex 25f9286ab5..538a2370d1 100644--- a/tests/mcp/files.spec.ts+++ b/tests/mcp/files.spec.ts@@ -149,3 +149,179 @@ test('navigating to download link emits download', async ({ startClient, server,downloads: expect.stringMatching(`- Downloaded file test\.txt to|- Downloading file test\.txt`),});});++test('file upload restricted to roots by default', async ({ startClient, server }, testInfo) => {+ const rootDir = testInfo.outputPath('workspace');+ await fs.mkdir(rootDir, { recursive: true });++ const { client } = await startClient({+ roots: [+ {+ name: 'workspace',+ uri: `file://${rootDir}`,+ }+ ],+ });++ server.setContent('/', `<input type="file" />`, 'text/html');++ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ // Click on file input to trigger file chooser+ await client.callTool({+ name: 'browser_click',+ arguments: {+ element: 'Textbox',+ ref: 'e2',+ },+ });++ // Create a file inside the root+ const fileInsideRoot = testInfo.outputPath('workspace', 'inside.txt');+ await fs.writeFile(fileInsideRoot, 'Inside root');++ // Should succeed - file is inside root+ expect(await client.callTool({+ name: 'browser_file_upload',+ arguments: {+ paths: [fileInsideRoot],+ },+ })).toHaveResponse({+ code: expect.stringContaining(`await fileChooser.setFiles(`),+ });++ // Click again to open file chooser+ await client.callTool({+ name: 'browser_click',+ arguments: {+ element: 'Textbox',+ ref: 'e2',+ },+ });++ // Create a file outside the root+ const fileOutsideRoot = testInfo.outputPath('outside.txt');+ await fs.writeFile(fileOutsideRoot, 'Outside root');++ // Should fail - file is outside root+ expect(await client.callTool({+ name: 'browser_file_upload',+ arguments: {+ paths: [fileOutsideRoot],+ },+ })).toHaveResponse({+ isError: true,+ result: expect.stringMatching('File access denied: .* is outside allowed roots'),+ });+});++test('file upload is restricted to cwd if no roots are configured', async ({ startClient, server }, testInfo) => {+ const rootDir = testInfo.outputPath('workspace');+ await fs.mkdir(rootDir, { recursive: true });++ const { client } = await startClient({+ cwd: rootDir,+ });++ server.setContent('/', `<input type="file" />`, 'text/html');++ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ // Click on file input to trigger file chooser+ await client.callTool({+ name: 'browser_click',+ arguments: {+ element: 'Textbox',+ ref: 'e2',+ },+ });++ // Create a file inside the root+ const fileInsideRoot = testInfo.outputPath('workspace', 'inside.txt');+ await fs.writeFile(fileInsideRoot, 'Inside root');++ // Should succeed - file is inside root+ expect(await client.callTool({+ name: 'browser_file_upload',+ arguments: {+ paths: [fileInsideRoot],+ },+ })).toHaveResponse({+ code: expect.stringContaining(`await fileChooser.setFiles(`),+ });++ // Click again to open file chooser+ await client.callTool({+ name: 'browser_click',+ arguments: {+ element: 'Textbox',+ ref: 'e2',+ },+ });++ const fileOutsideRoot = testInfo.outputPath('outside.txt');+ await fs.writeFile(fileOutsideRoot, 'Outside root');++ expect(await client.callTool({+ name: 'browser_file_upload',+ arguments: {+ paths: [fileOutsideRoot],+ },+ })).toHaveResponse({+ isError: true,+ result: expect.stringMatching('File access denied: .* is outside allowed roots. Allowed roots: ' + rootDir.replace(/\\/g, '\\\\')),+ });+});++test('file upload unrestricted when flag is set', async ({ startClient, server }, testInfo) => {+ const rootDir = testInfo.outputPath('workspace');+ await fs.mkdir(rootDir, { recursive: true });++ const { client } = await startClient({+ config: {+ allowUnrestrictedFileAccess: true,+ },+ roots: [+ {+ name: 'workspace',+ uri: `file://${rootDir}`,+ }+ ],+ });++ server.setContent('/', `<input type="file" />`, 'text/html');++ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ // Click on file input to trigger file chooser+ await client.callTool({+ name: 'browser_click',+ arguments: {+ element: 'Textbox',+ ref: 'e2',+ },+ });++ // Create a file outside the root+ const fileOutsideRoot = testInfo.outputPath('outside.txt');+ await fs.writeFile(fileOutsideRoot, 'Outside root');++ // Should succeed - unrestricted uploads are allowed+ expect(await client.callTool({+ name: 'browser_file_upload',+ arguments: {+ paths: [fileOutsideRoot],+ },+ })).toHaveResponse({+ code: expect.stringContaining(`await fileChooser.setFiles(`),+ });+});diff --git a/tests/mcp/run-code.spec.ts b/tests/mcp/run-code.spec.tsindex 8a10abf1d2..a8e3149714 100644--- a/tests/mcp/run-code.spec.ts+++ b/tests/mcp/run-code.spec.ts@@ -14,6 +14,7 @@* limitations under the License.*/+import fs from 'fs/promises';import { test, expect } from './fixtures';test('browser_run_code', async ({ client, server }) => {@@ -76,6 +77,74 @@ test('browser_run_code no-require', async ({ client, server }) => {});});+test('browser_run_code blocks fetch of file:// URLs by default', async ({ client, server }) => {+ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.EMPTY_PAGE },+ });++ expect(await client.callTool({+ name: 'browser_run_code',+ arguments: {+ code: `async (page) => { await page.request.get('file:///etc/passwd'); }`,+ },+ })).toHaveResponse({+ result: expect.stringContaining('Error: apiRequestContext.get: Access to "file:" URL is blocked. Allowed protocols: http:, https:, about:, data:. Attempted URL: file:///etc/passwd'),+ isError: true,+ });+});++test('browser_run_code restricts setInputFiles to roots by default', async ({ startClient, server }, testInfo) => {+ const rootDir = testInfo.outputPath('workspace');+ await fs.mkdir(rootDir, { recursive: true });++ const { client } = await startClient({+ roots: [+ {+ name: 'workspace',+ uri: `file://${rootDir}`,+ }+ ],+ });++ server.setContent('/', `<input type="file" />`, 'text/html');++ await client.callTool({+ name: 'browser_navigate',+ arguments: { url: server.PREFIX },+ });++ // Create a file inside the root+ const fileInsideRoot = testInfo.outputPath('workspace', 'inside.txt');+ await fs.writeFile(fileInsideRoot, 'Inside root');++ expect(await client.callTool({+ name: 'browser_run_code',+ arguments: {+ code: `async (page) => {+ await page.locator('input').setInputFiles('${fileInsideRoot.replace(/\\/g, '\\\\')}');+ return 'success';+ }`,+ },+ })).toHaveResponse({+ result: '"success"',+ });++ // Create a file outside the root+ const fileOutsideRoot = testInfo.outputPath('outside.txt');+ await fs.writeFile(fileOutsideRoot, 'Outside root');++ expect(await client.callTool({+ name: 'browser_run_code',+ arguments: {+ code: `(page) => page.locator('input').setInputFiles('${fileOutsideRoot.replace(/\\/g, '\\\\')}')`,+ },+ })).toHaveResponse({+ isError: true,+ result: expect.stringMatching('File access denied: .* is outside allowed roots'),+ });+});+test('browser_run_code return value', async ({ client, server }) => {server.setContent('/', `<button onclick="console.log('Submit')">Submit</button>