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
fix(mcp): allow loopback hosts by default for all bind addresses (#42993)
Yury Semikhatsky5b8c4a0f524d
diff --git a/packages/playwright-core/src/tools/mcp/config.d.ts b/packages/playwright-core/src/tools/mcp/config.d.tsindex 0ab34a9ba4..1971b09db6 100644--- a/packages/playwright-core/src/tools/mcp/config.d.ts+++ b/packages/playwright-core/src/tools/mcp/config.d.ts@@ -121,7 +121,7 @@ export type Config = {host?: string;/**- * The hosts this server is allowed to serve from. Defaults to the host server is bound to.+ * The hosts this server is allowed to serve from. Defaults to localhost, loopback IPs and the host passed via --host; other hosts must be listed explicitly.* This is not for CORS, but rather for the DNS rebinding protection.*/allowedHosts?: string[];diff --git a/packages/playwright-core/src/tools/mcp/program.ts b/packages/playwright-core/src/tools/mcp/program.tsindex a921a42c94..eec1b45158 100644--- a/packages/playwright-core/src/tools/mcp/program.ts+++ b/packages/playwright-core/src/tools/mcp/program.ts@@ -33,7 +33,7 @@ const version = packageJSON.version;export function decorateMCPCommand(command: Command) {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-hosts <hosts...>', 'comma-separated list of hosts this server is allowed to serve from. Defaults to localhost, loopback IPs and the host passed via --host; other hosts must be listed explicitly. 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)diff --git a/packages/playwright-core/src/tools/utils/mcp/http.ts b/packages/playwright-core/src/tools/utils/mcp/http.tsindex 78e75b44e1..4d52df5964 100644--- a/packages/playwright-core/src/tools/utils/mcp/http.ts+++ b/packages/playwright-core/src/tools/utils/mcp/http.ts@@ -23,7 +23,6 @@ import debug from 'debug';import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';import { isUnderTest } from '@utils/debug';-import { urlHostFromAddress } from '@utils/httpServer';import { createHttpServer, startHttpServer } from '@utils/network';import { ManualPromise } from '@isomorphic/manualPromise';@@ -42,40 +41,29 @@ export async function startMcpHttpServer(): Promise<string> {const httpServer = createHttpServer();await startHttpServer(httpServer, config);- return await installHttpTransport(httpServer, serverBackendFactory, allowedHosts);-}--export function addressToString(address: string | net.AddressInfo | null, options: {- protocol: 'http' | 'ws';- normalizeLoopback?: boolean;-}): string {+ const address = httpServer.address();assert(address, 'Could not bind server socket');if (typeof address === 'string')throw new Error('Unexpected address type: ' + address);- let host = urlHostFromAddress(address);- if (options.normalizeLoopback && (host === '0.0.0.0' || host === '[::]' || host === '[::1]' || host === '127.0.0.1'))- host = 'localhost';- return `${options.protocol}://${host}:${address.port}`;+ const bindHost = config.host;+ const host = !bindHost || bindHost === '0.0.0.0' || bindHost === '::' ? 'localhost' : net.isIPv6(bindHost) ? `[${bindHost}]` : bindHost;+ const url = `http://${host}:${address.port}`;+ // Loopback names cannot be rebound, so they are safe to allow for any bind address. The host passed via --host is chosen by the user.+ allowedHosts = allowedHosts?.map(h => h.toLowerCase()) ?? [...new Set([`localhost:${address.port}`, `127.0.0.1:${address.port}`, `[::1]:${address.port}`, new URL(url).host])];+ installHttpTransport(httpServer, serverBackendFactory, allowedHosts);+ return url;}-async function installHttpTransport(httpServer: http.Server, serverBackendFactory: ServerBackendFactory, allowedHosts?: string[]) {- const url = addressToString(httpServer.address(), { protocol: 'http', normalizeLoopback: true });- const host = new URL(url).host;- allowedHosts = (allowedHosts || [host]).map(h => h.toLowerCase());+function installHttpTransport(httpServer: http.Server, serverBackendFactory: ServerBackendFactory, allowedHosts: string[]) {const allowAnyHost = allowedHosts.includes('*');const sseSessions = new Map();const streamableSessions = new Map();httpServer.on('request', async (req, res) => {if (!allowAnyHost) {+ // Prevent DNS evil.com -> localhost rebind. Browsers always send Host, requests without it are not affected.const host = req.headers.host?.toLowerCase();- if (!host) {- res.statusCode = 400;- return res.end('Missing host');- }-- // Prevent DNS evil.com -> localhost rebind.- if (!allowedHosts.includes(host)) {+ if (host && !allowedHosts.includes(host)) {// Access from the browser is forbidden.res.statusCode = 403;return res.end('Access is only allowed at ' + allowedHosts.join(', '));@@ -95,8 +83,6 @@ async function installHttpTransport(httpServer: http.Server, serverBackendFactorelseawait handleStreamable(serverBackendFactory, req, res, streamableSessions);});-- return url;}async function handleSSE(serverBackendFactory: ServerBackendFactory, req: http.IncomingMessage, res: http.ServerResponse, url: URL, sessions: Map<string, SSEServerTransportType>) {diff --git a/tests/mcp/http.spec.ts b/tests/mcp/http.spec.tsindex da13258d6f..3bda5da828 100644--- a/tests/mcp/http.spec.ts+++ b/tests/mcp/http.spec.ts@@ -15,7 +15,7 @@*/import fs from 'fs';-import dns from 'dns';+import http from 'http';import { ChildProcess, spawn } from 'child_process';import { chromium } from 'playwright';@@ -65,19 +65,6 @@ const test = baseTest.extend<{ serverEndpoint: (options?: { args?: string[], noP},});-async function resolveToIp(address: string) {- const resolvedIp = await new Promise<{ address: string, family: number }>((resolve, reject) => {- dns.lookup('localhost', (err, address, family) => {- if (err)- return reject(err);- resolve({ address, family }); // ::1 6 OR 127.0.0.1 4- });- });- if (resolvedIp.family === 6)- return `[${resolvedIp.address}]`;- return resolvedIp.address;-}-test('http transport', async ({ serverEndpoint }) => {const { url } = await serverEndpoint();const transport = new StreamableHTTPClientTransport(new URL('/mcp', url));@@ -705,12 +692,23 @@ test('should not run heartbeat when timeout is non-positive', async ({ serverEndawait client.close();});+async function requestWithHost(url: URL, host: string | undefined): Promise<{ status: number, text: string }> {+ return await new Promise((resolve, reject) => {+ const req = http.request(url, { method: 'GET', setHost: false, headers: host ? { host } : {} }, res => {+ let text = '';+ res.on('data', chunk => text += chunk);+ res.on('end', () => resolve({ status: res.statusCode!, text }));+ });+ req.on('error', reject);+ req.end();+ });+}+test('should not allow rebinding to localhost', async ({ serverEndpoint }) => {const { url } = await serverEndpoint();- const ip = await resolveToIp('localhost');- const response = await fetch(url.href.replace('localhost', ip));+ const response = await requestWithHost(url, `evil.com:${url.port}`);expect.soft(response.status).toBe(403);- expect.soft(await response.text()).toContain('Access is only allowed at localhost');+ expect.soft(response.text).toContain('Access is only allowed at localhost');});test('should respect allowed hosts (negative)', async ({ serverEndpoint }) => {@@ -734,6 +732,27 @@ test('should respect allowed hosts (positive)', async ({ serverEndpoint, findFreexpect(response.status).toBe(400);});+test('should allow only loopback hosts by default when bound to all interfaces', { annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42952' } }, async ({ serverEndpoint }) => {+ const { url } = await serverEndpoint({ args: ['--host=0.0.0.0'] });+ expect(url.hostname).toBe('localhost');+ // 400 is expected for the mcp fetch.+ expect((await fetch(`http://localhost:${url.port}`)).status).toBe(400);+ expect((await fetch(`http://127.0.0.1:${url.port}`)).status).toBe(400);+ expect((await requestWithHost(url, undefined)).status).toBe(400);+ const response = await requestWithHost(url, `some-container:${url.port}`);+ expect(response.status).toBe(403);+ expect(response.text).toContain('Access is only allowed at localhost');+});++test('should allow the bound host by default', async ({ serverEndpoint }) => {+ test.skip(process.platform !== 'linux', 'Only Linux routes all of 127.0.0.0/8 to loopback');+ const { url } = await serverEndpoint({ args: ['--host=127.0.0.2'] });+ expect(url.hostname).toBe('127.0.0.2');+ const response = await fetch(url.href);+ // 400 is expected for the mcp fetch.+ expect(response.status).toBe(400);+});+test('should be able to allow any host', async ({ serverEndpoint }) => {const { url } = await serverEndpoint({ args: ['--allowed-hosts=*'] });const response = await fetch(url.href);