diff --git a/.changeset/chromium-sandbox-default.md b/.changeset/chromium-sandbox-default.md new file mode 100644 index 0000000000..30466e450e --- /dev/null +++ b/.changeset/chromium-sandbox-default.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/web": minor +--- + +**Release:** Chromium launches with its OS sandbox on by default on macOS and Windows, which helps contain a renderer exploit on a page the agent reaches. `web({ chromiumSandbox })` turns it on for Linux, where it stays off by default, or off elsewhere. diff --git a/SECURITY.md b/SECURITY.md index 1c7d061164..112a544b59 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -78,6 +78,11 @@ elsewhere as one the agent may follow there, with the secrets the step was given. If a threat model ever calls for an origin allowlist again, it comes back as an opt-in. +On macOS and Windows a locally launched Chromium runs with its OS sandbox on, +which helps contain a renderer exploit on a page the agent reaches. On Linux, +where root and most containers cannot start it, `web({ chromiumSandbox: true })` +turns it on. + Child frames off the site of the target's `url`, its registrable domain, are dropped from observations. The browser engine's `headers` and `basicAuth` are scoped tighter, to the exact origin of `url` plus the origins diff --git a/docs/ja/reference/web.mdx b/docs/ja/reference/web.mdx index d82d2acb6c..ce58fdf51b 100644 --- a/docs/ja/reference/web.mdx +++ b/docs/ja/reference/web.mdx @@ -43,6 +43,7 @@ web({ viewport: { width: 390, height: 844 }, locale: 'de-DE' }); | オプション | 型 | デフォルト | | --- | --- | --- | | [`browser`](#browser) | `BrowserName \| BrowserProvider` | `'chromium'` | +| [`chromiumSandbox`](#chromiumsandbox) | `boolean` | `true`(Linux では `false`) | | [`viewport`](#viewport) | `ViewportSize \| null` | 1280 × 720 | | [`screencast`](#screencast) | `WebScreencastOptions` | ビューポートのサイズ | | [`connect`](#connect) | `WebConnectOptions` | ローカルで起動 | @@ -83,6 +84,23 @@ web({ browser: 'firefox' }); // default: 'chromium' | --- | --- | | `INVALID_CONFIG` | `browser: provider` と `connect` を併用した場合。 | +#### `chromiumSandbox` + +ローカルで起動する Chromium を OS のサンドボックス付きで動かすかどうかです。 + +```ts +web({ chromiumSandbox: true }); // default: true on macOS and Windows, false on Linux +``` + +- サンドボックスは、エージェントが到達したページでのレンダラーの脆弱性悪用を封じ込める助けになります。[セキュリティ](/security)を参照してください。 +- Linux のサンドボックスには非特権ユーザー名前空間が必要ですが、root、多くのコンテナ、Ubuntu 23.10 以降はこれをブロックします。許可しているホストでは `true` を設定してください。 +- `connect` やプロバイダー経由のブラウザはそのホストが起動し、Firefox と WebKit にはこのオプションがないため、いずれもこの設定を読みません。 + +| エラー | 発生条件 | +| --- | --- | +| `INVALID_CONFIG` | 真偽値以外の値を渡した場合(設定の読み込み時)。 | +| `ENGINE_FAILURE` | サンドボックスが有効で、このホストでは起動できない場合。 | + #### `viewport` 各試行のページの初期ビューポートです。 diff --git a/docs/ja/security.mdx b/docs/ja/security.mdx index 780721d499..449729f9b1 100644 --- a/docs/ja/security.mdx +++ b/docs/ja/security.mdx @@ -33,6 +33,8 @@ e2e は、利用者が書いたコードを信頼し、アプリが表示する モデルはツールを通してだけ操作します。ランナーは実行前に各呼び出しを閉じたスキーマで検証し、モデルのテキストをコードとして評価しません。組み込みツールは未宣言のキーを拒否します。ただしフィールドがないツールはキーを捨てて実行します。プロジェクトツールは自身の `defineTool` スキーマに従います。`file:` への移動など、ルールに違反する呼び出しは `POLICY_DENIED` で失敗します。オリジンの許可リストはありません。エージェントはアプリから別のサイトへ移動し、そこでステップのシークレットを使えます。 +macOS と Windows では、Chromium は OS のサンドボックスを有効にして起動します。エージェントが到達したページでのレンダラーの脆弱性悪用を封じ込める助けになります。Linux ではオプトインです。[`chromiumSandbox`](/reference/web#chromiumsandbox) を参照してください。 + ## 利用者の権限で実行されるもの テスト、設定、エンジン、ツール、レポーター、ストア、シークレットプロバイダー、アプリコマンドは、サンドボックスなしで利用者の OS 権限で動きます。信頼できないプルリクエストのコードは、シークレットや書き込みトークンを持たない外部サンドボックスで実行してください。 diff --git a/docs/reference/web.mdx b/docs/reference/web.mdx index 3ae12bdfa6..8a52e7fdf7 100644 --- a/docs/reference/web.mdx +++ b/docs/reference/web.mdx @@ -48,6 +48,7 @@ web({ viewport: { width: 390, height: 844 }, locale: 'de-DE' }); | Option | Type | Default | | --- | --- | --- | | [`browser`](#browser) | `BrowserName \| BrowserProvider` | `'chromium'` | +| [`chromiumSandbox`](#chromiumsandbox) | `boolean` | `true`, `false` on Linux | | [`viewport`](#viewport) | `ViewportSize \| null` | 1280 by 720 | | [`screencast`](#screencast) | `WebScreencastOptions` | the viewport's size | | [`connect`](#connect) | `WebConnectOptions` | launches locally | @@ -98,6 +99,26 @@ web({ browser: 'firefox' }); // default: 'chromium' | --- | --- | | `INVALID_CONFIG` | `browser: provider` together with `connect`. | +#### `chromiumSandbox` + +Whether a locally launched Chromium runs with its OS sandbox on. + +```ts +web({ chromiumSandbox: true }); // default: true on macOS and Windows, false on Linux +``` + +- The sandbox helps contain a renderer exploit on a page the agent reaches; + see [Security](/security). +- On Linux the sandbox needs unprivileged user namespaces, which root, most + containers, and Ubuntu 23.10+ block. Set `true` on a host that allows them. +- A browser reached through `connect` or a provider is launched by its host, + and Firefox and WebKit have no such option, so none of them read it. + +| Throws | When | +| --- | --- | +| `INVALID_CONFIG` | Any value that is not a boolean, at config load. | +| `ENGINE_FAILURE` | The sandbox is on and cannot start on this host. | + #### `viewport` The initial viewport of every attempt's page. diff --git a/docs/security.mdx b/docs/security.mdx index f2d4940d05..28a8f64096 100644 --- a/docs/security.mdx +++ b/docs/security.mdx @@ -61,6 +61,10 @@ which case it drops the keys and runs; a project tool follows its own `file:`, fails with `POLICY_DENIED`. There is no origin allowlist: the agent can follow the app to another site and use the step's secrets there. +On macOS and Windows, Chromium launches with its OS sandbox on, which helps +contain a renderer exploit on a page the agent reaches. On Linux it is opt-in: +see [`chromiumSandbox`](/reference/web#chromiumsandbox). + ## What runs with your permissions Your tests, config, engines, tools, reporters, stores, secret providers, and diff --git a/docs/zh/reference/web.mdx b/docs/zh/reference/web.mdx index 431cb8bda2..6276490828 100644 --- a/docs/zh/reference/web.mdx +++ b/docs/zh/reference/web.mdx @@ -43,6 +43,7 @@ web({ viewport: { width: 390, height: 844 }, locale: 'de-DE' }); | 选项 | 类型 | 默认值 | | --- | --- | --- | | [`browser`](#browser) | `BrowserName \| BrowserProvider` | `'chromium'` | +| [`chromiumSandbox`](#chromiumsandbox) | `boolean` | `true`,Linux 上为 `false` | | [`viewport`](#viewport) | `ViewportSize \| null` | 1280 × 720 | | [`screencast`](#screencast) | `WebScreencastOptions` | 视口尺寸 | | [`connect`](#connect) | `WebConnectOptions` | 在本地启动 | @@ -83,6 +84,23 @@ web({ browser: 'firefox' }); // default: 'chromium' | --- | --- | | `INVALID_CONFIG` | 同时设置 `browser: provider` 和 `connect`。 | +#### `chromiumSandbox` + +本地启动的 Chromium 是否启用操作系统沙箱。 + +```ts +web({ chromiumSandbox: true }); // default: true on macOS and Windows, false on Linux +``` + +- 沙箱有助于遏制智能体所到页面上的渲染进程漏洞利用,见[安全](/security)。 +- 在 Linux 上,沙箱需要非特权用户命名空间,而 root、大多数容器和 Ubuntu 23.10 及以上版本会阻止它。在允许的主机上设置 `true`。 +- 通过 `connect` 或提供方接入的浏览器由其主机启动,Firefox 和 WebKit 没有此选项,因此它们都不读取该设置。 + +| 抛出错误 | 触发条件 | +| --- | --- | +| `INVALID_CONFIG` | 值不是布尔值(加载配置时)。 | +| `ENGINE_FAILURE` | 沙箱已启用,但无法在此主机上启动。 | + #### `viewport` 每次尝试的页面初始视口。 diff --git a/docs/zh/security.mdx b/docs/zh/security.mdx index ead6e0e112..a380a4cf41 100644 --- a/docs/zh/security.mdx +++ b/docs/zh/security.mdx @@ -33,6 +33,8 @@ e2e 信任你编写的代码,并将应用显示的所有内容视为不可信 模型只能通过工具操作。运行器会在执行前按封闭的 schema 检查每次调用,绝不会将模型文本作为代码求值。内置工具会拒绝未声明的键,除非工具没有字段,此时它会丢弃这些键并执行;项目工具遵循自己的 `defineTool` schema。违反规则的调用(例如导航到 `file:`)会以 `POLICY_DENIED` 失败。没有源允许列表:智能体可以跟随应用进入其他网站,并在那里使用该步骤的机密值。 +在 macOS 和 Windows 上,Chromium 启动时会启用操作系统沙箱,这有助于遏制智能体所到页面上的渲染进程漏洞利用。在 Linux 上需要手动开启,见 [`chromiumSandbox`](/reference/web#chromiumsandbox)。 + ## 哪些内容以你的权限运行 你的测试、配置、引擎、工具、报告器、存储、机密值提供方和应用命令都以你的操作系统权限运行,不受沙箱隔离。请在没有机密值或写入令牌的外部沙箱中运行不可信的拉取请求(PR)代码。 diff --git a/packages/web/src/browser-connection.ts b/packages/web/src/browser-connection.ts index d3b4958a0b..69f041b63c 100644 --- a/packages/web/src/browser-connection.ts +++ b/packages/web/src/browser-connection.ts @@ -1,7 +1,9 @@ /** Shares one browser process connection across a worker's attempts. */ import type { Browser, BrowserType, ConnectOverCDPOptions } from 'playwright-core'; +import { EngineError } from '@e2e-dev/core/engine'; import { SELECTOR_ENGINES } from './selector-engines.ts'; +import { message } from './support.ts'; /** * Playwright, imported the first time a browser is looked up, launched, or @@ -38,6 +40,29 @@ export function isBrowserName(name: string): name is BrowserName { */ const RUNNER_OWNS_SIGNALS = { handleSIGINT: false, handleSIGTERM: false } as const; +/** + * Chromium's sandbox is on where it starts out of the box. On Linux it needs + * unprivileged user namespaces, which root, most containers, and Ubuntu + * 23.10+ refuse, so there it is opt-in. + */ +export function defaultChromiumSandbox(platform: NodeJS.Platform = process.platform): boolean { + return platform !== 'linux'; +} + +/** What `BrowserConnection.acquire` launches or attaches to. */ +export interface BrowserAcquireOptions { + /** Which browser to launch. */ + readonly name: BrowserName; + /** Whether the browser opens headed. */ + readonly headed: boolean; + /** How long a launch or attach may take. */ + readonly timeoutMs: number; + /** Whether a Chromium launch keeps its OS sandbox on; other browsers ignore it. */ + readonly chromiumSandbox: boolean; + /** Attaches to a remote browser instead of launching one, when given. */ + readonly connect?: (() => Promise) | undefined; +} + /** * Launching a browser process costs hundreds of milliseconds; per-attempt * isolation lives in browser contexts, so every attempt a worker runs can @@ -55,26 +80,20 @@ export class BrowserConnection { * so a caller that resolves a fresh per-run endpoint reconnects cleanly * after a dropped session. */ - async acquire( - name: BrowserName, - headed: boolean, - timeoutMs: number, - connect?: () => Promise, - ): Promise { + async acquire(options: BrowserAcquireOptions): Promise { + const { connect } = options; const cached = this.pending; if (cached !== undefined) { const browser = await cached.catch(() => null); if (browser !== null && browser.isConnected()) return browser; - if (this.pending !== cached) return this.acquire(name, headed, timeoutMs, connect); + if (this.pending !== cached) return this.acquire(options); this.pending = undefined; } // Set before anything awaits: the first call loads Playwright, and a `dispose` // that arrives meanwhile must close the browser this launch produces, while a // second caller waits for it instead of launching another. const launching = registerSelectorEngines().then(() => - connect !== undefined - ? connect() - : browserType(name).then((type) => type.launch({ headless: !headed, timeout: timeoutMs, ...RUNNER_OWNS_SIGNALS })), + connect !== undefined ? connect() : this.launchLocal(options), ); this.pending = launching; try { @@ -85,6 +104,34 @@ export class BrowserConnection { } } + /** + * A sandbox that cannot start fails with Playwright's whole launch call + * log; the engine error names the option instead. + */ + private async launchLocal(options: BrowserAcquireOptions): Promise { + const { name, headed, timeoutMs, chromiumSandbox } = options; + const type = await browserType(name); + try { + return await type.launch({ + headless: !headed, + timeout: timeoutMs, + ...RUNNER_OWNS_SIGNALS, + ...(name === 'chromium' ? { chromiumSandbox } : {}), + }); + } catch (cause) { + if (name === 'chromium' && chromiumSandbox && message(cause).includes('Chromium sandboxing failed!')) { + // No `cause`: the runner follows the chain into the surfaced + // message, which would put the call log back. + throw new EngineError( + 'ENGINE_FAILURE', + 'Chromium failed to launch because its sandbox cannot start on this host. Pass web({ chromiumSandbox: false }) to launch without the sandbox.', + { retryable: false }, + ); + } + throw cause; + } + } + /** Closes the connection, including a launch still in flight; idempotent and best-effort. */ async dispose(): Promise { const pending = this.pending; diff --git a/packages/web/src/engine.ts b/packages/web/src/engine.ts index a590f9999a..7b2140a144 100644 --- a/packages/web/src/engine.ts +++ b/packages/web/src/engine.ts @@ -94,6 +94,7 @@ export function web(options: WebOptions = {}): WebEngine { if (options.basicAuth !== undefined) validateBasicAuth(options.basicAuth); if (options.credentialOrigins !== undefined) validateCredentialOrigins(options); if (options.testIdAttribute !== undefined) validateTestIdAttribute(options.testIdAttribute); + if (options.chromiumSandbox !== undefined) validateChromiumSandbox(options.chromiumSandbox); if (options.userAgent !== undefined) validateUserAgent(options.userAgent, options.headers); if (options.locale !== undefined) validateLocale(options.locale, options.headers); if (options.timezoneId !== undefined) validateTimezoneId(options.timezoneId); @@ -176,6 +177,7 @@ export function web(options: WebOptions = {}): WebEngine { /** Every option `web()` takes, kept equal to `WebOptions` by the compiler. */ const WEB_OPTION_KEYS: readonly string[] = Object.keys({ browser: true, + chromiumSandbox: true, viewport: true, screencast: true, connect: true, @@ -437,6 +439,16 @@ function validateTestIdAttribute(attribute: unknown): void { } } +/** Refuses a sandbox opt-out that is not a boolean, at config load. */ +function validateChromiumSandbox(chromiumSandbox: unknown): void { + if (typeof chromiumSandbox !== 'boolean') { + throw new ConfigurationError( + 'INVALID_CONFIG', + `web({ chromiumSandbox }) must be a boolean, got ${JSON.stringify(chromiumSandbox)}`, + ); + } +} + /** * A browser target opens a URL: without `app.url` there is nothing for * `app.open()` to open, and the fields that describe an installed device app diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index 4cfd434080..718d3a3bc2 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -46,7 +46,7 @@ import { } from '@e2e-dev/core/engine'; import { matchesText } from '@e2e-dev/core/engine'; import { classifyActionError, classifyInputError, dispatchLocatorAction, dispatchPointerAction } from './actions.ts'; -import { BrowserConnection, connectCdp, type BrowserName } from './browser-connection.ts'; +import { BrowserConnection, connectCdp, defaultChromiumSandbox, type BrowserName } from './browser-connection.ts'; import { AttemptSession, type AttemptTab, type StorageState } from './attempt-session.ts'; import type { CdpEndpointResolver } from './cdp-recovery.ts'; import { LeasedBrowsers, type BrowserProvider, type LeaseDownloads } from './provider.ts'; @@ -178,6 +178,11 @@ export interface WebOptions { * provider implies chromium and excludes `connect`. */ readonly browser?: BrowserName | BrowserProvider; + /** + * Whether a locally launched Chromium runs with its OS sandbox on; default + * `true` on macOS and Windows, `false` on Linux. + */ + readonly chromiumSandbox?: boolean; /** * Initial viewport of every attempt's page; default 1280 by 720. `null` * emulates no size: the page fills the browser window, whatever size the @@ -297,6 +302,7 @@ export class PlaywrightSurface { private readonly browserName: BrowserName; private readonly connection = new BrowserConnection(); + private readonly chromiumSandbox: boolean; private readonly connect: WebConnectOptions | undefined; /** The provider's browsers, when `browser` names one; the runner and worker halves of the lease bookkeeping. */ private readonly leases: LeasedBrowsers | undefined; @@ -340,6 +346,7 @@ export class PlaywrightSurface { constructor(options: WebOptions) { this.browserName = typeof options.browser === 'string' ? options.browser : 'chromium'; + this.chromiumSandbox = options.chromiumSandbox ?? defaultChromiumSandbox(); this.leases = typeof options.browser === 'object' && options.browser !== null ? new LeasedBrowsers(options.browser) : undefined; this.connect = options.connect; this.viewport = options.viewport === undefined ? DEFAULT_VIEWPORT : options.viewport; @@ -426,7 +433,13 @@ export class PlaywrightSurface { if (signal.aborted) throw cancelled(`browser ${verb} cancelled`); try { return await raceAbort( - this.connection.acquire(this.browserName, this.headed, BROWSER_LAUNCH_TIMEOUT_MS, this.connector(signal)), + this.connection.acquire({ + name: this.browserName, + headed: this.headed, + timeoutMs: BROWSER_LAUNCH_TIMEOUT_MS, + chromiumSandbox: this.chromiumSandbox, + connect: this.connector(signal), + }), signal, `browser ${verb}`, ); diff --git a/packages/web/tests/integration/screenshot-caret.test.ts b/packages/web/tests/integration/screenshot-caret.test.ts index 74c78a8330..870b0421cd 100644 --- a/packages/web/tests/integration/screenshot-caret.test.ts +++ b/packages/web/tests/integration/screenshot-caret.test.ts @@ -3,7 +3,7 @@ import type { Browser, BrowserContext, Page } from 'playwright-core'; import { afterAll, beforeAll, expect, it, vi } from 'vitest'; import type { OperationContext } from '@e2e-dev/core/engine'; -import { BrowserConnection } from '../../src/browser-connection.ts'; +import { BrowserConnection, defaultChromiumSandbox } from '../../src/browser-connection.ts'; import { CLOSED_SHADOW_ROOTS_INIT_SCRIPT } from '../../src/closed-shadow.ts'; import { capturePixels } from '../../src/observe.ts'; import { startFixtureApp, type FixtureApp } from '../helpers/fixture-app.ts'; @@ -14,7 +14,7 @@ let context: BrowserContext; beforeAll(async () => { app = await startFixtureApp(); - const browser: Browser = await connection.acquire('chromium', false, 30_000); + const browser: Browser = await connection.acquire({ name: 'chromium', headed: false, timeoutMs: 30_000, chromiumSandbox: defaultChromiumSandbox() }); context = await browser.newContext({ viewport: { width: 320, height: 200 } }); await context.addInitScript(CLOSED_SHADOW_ROOTS_INIT_SCRIPT); }); diff --git a/packages/web/tests/integration/stalled-frame.test.ts b/packages/web/tests/integration/stalled-frame.test.ts index 2a1a9ad64e..bde3bd3913 100644 --- a/packages/web/tests/integration/stalled-frame.test.ts +++ b/packages/web/tests/integration/stalled-frame.test.ts @@ -7,7 +7,7 @@ import type { Browser, BrowserContext, Page, Route } from 'playwright-core'; import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest'; import type { OperationContext } from '@e2e-dev/core/engine'; -import { BrowserConnection } from '../../src/browser-connection.ts'; +import { BrowserConnection, defaultChromiumSandbox } from '../../src/browser-connection.ts'; import { CLOSED_SHADOW_ROOTS_INIT_SCRIPT } from '../../src/closed-shadow.ts'; import { captureObservation } from '../../src/observation-capture.ts'; import { capturePixels } from '../../src/observe.ts'; @@ -30,7 +30,7 @@ const operation: OperationContext = { beforeAll(async () => { app = await startFixtureApp(); - const browser: Browser = await connection.acquire('chromium', false, 30_000); + const browser: Browser = await connection.acquire({ name: 'chromium', headed: false, timeoutMs: 30_000, chromiumSandbox: defaultChromiumSandbox() }); context = await browser.newContext({ viewport: { width: 320, height: 200 } }); await context.addInitScript(CLOSED_SHADOW_ROOTS_INIT_SCRIPT); }); diff --git a/packages/web/tests/types/connection.ts b/packages/web/tests/types/connection.ts index 785d3fce70..d1fd576fa4 100644 --- a/packages/web/tests/types/connection.ts +++ b/packages/web/tests/types/connection.ts @@ -84,3 +84,6 @@ import type { BrowserLease, BrowserProvider, CdpTarget, WebConnectOptions, WebIn ({ endpoint: 'wss://browser.example', headers: { Authorization: 42 } }) satisfies CdpTarget; // @ts-expect-error a CDP target must name its endpoint. ({ cdpEndpoint: () => ({ headers: {} }) }) satisfies WebConnectOptions; +({ chromiumSandbox: false }) satisfies WebOptions; +// @ts-expect-error chromiumSandbox is a boolean. +({ chromiumSandbox: 'yes' }) satisfies WebOptions; diff --git a/packages/web/tests/unit/browser-connection.test.ts b/packages/web/tests/unit/browser-connection.test.ts index 67c68d47ba..08027d7f71 100644 --- a/packages/web/tests/unit/browser-connection.test.ts +++ b/packages/web/tests/unit/browser-connection.test.ts @@ -12,7 +12,7 @@ function fakeBrowser() { it('closes the browser a first launch produces when dispose arrives before that launch settles', async () => { const { browser, close } = fakeBrowser(); const connection = new BrowserConnection(); - const acquiring = connection.acquire('chromium', false, 1_000, async () => browser); + const acquiring = connection.acquire({ name: 'chromium', headed: false, timeoutMs: 1_000, chromiumSandbox: true, connect: async () => browser }); await connection.dispose(); await acquiring; expect(close).toHaveBeenCalledOnce(); @@ -23,8 +23,8 @@ it('launches once for two callers that ask before the first launch settles', asy const connect = vi.fn(async () => browser); const connection = new BrowserConnection(); const [first, second] = await Promise.all([ - connection.acquire('chromium', false, 1_000, connect), - connection.acquire('chromium', false, 1_000, connect), + connection.acquire({ name: 'chromium', headed: false, timeoutMs: 1_000, chromiumSandbox: true, connect }), + connection.acquire({ name: 'chromium', headed: false, timeoutMs: 1_000, chromiumSandbox: true, connect }), ]); expect(connect).toHaveBeenCalledOnce(); expect(second).toBe(first); diff --git a/packages/web/tests/unit/chromium-sandbox-surface.test.ts b/packages/web/tests/unit/chromium-sandbox-surface.test.ts new file mode 100644 index 0000000000..0ae2450688 --- /dev/null +++ b/packages/web/tests/unit/chromium-sandbox-surface.test.ts @@ -0,0 +1,52 @@ +/** The surface hands its launch the `chromiumSandbox` option, or the platform default without one. */ +import type { Browser } from 'playwright-core'; +import { afterEach, expect, it, vi } from 'vitest'; +import { defaultChromiumSandbox } from '../../src/browser-connection.ts'; +import { PlaywrightSurface, type WebOptions } from '../../src/surface.ts'; + +const acquire = vi.hoisted(() => vi.fn()); +vi.mock('../../src/browser-connection.ts', async (importOriginal) => ({ + ...(await importOriginal()), + BrowserConnection: class { + acquire = acquire; + dispose = async () => undefined; + }, +})); + +let surfaces: PlaywrightSurface[] = []; + +async function launchedSandbox(options: WebOptions): Promise { + acquire.mockReset(); + acquire.mockResolvedValue({} as unknown as Browser); + const surface = new PlaywrightSurface(options); + surfaces.push(surface); + await surface.init({ + runId: 'run', + targetName: 'web', + projectRoot: process.cwd(), + app: {}, + env: {}, + headed: false, + workerSlot: 0, + signal: new AbortController().signal, + log: () => undefined, + }); + expect(acquire).toHaveBeenCalledOnce(); + return (acquire.mock.calls[0]![0] as { chromiumSandbox: unknown }).chromiumSandbox; +} + +afterEach(async () => { + for (const surface of surfaces) { + await surface.dispose({ timeoutMs: 1_000, signal: new AbortController().signal }); + } + surfaces = []; +}); + +it('launches with the platform default when the option is omitted', async () => { + await expect(launchedSandbox({})).resolves.toBe(defaultChromiumSandbox()); +}); + +it('launches with what the option says', async () => { + await expect(launchedSandbox({ chromiumSandbox: false })).resolves.toBe(false); + await expect(launchedSandbox({ chromiumSandbox: true })).resolves.toBe(true); +}); diff --git a/packages/web/tests/unit/chromium-sandbox.test.ts b/packages/web/tests/unit/chromium-sandbox.test.ts new file mode 100644 index 0000000000..805b5d0559 --- /dev/null +++ b/packages/web/tests/unit/chromium-sandbox.test.ts @@ -0,0 +1,162 @@ +/** A Chromium launch takes the sandbox value it is asked for, and a sandbox that cannot start names the option. */ +import type { Browser } from 'playwright-core'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { BrowserConnection, defaultChromiumSandbox, type BrowserAcquireOptions } from '../../src/browser-connection.ts'; +import { web } from '../../src/engine.ts'; + +const chromiumLaunch = vi.hoisted(() => vi.fn()); +const firefoxLaunch = vi.hoisted(() => vi.fn()); +const webkitLaunch = vi.hoisted(() => vi.fn()); +vi.mock('playwright-core', () => ({ + chromium: { launch: chromiumLaunch }, + firefox: { launch: firefoxLaunch }, + webkit: { launch: webkitLaunch }, + selectors: { register: vi.fn() }, +})); + +/** A browser that reports itself connected, with the `close` its owner is expected to call. */ +function fakeBrowser(connected: () => boolean = () => true) { + const close = vi.fn(async () => undefined); + return { browser: { isConnected: connected, close } as unknown as Browser, close }; +} + +function launch(chromiumSandbox: boolean, overrides: Partial = {}): BrowserAcquireOptions { + return { name: 'chromium', headed: false, timeoutMs: 1_000, chromiumSandbox, ...overrides }; +} + +/** The single launch options object a mocked browser type was called with. */ +function launchOf(type: ReturnType): Record { + const calls = (type as unknown as { mock: { calls: unknown[][] } }).mock.calls; + expect(calls).toHaveLength(1); + return calls[0]![0] as Record; +} + +describe('BrowserConnection', () => { + beforeEach(() => { + chromiumLaunch.mockReset(); + firefoxLaunch.mockReset(); + webkitLaunch.mockReset(); + }); + + it('launches chromium with the sandbox on when asked', async () => { + const { browser } = fakeBrowser(); + chromiumLaunch.mockResolvedValue(browser); + const connection = new BrowserConnection(); + await connection.acquire(launch(true)); + expect(launchOf(chromiumLaunch)).toEqual({ + headless: true, + timeout: 1_000, + handleSIGINT: false, + handleSIGTERM: false, + chromiumSandbox: true, + }); + await connection.dispose(); + }); + + it('launches chromium with the sandbox off when asked', async () => { + const { browser } = fakeBrowser(); + chromiumLaunch.mockResolvedValue(browser); + const connection = new BrowserConnection(); + await connection.acquire(launch(false)); + expect(launchOf(chromiumLaunch)).toMatchObject({ chromiumSandbox: false }); + await connection.dispose(); + }); + + it('keeps the sandbox on when a waiter joins a relaunch that is still in flight', async () => { + let connected = true; + const { browser: first } = fakeBrowser(() => connected); + const { browser: third } = fakeBrowser(); + chromiumLaunch + .mockResolvedValueOnce(first) + .mockImplementationOnce( + () => + new Promise((_, reject) => { + setTimeout(() => reject(new Error('browserType.launch: Chromium sandboxing failed!')), 20); + }), + ) + .mockResolvedValueOnce(third); + const connection = new BrowserConnection(); + await connection.acquire(launch(true)); + connected = false; + // The relaunch is still in flight when the waiter joins it, so the + // waiter goes through the re-acquire once: a flip there cannot cancel + // out against a second one. + const relaunch = connection.acquire(launch(true)); + await new Promise((resolve) => setTimeout(resolve, 0)); + const waiter = connection.acquire(launch(true)); + const [relaunchResult, waiterResult] = await Promise.allSettled([relaunch, waiter]); + expect(relaunchResult.status).toBe('rejected'); + expect(waiterResult.status).toBe('fulfilled'); + expect(chromiumLaunch).toHaveBeenCalledTimes(3); + expect(chromiumLaunch.mock.calls.map((call) => (call[0] as { chromiumSandbox: unknown }).chromiumSandbox)).toEqual([true, true, true]); + await connection.dispose(); + }); + + it('turns a sandbox launch failure into an error naming the option', async () => { + chromiumLaunch.mockRejectedValueOnce( + new Error( + 'browserType.launch: Target page, context or browser has been closed\n' + + 'Chromium sandboxing failed!\n' + + 'Call log:\n' + + ' - launching Chromium with --no-sandbox --flag-a --flag-b', + ), + ); + const connection = new BrowserConnection(); + let error: (Error & { code?: unknown; cause?: unknown; retryable?: unknown }) | undefined; + try { + await connection.acquire(launch(true)); + } catch (caught) { + error = caught as Error & { code?: unknown; cause?: unknown; retryable?: unknown }; + } + expect(error?.code).toBe('ENGINE_FAILURE'); + expect(error?.retryable).toBe(false); + expect(error?.message).toContain('web({ chromiumSandbox: false })'); + expect(error?.message).not.toContain('Call log'); + expect(error?.message).not.toContain('--flag-a'); + expect(error?.cause).toBeUndefined(); + await connection.dispose(); + }); + + it('passes any other launch failure through unchanged', async () => { + const failure = new Error('browserType.launch: executable does not exist'); + chromiumLaunch.mockRejectedValueOnce(failure); + const connection = new BrowserConnection(); + await expect( + connection.acquire(launch(true)), + ).rejects.toBe(failure); + await connection.dispose(); + }); + + it('does not pass the chromium-only option to firefox or webkit', async () => { + const { browser } = fakeBrowser(); + firefoxLaunch.mockResolvedValue(browser); + webkitLaunch.mockResolvedValue(browser); + const connection = new BrowserConnection(); + await connection.acquire(launch(true, { name: 'firefox' })); + await connection.dispose(); + expect(launchOf(firefoxLaunch)).not.toHaveProperty('chromiumSandbox'); + const second = new BrowserConnection(); + await second.acquire(launch(true, { name: 'webkit' })); + await second.dispose(); + expect(launchOf(webkitLaunch)).not.toHaveProperty('chromiumSandbox'); + }); +}); + +describe('defaultChromiumSandbox', () => { + it('is on where the sandbox starts out of the box and off on Linux', () => { + expect(defaultChromiumSandbox('darwin')).toBe(true); + expect(defaultChromiumSandbox('win32')).toBe(true); + expect(defaultChromiumSandbox('linux')).toBe(false); + }); +}); + +describe('web({ chromiumSandbox })', () => { + it('rejects a value that is not a boolean as INVALID_CONFIG', () => { + expect(() => web({ chromiumSandbox: 'yes' as unknown as boolean })).toThrowError(expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringContaining('must be a boolean') })); + }); + + it('accepts true and false', () => { + expect(() => web({ chromiumSandbox: true })).not.toThrow(); + expect(() => web({ chromiumSandbox: false })).not.toThrow(); + }); +}); diff --git a/packages/web/tests/unit/protected-app-options.test.ts b/packages/web/tests/unit/protected-app-options.test.ts index d75f71fa1a..e36e00b86e 100644 --- a/packages/web/tests/unit/protected-app-options.test.ts +++ b/packages/web/tests/unit/protected-app-options.test.ts @@ -223,7 +223,7 @@ describe('web() option keys', () => { refused('web() has unknown key "viewprt"; did you mean "viewport"?'), ); expect(() => web({ launchOptions: {} } as unknown as Parameters[0])).toThrow( - refused('web() has unknown key "launchOptions"; expected one of browser, viewport, screencast, connect, headers, basicAuth, credentialOrigins, testIdAttribute, userAgent, locale, timezoneId, colorScheme, reducedMotion, initScripts'), + refused('web() has unknown key "launchOptions"; expected one of browser, chromiumSandbox, viewport, screencast, connect, headers, basicAuth, credentialOrigins, testIdAttribute, userAgent, locale, timezoneId, colorScheme, reducedMotion, initScripts'), ); }); diff --git a/packages/web/tests/unit/surface-lifecycle.test.ts b/packages/web/tests/unit/surface-lifecycle.test.ts index ed4570df42..71c0122dce 100644 --- a/packages/web/tests/unit/surface-lifecycle.test.ts +++ b/packages/web/tests/unit/surface-lifecycle.test.ts @@ -11,7 +11,8 @@ import { createBrowserFixture } from '../../src/browser.ts'; import { ignoreTrace, noSecrets } from '../helpers/secrets.ts'; const acquire = vi.hoisted(() => vi.fn()); -vi.mock('../../src/browser-connection.ts', () => ({ +vi.mock('../../src/browser-connection.ts', async (importOriginal) => ({ + ...(await importOriginal()), BrowserConnection: class { acquire = acquire; dispose = async () => undefined; }, connectCdp: vi.fn(), })); diff --git a/plugins/e2e/skills/e2e/references/setup.md b/plugins/e2e/skills/e2e/references/setup.md index e5f4feaedc..326980004f 100644 --- a/plugins/e2e/skills/e2e/references/setup.md +++ b/plugins/e2e/skills/e2e/references/setup.md @@ -242,6 +242,7 @@ start a script that brings them up and serves the app. | `colorScheme`, `reducedMotion` | The `prefers-color-scheme` (`'light'`, `'dark'`, `'no-preference'`) and `prefers-reduced-motion` (`'reduce'`, `'no-preference'`) every page reports to its `@media` rules and `matchMedia`, from first paint. | | `initScripts` | Scripts every document runs before the page's own: source, `{ path }`, or a function with no closures. | | `testIdAttribute` | What `getByTestId` reads; default `data-testid`. | +| `chromiumSandbox` | Whether a locally launched Chromium runs with its OS sandbox on; default `true` on macOS and Windows, `false` on Linux, where root and most containers cannot start it. | | `screencast` | `{ size?, quality? }` for the engine's own video: frame size (default the viewport's), JPEG quality 0 to 100. | - `basicAuth` via `secrets.get()` masks text, not screenshots or model pixels diff --git a/skills/e2e/references/setup.md b/skills/e2e/references/setup.md index e5f4feaedc..326980004f 100644 --- a/skills/e2e/references/setup.md +++ b/skills/e2e/references/setup.md @@ -242,6 +242,7 @@ start a script that brings them up and serves the app. | `colorScheme`, `reducedMotion` | The `prefers-color-scheme` (`'light'`, `'dark'`, `'no-preference'`) and `prefers-reduced-motion` (`'reduce'`, `'no-preference'`) every page reports to its `@media` rules and `matchMedia`, from first paint. | | `initScripts` | Scripts every document runs before the page's own: source, `{ path }`, or a function with no closures. | | `testIdAttribute` | What `getByTestId` reads; default `data-testid`. | +| `chromiumSandbox` | Whether a locally launched Chromium runs with its OS sandbox on; default `true` on macOS and Windows, `false` on Linux, where root and most containers cannot start it. | | `screencast` | `{ size?, quality? }` for the engine's own video: frame size (default the viewport's), JPEG quality 0 to 100. | - `basicAuth` via `secrets.get()` masks text, not screenshots or model pixels