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(wsServer): validate Host header on loopback bindings (#40503)
Pavel Feldmanb7e9be05449f
diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.tsindex c5bc0c8fc8..2aad085989 100644--- a/packages/playwright-core/src/server/registry/index.ts+++ b/packages/playwright-core/src/server/registry/index.ts@@ -1287,15 +1287,10 @@ 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)+ if (artifact)+ scriptArgs.push(artifact.location /* url */);+ elsethrow 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);}diff --git a/packages/playwright/src/reporters/merge.ts b/packages/playwright/src/reporters/merge.tsindex 131985684f..f9b964164e 100644--- a/packages/playwright/src/reporters/merge.ts+++ b/packages/playwright/src/reporters/merge.ts@@ -69,12 +69,7 @@ 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) => {- 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);- },+ resolvePath: (rootDir, relativePath) => stringPool.internString(pathPackage.normalize(pathPackage.join(rootDir, relativePath))),configOverrides: config.config,});printStatus(`processing test events`);diff --git a/packages/utils/httpServer.ts b/packages/utils/httpServer.tsindex 8691634ef4..cf36a2cbd4 100644--- a/packages/utils/httpServer.ts+++ b/packages/utils/httpServer.ts@@ -172,7 +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);+ this._allowedHosts = computeAllowedHosts(host, address.address);}}@@ -264,7 +264,8 @@ export class HttpServer {if (this._allowedHosts) {const host = request.headers.host?.toLowerCase();- if (!host || !this._allowedHosts.has(host)) {+ const hostname = host ? hostnameFromHostHeader(host) : undefined;+ if (!hostname || !this._allowedHosts.has(hostname)) {response.statusCode = 403;response.end();return;@@ -292,18 +293,23 @@ export class HttpServer {}}-function computeAllowedHosts(requested: string | undefined, bound: string, port: number): Set<string> | null {+export function computeAllowedHosts(requested: string | undefined, bound: string): 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}`,- ]);+ return new Set(['localhost', '127.0.0.1', '[::1]']);+}++export function hostnameFromHostHeader(host: string): string {+ if (host.startsWith('[')) {+ const end = host.indexOf(']');+ return end < 0 ? host : host.substring(0, end + 1);+ }+ const colon = host.indexOf(':');+ return colon < 0 ? host : host.substring(0, colon);}export function serveFolder(folder: string): HttpServer {diff --git a/packages/utils/wsServer.ts b/packages/utils/wsServer.tsindex 921a24dbd7..1fbbaad456 100644--- a/packages/utils/wsServer.ts+++ b/packages/utils/wsServer.ts@@ -15,6 +15,7 @@*/import { WebSocketServer as wsServer } from 'ws';+import { computeAllowedHosts, hostnameFromHostHeader } from './httpServer';import { createHttpServer } from './network';import { debugLogger } from './debugLogger';@@ -52,6 +53,8 @@ export class WSServer {private _wsServer: WebSocketServer | undefined;server: http.Server | undefined;private _delegate: WSServerDelegate;+ // Allowed Host headers for HTTP requests. null disables the check (server bound to a public address).+ private _allowedHosts: Set<string> | null = null;constructor(delegate: WSServerDelegate) {this._delegate = delegate;@@ -64,7 +67,7 @@ export class WSServer {// the caller explicitly opts in by passing a host (e.g. '0.0.0.0').hostname ??= 'localhost';- const server = createHttpServer(this._delegate.onRequest);+ const server = createHttpServer((request, response) => this._onRequest(request, response));server.on('error', error => debugLogger.log('server', String(error)));this.server = server;@@ -75,7 +78,10 @@ export class WSServer {reject(new Error('Could not bind server socket'));return;}- const wsEndpoint = typeof address === 'string' ? `${address}${path}` : `ws://${hostname}:${address.port}${path}`;+ const urlHost = hostname.includes(':') && !hostname.startsWith('[') ? `[${hostname}]` : hostname;+ const wsEndpoint = typeof address === 'string' ? `${address}${path}` : `ws://${urlHost}:${address.port}${path}`;+ if (typeof address !== 'string')+ this._allowedHosts = computeAllowedHosts(hostname, address.address);resolve(wsEndpoint);}).on('error', reject);});@@ -117,6 +123,19 @@ export class WSServer {return wsEndpoint;}+ private _onRequest(request: http.IncomingMessage, response: http.ServerResponse) {+ if (this._allowedHosts) {+ const host = request.headers.host?.toLowerCase();+ const hostname = host ? hostnameFromHostHeader(host) : undefined;+ if (!hostname || !this._allowedHosts.has(hostname)) {+ response.statusCode = 403;+ response.end();+ return;+ }+ }+ this._delegate.onRequest(request, response);+ }+async close() {const server = this._wsServer;if (!server)