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
feat(launchServer): add allowClientNetwork option (#40493)
Dmitry Gozmanfa2d7584ee79
diff --git a/docs/src/api/class-browsertype.md b/docs/src/api/class-browsertype.mdindex a759f10959..ce815d6e8a 100644--- a/docs/src/api/class-browsertype.md+++ b/docs/src/api/class-browsertype.md@@ -426,6 +426,26 @@ of the `wsPath` can take control of the OS user. For this reason, you shoulduse an unguessable token when using this option.:::+### option: BrowserType.launchServer.allowClientNetwork+* since: v1.60+- `allowClientNetwork` <[string]>++This option allows the connecting client to expose its local network to the browser via+[`option: BrowserType.connect.exposeNetwork`]. The value is the maximum set of network rules+the server will accept; the client must request a subset of these rules through `exposeNetwork`,+otherwise its requests will be served directly from the server. Consists of a list of rules+separated by comma.++Available rules:+1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.+1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.+1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.++Some common examples:+1. `"*"` to allow exposing any network.+1. `"<loopback>"` to allow exposing localhost network.+1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to allow exposing test/staging deployments and localhost.+## method: BrowserType.name* since: v1.8- returns: <[string]>diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex 6c8ba8cba0..c612d45530 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -16001,6 +16001,26 @@ export interface BrowserType<Unused = {}> {* @param options*/launchServer(options?: {+ /**+ * This option allows the connecting client to expose its local network to the browser via+ * [`exposeNetwork`](https://playwright.dev/docs/api/class-browsertype#browser-type-connect-option-expose-network).+ * The value is the maximum set of network rules the server will accept; the client must request a subset of these+ * rules through `exposeNetwork`, otherwise its requests will be served directly from the server. Consists of a list+ * of rules separated by comma.+ *+ * Available rules:+ * 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.+ * 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.+ * 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.+ *+ * Some common examples:+ * 1. `"*"` to allow exposing any network.+ * 1. `"<loopback>"` to allow exposing localhost network.+ * 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to allow exposing test/staging deployments+ * and localhost.+ */+ allowClientNetwork?: string;+/*** **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.*diff --git a/packages/playwright-core/src/browserServerImpl.ts b/packages/playwright-core/src/browserServerImpl.tsindex d0776eae0a..17ec69eea1 100644--- a/packages/playwright-core/src/browserServerImpl.ts+++ b/packages/playwright-core/src/browserServerImpl.ts@@ -18,6 +18,7 @@ import EventEmitter from 'events';import { createGuid } from '@utils/crypto';import { isUnderTest } from '@utils/debug';+import { SocksProxy } from '@utils/socksProxy';import { rewriteErrorMessage } from '@isomorphic/stackTrace';import { DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT } from '@isomorphic/time';import { PlaywrightServer } from './remote/playwrightServer';@@ -57,6 +58,15 @@ export class BrowserServerLauncherImpl implements BrowserServerLauncher {timeout: options.timeout ?? DEFAULT_PLAYWRIGHT_LAUNCH_TIMEOUT,};+ // 2. Optionally start a SOCKS proxy that forwards client-allowed network requests back to the connecting client.+ let socksProxy: SocksProxy | undefined;+ let socksProxyPort: number | undefined;+ if (options.allowClientNetwork !== undefined) {+ socksProxy = new SocksProxy();+ socksProxy.setPattern(options.allowClientNetwork);+ socksProxyPort = await socksProxy.listen(0);+ }+let browser: Browser;try {const controller = new ProgressController(metadata);@@ -64,15 +74,16 @@ export class BrowserServerLauncherImpl implements BrowserServerLauncher {if (options._userDataDir !== undefined) {const validator = validatorPrimitives.scheme['BrowserTypeLaunchPersistentContextParams'];launchOptions = validator({ ...launchOptions, userDataDir: options._userDataDir }, '', validatorContext);- const context = await playwright[this._browserName].launchPersistentContext(progress, options._userDataDir, launchOptions);+ const context = await playwright[this._browserName].launchPersistentContext(progress, options._userDataDir, { ...launchOptions, socksProxyPort });return context._browser;} else {const validator = validatorPrimitives.scheme['BrowserTypeLaunchParams'];launchOptions = validator(launchOptions, '', validatorContext);- return await playwright[this._browserName].launch(progress, launchOptions, toProtocolLogger(options.logger));+ return await playwright[this._browserName].launch(progress, { ...launchOptions, socksProxyPort }, toProtocolLogger(options.logger));}});} catch (e) {+ await socksProxy?.close();const log = helper.formatBrowserLogs(metadata.log);rewriteErrorMessage(e, `${e.message} Failed to launch browser.${log}`);throw e;@@ -80,11 +91,11 @@ export class BrowserServerLauncherImpl implements BrowserServerLauncher {const path = options.wsPath ? (options.wsPath.startsWith('/') ? options.wsPath : `/${options.wsPath}`) : `/${createGuid()}`;- // 2. Start the server- const server = new PlaywrightServer({ mode: options._sharedBrowser ? 'launchServerShared' : 'launchServer', path, maxConnections: Infinity, preLaunchedBrowser: browser });+ // 3. Start the server+ const server = new PlaywrightServer({ mode: options._sharedBrowser ? 'launchServerShared' : 'launchServer', path, maxConnections: Infinity, preLaunchedBrowser: browser, preLaunchedSocksProxy: socksProxy });const wsEndpoint = await server.listen(options.port, options.host);- // 3. Return the BrowserServer interface+ // 4. Return the BrowserServer interfaceconst browserServer = new EventEmitter() as (BrowserServer & EventEmitter);browserServer.process = () => browser.options.browserProcess.process!;browserServer.wsEndpoint = () => wsEndpoint;@@ -94,6 +105,7 @@ export class BrowserServerLauncherImpl implements BrowserServerLauncher {(browserServer as any)._disconnectForTest = () => server.close();(browserServer as any)._userDataDirForTest = (browser as any)._userDataDirForTest;browser.options.browserProcess.onclose = (exitCode, signal) => {+ socksProxy?.close();server.close();browserServer.emit('close', exitCode, signal);};diff --git a/packages/playwright-core/src/client/types.ts b/packages/playwright-core/src/client/types.tsindex cb90ec932f..b29f8ebb8d 100644--- a/packages/playwright-core/src/client/types.ts+++ b/packages/playwright-core/src/client/types.ts@@ -109,6 +109,7 @@ export type LaunchServerOptions = LaunchOptions & {host?: string,port?: number,wsPath?: string,+ allowClientNetwork?: string,};export type LaunchAndroidServerOptions = {diff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex 6c8ba8cba0..c612d45530 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -16001,6 +16001,26 @@ export interface BrowserType<Unused = {}> {* @param options*/launchServer(options?: {+ /**+ * This option allows the connecting client to expose its local network to the browser via+ * [`exposeNetwork`](https://playwright.dev/docs/api/class-browsertype#browser-type-connect-option-expose-network).+ * The value is the maximum set of network rules the server will accept; the client must request a subset of these+ * rules through `exposeNetwork`, otherwise its requests will be served directly from the server. Consists of a list+ * of rules separated by comma.+ *+ * Available rules:+ * 1. Hostname pattern, for example: `example.com`, `*.org:99`, `x.*.y.com`, `*foo.org`.+ * 1. IP literal, for example: `127.0.0.1`, `0.0.0.0:99`, `[::1]`, `[0:0::1]:99`.+ * 1. `<loopback>` that matches local loopback interfaces: `localhost`, `*.localhost`, `127.0.0.1`, `[::1]`.+ *+ * Some common examples:+ * 1. `"*"` to allow exposing any network.+ * 1. `"<loopback>"` to allow exposing localhost network.+ * 1. `"*.test.internal-domain,*.staging.internal-domain,<loopback>"` to allow exposing test/staging deployments+ * and localhost.+ */+ allowClientNetwork?: string;+/*** **NOTE** Use custom browser args at your own risk, as some of them may break Playwright functionality.*diff --git a/tests/config/remoteServer.ts b/tests/config/remoteServer.tsindex c2989da4fd..5600c5a7f5 100644--- a/tests/config/remoteServer.ts+++ b/tests/config/remoteServer.ts@@ -70,6 +70,7 @@ export type RemoteServerOptions = {startStopAndRunHttp?: boolean;sharedBrowser?: boolean;artifactsDir?: string;+ allowClientNetwork?: string;};export class RemoteServer implements PlaywrightServer {@@ -100,6 +101,8 @@ export class RemoteServer implements PlaywrightServer {(launchOptions as any)._sharedBrowser = true;if (remoteServerOptions.artifactsDir)launchOptions.artifactsDir = remoteServerOptions.artifactsDir;+ if (remoteServerOptions.allowClientNetwork !== undefined)+ launchOptions.allowClientNetwork = remoteServerOptions.allowClientNetwork;const options = {browserTypeName: browserType.name(),channel,diff --git a/tests/library/browsertype-connect.spec.ts b/tests/library/browsertype-connect.spec.tsindex ee2a5b3dc4..31d173b499 100644--- a/tests/library/browsertype-connect.spec.ts+++ b/tests/library/browsertype-connect.spec.ts@@ -841,7 +841,9 @@ for (const kind of ['launchServer', 'run-server'] as const) {});test.describe('socks proxy', () => {- test.skip(kind === 'launchServer', 'not supported yet');+ // For 'launchServer', the proxy pattern is configured on the server up-front via allowClientNetwork.+ // For 'run-server', the proxy pattern comes from each connecting client.+ const allowAllOnServer = kind === 'launchServer' ? { allowClientNetwork: '*' } : undefined;test('should forward non-forwarded requests', async ({ server, startRemoteServer, connect }) => {let reachedOriginalTarget = false;@@ -849,7 +851,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {reachedOriginalTarget = true;res.end('<html><body>original-target</body></html>');});- const remoteServer = await startRemoteServer(kind);+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: '*' });const page = await browser.newPage();await page.goto(server.PREFIX + '/foo.html');@@ -866,7 +868,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {res.end('<html><body></body></html>');});const examplePort = 20_000 + testInfo.workerIndex * 3;- const remoteServer = await startRemoteServer(kind);+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: '*' } as any, dummyServerPort);const page = await browser.newPage();{@@ -897,7 +899,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {res.end('<html><body></body></html>');});const examplePort = 20_000 + testInfo.workerIndex * 3;- const remoteServer = await startRemoteServer(kind);+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: '*' }, ipV6ServerPort);const page = await browser.newPage();{@@ -928,7 +930,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {res.end('<html><body></body></html>');});const examplePort = 20_000 + workerInfo.workerIndex * 3;- const remoteServer = await startRemoteServer(kind);+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: '*' }, dummyServerPort);const page = await browser.newPage();{@@ -959,7 +961,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {res.end('<html><body></body></html>');});const examplePort = 20_000 + workerInfo.workerIndex * 3;- const remoteServer = await startRemoteServer(kind);+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: '*' }, ipV6ServerPort);const page = await browser.newPage();{@@ -988,7 +990,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {res.end('<html><body></body></html>');});const examplePort = 20_000 + workerInfo.workerIndex * 3;- const remoteServer = await startRemoteServer(kind);+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: '*' }, dummyServerPort);const page = await browser.newPage();await page.goto(`http://local.playwright:${examplePort}/foo.html`);@@ -998,7 +1000,7 @@ for (const kind of ['launchServer', 'run-server'] as const) {test('should lead to the error page for forwarded requests when the connection is refused', async ({ connect, startRemoteServer, browserName }, workerInfo) => {const examplePort = 20_000 + workerInfo.workerIndex * 3;- const remoteServer = await startRemoteServer(kind);+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: '*' });const page = await browser.newPage();const error = await page.goto(`http://127.0.0.1:${examplePort}`).catch(e => e);@@ -1019,7 +1021,8 @@ for (const kind of ['launchServer', 'run-server'] as const) {res.end('<html><body>from-original-server</body></html>');});const examplePort = 20_000 + workerInfo.workerIndex * 3;- const remoteServer = await startRemoteServer(kind);+ const serverOptions = kind === 'launchServer' ? { allowClientNetwork: 'localhost' } : undefined;+ const remoteServer = await startRemoteServer(kind, serverOptions);const browser = await connect(remoteServer.wsEndpoint(), { exposeNetwork: 'localhost' }, dummyServerPort);const page = await browser.newPage();@@ -1047,7 +1050,9 @@ for (const kind of ['launchServer', 'run-server'] as const) {reachedOriginalTarget = true;res.end('<html><body>from-original-server</body></html>');});- const remoteServer = await startRemoteServer(kind);+ // Server allows everything ('x-playwright-proxy': '*' for run-server, allowClientNetwork: '*' for launchServer)+ // so that the request reaches the client, where the client's exposeNetwork pattern will reject it.+ const remoteServer = await startRemoteServer(kind, allowAllOnServer);const browser = await connect(remoteServer.wsEndpoint(), {exposeNetwork: '127.0.0.1',headers: {