Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

fix(server): guard JSON.parse in protocol message handlers (#40756)

Sebastien Tardifcb3312bc0483
diff --git a/packages/playwright-core/src/remote/playwrightConnection.ts b/packages/playwright-core/src/remote/playwrightConnection.ts
index 5bc2e69192..f03f7a1d8b 100644
--- a/packages/playwright-core/src/remote/playwrightConnection.ts
+++ b/packages/playwright-core/src/remote/playwrightConnection.ts
@@ -64,7 +64,14 @@ export class PlaywrightConnection {
transport.on('message', async (message: string) => {
await lock;
const messageString = Buffer.from(message).toString();
- const jsonMessage = JSON.parse(messageString);
+ let jsonMessage: any;
+ try {
+ jsonMessage = JSON.parse(messageString);
+ } catch (e) {
+ debugLogger.log('server', `[${this._id}] failed to parse message: ${e}`);
+ this.close({ code: 1007, reason: 'Malformed message' });
+ return;
+ }
if (debugLogger.isEnabled('server:channel'))
debugLogger.log('server:channel', `[${this._id}] ${monotonicTime() * 1000} ◀ RECV ${messageString}`);
if (debugLogger.isEnabled('server:metadata'))
diff --git a/tests/library/browsertype-connect.spec.ts b/tests/library/browsertype-connect.spec.ts
index ee2a5b3dc4..46fe27051d 100644
--- a/tests/library/browsertype-connect.spec.ts
+++ b/tests/library/browsertype-connect.spec.ts
@@ -158,6 +158,22 @@ for (const kind of ['launchServer', 'run-server'] as const) {
}
});
+ test('should not crash on malformed json frame', async ({ connect, startRemoteServer }) => {
+ const remoteServer = await startRemoteServer(kind);
+ const ws = new WebSocket(remoteServer.wsEndpoint());
+ await new Promise<void>((resolve, reject) => {
+ ws.once('open', resolve);
+ ws.once('error', reject);
+ });
+ ws.send(']');
+ await new Promise<void>(resolve => ws.once('close', () => resolve()));
+ // Server should still be alive and accept new connections.
+ const browser = await connect(remoteServer.wsEndpoint());
+ const page = await browser.newPage();
+ expect(await page.evaluate('1 + 2')).toBe(3);
+ await browser.close();
+ });
+
test('should be able to visit ipv6', async ({ connect, startRemoteServer, ipV6ServerPort, channel }) => {
test.fail(!!process.env.INSIDE_DOCKER, 'docker does not support IPv6 by default');
test.fail(channel === 'webkit-wsl', 'WebKit on WSL does not support IPv6: https://github.com/microsoft/WSL/issues/10803');