From 466de7765d0a1ccad9b2c914bbed2094543eea54 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Mon, 26 Oct 2026 15:11:04 +0100 Subject: [PATCH 1/4] fix(web)!: scope headers and basicAuth to the app's origin headers went to every host on the app's site and basicAuth answered a 401 from any origin. Both now go to the app's exact origin, with headerOrigins and basicAuth.origins for extras. The runner passes the origin to engines as EngineAppInfo.origin. --- .changeset/engine-app-origin.md | 5 + .changeset/web-credential-origins.md | 7 ++ docs/migrate/playwright.mdx | 6 +- docs/reference/config.mdx | 17 +-- docs/reference/engine.mdx | 27 +++-- docs/reference/security.mdx | 40 +++++-- docs/reference/web.mdx | 56 ++++++--- docs/security.mdx | 5 +- docs/web.mdx | 16 +-- packages/e2e/src/config/app.ts | 11 +- packages/e2e/src/engine/index.ts | 19 +-- packages/e2e/src/internal/urls.ts | 7 +- .../tests/integration/engine-contract.test.ts | 1 + packages/e2e/tests/unit/app-ports.test.ts | 3 + packages/web/package.json | 2 +- packages/web/src/browser.ts | 16 +-- packages/web/src/engine.ts | 32 ++++- packages/web/src/protected-app.ts | 110 +++++++++++++----- packages/web/src/surface.ts | 57 ++++++--- packages/web/tests/helpers/fixture-app.ts | 5 + .../tests/integration/protected-app.test.ts | 75 +++++++++--- packages/web/tests/integration/routes.test.ts | 24 ++-- .../tests/unit/protected-app-options.test.ts | 69 ++++++++--- .../web/tests/unit/surface-lifecycle.test.ts | 13 ++- plugins/e2e/skills/e2e/references/setup.md | 4 +- .../skills/e2e/references/writing-tests.md | 4 +- skills/e2e/references/setup.md | 4 +- skills/e2e/references/writing-tests.md | 4 +- 28 files changed, 458 insertions(+), 181 deletions(-) create mode 100644 .changeset/engine-app-origin.md create mode 100644 .changeset/web-credential-origins.md diff --git a/.changeset/engine-app-origin.md b/.changeset/engine-app-origin.md new file mode 100644 index 0000000000..b2f8c06258 --- /dev/null +++ b/.changeset/engine-app-origin.md @@ -0,0 +1,5 @@ +--- +"e2e": patch +--- + +Engines receive the app's origin as `EngineAppInfo.origin` in `prepare` and `init`, on the run's port when `app.url` asks for a free one, so an engine can scope a credential it injects to the exact origin. diff --git a/.changeset/web-credential-origins.md b/.changeset/web-credential-origins.md new file mode 100644 index 0000000000..76612c3dd6 --- /dev/null +++ b/.changeset/web-credential-origins.md @@ -0,0 +1,7 @@ +--- +"@e2e-dev/web": minor +--- + +**Breaking:** `web({ headers })` and `web({ basicAuth })` go only to the app's origin, the scheme, host, and port of `app.url`. Before, `headers` went to every host on the app's site (another port on the same host, sibling subdomains, every host under a shared domain such as `vercel.app`), and `basicAuth` answered a `401` from any origin, so a third-party origin the app embeds could collect the credential. + +To migrate, list each other origin that needs the credential: `headerOrigins: ['https://api.example.com']` for `headers`, and `basicAuth: { username, password, origins: ['https://api.example.com'] }` for basic auth. An app whose `app.url` redirects to another origin (`http:` to `https:`, the apex to `www`) needs the origin it lands on listed, or set `app.url` to it. `headers` still ride a request's own redirects to any origin, as before. Requires `e2e` 0.23.1 or later. diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx index d2017ec7e7..1c030d32c5 100644 --- a/docs/migrate/playwright.mdx +++ b/docs/migrate/playwright.mdx @@ -68,8 +68,8 @@ A Playwright key such as `testDir`, `baseURL`, `use`, `webServer`, or | --- | --- | --- | | `use.viewport`, `use.browserName` | `web({ viewport, browser })` | renamed | | `use.testIdAttribute` | `web({ testIdAttribute })` | renamed | -| `use.httpCredentials` | `web({ basicAuth })` | renamed | -| `use.extraHTTPHeaders` | `web({ headers })`, sent to the app's site only | renamed | +| `use.httpCredentials` | `web({ basicAuth })`, answered for the app's origin only; `basicAuth.origins` adds more | renamed | +| `use.extraHTTPHeaders` | `web({ headers })`, sent to the app's origin only | renamed | | `chromium.connectOverCDP(url)` | `web({ connect: { cdpEndpoint: () => url } })`, chromium only | renamed | | `use.connectOptions` (`wsEndpoint`) | `web({ connect })` attaches over CDP only | missing | | `retries`, `workers`, `timeout` | the same names at the top level. `workers` takes an integer from 1 to 1024, not `'50%'`; `retries` stops at 10. The defaults differ, see [below](#defaults-that-differ) | renamed | @@ -256,7 +256,7 @@ uses it declares `requires: ['browser']` and other targets skip it. Calls on | --- | --- | --- | | `page.route(pattern, handler)` | `browser.route(pattern, handler)`; a string or `RegExp` pattern, no predicate function; the handler decides exactly once. A string is a glob on the full URL, never resolved against `app.url`. `?` matches any one character on purpose, where Playwright reads it literally; `{a,b}` is literal, and `**/` needs at least one segment | web only | | `route.fulfill({ json, body, path, status, headers, contentType })` | the same; one of `json`, `body`, or `path`, and `path` is relative to the project root. `body` is a string, `Buffer`, or `Uint8Array`, and a `\n`-joined `set-cookie` sets each cookie | web only | -| `route.continue({ url, method, headers, postData })`, `route.fallback()` | the same; a `url` resolves against `app.url` and keeps the request's `http` or `https` scheme. A header set to `undefined` is dropped; configured site headers still apply. `fallback()` takes no overrides | web only | +| `route.continue({ url, method, headers, postData })`, `route.fallback()` | the same; a `url` resolves against `app.url` and keeps the request's `http` or `https` scheme. A header set to `undefined` is dropped; configured headers still apply to an allowed origin. `fallback()` takes no overrides | web only | | `route.fetch()` | argument-free: no `timeout`, `headers`, or `maxRedirects` options, and redirects return unfollowed; returns `{ url, status, headers, body(), text(), json() }` without deciding the route | web only | | `route.abort(code)`, `route.fallback(overrides)` | none yet; `abort()` takes no error code | missing | | `page.unroute()` | `browser.unroute()` | web only | diff --git a/docs/reference/config.mdx b/docs/reference/config.mdx index 3509470c9d..07b3703bdf 100644 --- a/docs/reference/config.mdx +++ b/docs/reference/config.mdx @@ -382,8 +382,8 @@ url: 'http://localhost:3000', - A missing scheme becomes `https://`, or `http://` for a loopback host. - Plain HTTP is accepted for loopback hosts only. - Port `0` on `127.0.0.1` or `[::1]` asks for a [free port](#free-ports). -- Its site scopes engine headers and observed frames: see - [the app's site](#the-apps-site). +- Its origin scopes engine request credentials, and its site scopes observed + frames: see [the app's site](#the-apps-site). | Throws | When | | --- | --- | @@ -564,11 +564,14 @@ readyUrl: 'http://localhost:3000/health', // default: url A test or the agent may open any http(s) URL, and `about:blank`. Every other scheme (`file:`, `data:`, `javascript:`, `view-source:`, `blob:`) is `POLICY_DENIED`. The site of `url` is its registrable domain: -`app.example.com` and `auth.example.com` are one site. It scopes two things: - -- The browser engine's [`headers`](/reference/web#options) reach the site and - no other host. -- Child frames off the site stay out of observations. +`app.example.com` and `auth.example.com` are one site. Child frames off the +site stay out of observations. + +The browser engine's [`headers`](/reference/web#headers) and +[`basicAuth`](/reference/web#basicauth) are scoped tighter, to the origin of +`url` (scheme, host, and port, the run's free port included) plus the +origins you list. See +[request credentials](/reference/security#request-credentials). #### Free ports diff --git a/docs/reference/engine.mdx b/docs/reference/engine.mdx index f2dc8fe8e6..59ea73346e 100644 --- a/docs/reference/engine.mdx +++ b/docs/reference/engine.mdx @@ -729,7 +729,7 @@ export interface EngineInitInfo { * `process.cwd()`, which an in-process run does not change. */ readonly projectRoot: string; - /** The app the target declares: the site policy of its URL, and what a device launches. */ + /** The app the target declares: the origin and site policy of its URL, and what a device launches. */ readonly app: EngineAppInfo; /** * This worker's environment: the run's, plus what this target's `prepare` @@ -1291,6 +1291,7 @@ the declaration to [`validateApp`](#validateapp) at config load. | Target field | Reaches the engine as | | --- | --- | | `url` | `validateApp` only. The harness opens it through `session.open`. | +| the origin of `url`, on the run's port | `info.app.origin` in `prepare` and `init` | | the site of `url` | `info.app.site` in `prepare` and `init` | | `bundleId`, `appPath`, `launchArguments`, `permissions` | `validateApp`, and `info.app` in `prepare` and `init`, as the target declared them | | `command`, `readyUrl` | Never. The runner starts the app. | @@ -1342,26 +1343,32 @@ export type AppPermissionState = 'grant' | 'deny' | 'reset'; #### `EngineAppInfo` The resolved app, as `EnginePrepareInfo.app` and `EngineInitInfo.app`: the -site of the URL and the device fields as the target declared them. Apply the -site to a URL with [`sameSite`](#site-helpers). +origin and site of the URL, and the device fields as the target declared +them. Scope a credential the engine injects to the exact origin. Apply the +site to observed frames with [`sameSite`](#site-helpers). ```ts -if (sameSite(request.url, info.app.site ?? '')) request.headers.set('x-api-key', key); +if (new URL(request.url).origin === info.app.origin) request.headers.set('x-api-key', key); ``` ```ts /** * The app the harness resolved from the target's declaration, handed to - * `prepare` and `init`: the site policy for the decisions only a surface can - * make (which nested documents enter an observation, which requests carry - * injected credentials), and what a device launches. + * `prepare` and `init`: the origin and site policy for the decisions only a + * surface can make (which requests carry injected credentials, which nested + * documents enter an observation), and what a device launches. */ export interface EngineAppInfo { + /** + * The app URL's origin on the run's port (`scheme://host:port`, as + * `URL.origin` serializes it): where injected request credentials go. + * Absent when the app has no URL. + */ + readonly origin?: string; /** * The app URL's registrable domain, as read by `siteOf`. Use `sameSite` - * to scope secret fills, injected headers, and observed child frames. - * Absent when the app has no URL. The runner passes navigation URLs - * separately through `session.open`. + * to scope observed child frames. Absent when the app has no URL. The + * runner passes navigation URLs separately through `session.open`. */ readonly site?: string; /** The installed app to launch, as the target declared it. */ diff --git a/docs/reference/security.mdx b/docs/reference/security.mdx index 43df0f684b..6b200caa0f 100644 --- a/docs/reference/security.mdx +++ b/docs/reference/security.mdx @@ -16,7 +16,8 @@ lists the rules behind it, as the code enforces them. | [Tool calls](#tool-calls) | Built-in and project tools, node ids | | [Policy denials](#policy-denials) | Calls that fail with `POLICY_DENIED` | | [Navigation](#navigation) | URL schemes per entry point | -| [Site check](#site-check) | Headers, child frames, `basicAuth` | +| [Request credentials](#request-credentials) | `headers`, `basicAuth` | +| [Site check](#site-check) | Child frames | | [Secret fills](#secret-fills) | `type_secret`, `fill(secret)` | | [Screenshots after a secret fill](#screenshots-after-a-secret-fill) | What masking covers | | [Secrets in engine options](#secrets-in-engine-options) | `basicAuth` and other engine options | @@ -100,18 +101,37 @@ There is no origin allowlist. The agent can follow the app to other sites and use the step's secrets there. +### Request credentials + +The browser engine sends configured request credentials only to exact +origins: the scheme, host, and port of `app.url`, plus the extras you list. + +| Option | Goes to | Extra origins | +| --- | --- | --- | +| `headers` | Every request to an allowed origin | `headerOrigins` | +| `basicAuth` | The answer to a `401` challenge from an allowed origin | `basicAuth.origins` | + +- Another port on the same host, a subdomain, and a sibling host under a + shared domain such as `vercel.app` are other origins. They get no + credentials. +- `headers` follow the origin a request starts on. A request to an allowed + origin keeps them through every redirect, to any origin. A request that + starts elsewhere gets none, even when it redirects to an allowed origin. +- `basicAuth` answers the origin that sends the `401`. A redirect to another + origin, such as `http:` to `https:` or the apex to `www`, gets no answer + unless you list the origin it lands on. +- An extra is an `http:` or `https:` origin with no path, query, or + fragment, such as `https://api.example.com`. Anything else is + `INVALID_CONFIG` at config load. + ### Site check The browser engine compares hostnames to decide what counts as the target's -site. - -- Configured `headers` go only on requests to the target's site. -- Observations leave out child frames from other sites, and `data:` frames. -- The check approximates the registrable domain without a public suffix - list. A shared hosting domain such as `vercel.app` counts as one site, so - headers can reach other hosts under it. -- `basicAuth` ignores the site check. It answers a `401` challenge from any - origin. +site. Observations leave out child frames from other sites, and `data:` +frames. + +The check approximates the registrable domain without a public suffix list. +A shared hosting domain such as `vercel.app` counts as one site. ### Secret fills diff --git a/docs/reference/web.mdx b/docs/reference/web.mdx index f25db53014..00e5675628 100644 --- a/docs/reference/web.mdx +++ b/docs/reference/web.mdx @@ -52,6 +52,7 @@ web({ viewport: { width: 390, height: 844 }, locale: 'de-DE' }); | [`screencast`](#screencast) | `WebScreencastOptions` | the viewport's size | | [`connect`](#connect) | `WebConnectOptions` | launches locally | | [`headers`](#headers) | `Record` | - | +| [`headerOrigins`](#headerorigins) | `string[]` | - | | [`basicAuth`](#basicauth) | `WebBasicAuth` | - | | [`testIdAttribute`](#testidattribute) | `string` | `'data-testid'` | | [`userAgent`](#useragent) | `string` | the browser's own | @@ -240,15 +241,18 @@ session state capture and restore. `app.clearState` fails with #### `headers` -Headers added to requests within the app's site, including subdomains. +Headers added to every request to the app's origin: the scheme, host, and +port of `app.url`. Another port, a subdomain, and any other host get none. ```ts web({ headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' } }); ``` -- A [continued](#route) request bound for the app's site still carries them. +- A [continued](#route) request bound for an allowed origin still carries + them. - `headers` and `basicAuth` are how a test reaches a [protected preview](/web#protected-previews). +- See [request credentials](/reference/security#request-credentials). | Throws | When | | --- | --- | @@ -259,15 +263,33 @@ web({ headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' } }); blocks service workers. +#### `headerOrigins` + +More origins that receive [`headers`](#headers), beyond the app's own, such +as an API on another host behind the same gate. + +```ts +web({ + headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' }, + headerOrigins: ['https://api.staging.example.com'], +}); +``` + +| Throws | When | +| --- | --- | +| `INVALID_CONFIG` | No `headers`, or an entry that is not an `http:` or `https:` origin with no path, query, or fragment. | + #### `basicAuth` -HTTP basic authentication. The browser answers a `401` challenge with these -credentials on any origin, matching Playwright's `httpCredentials`. +HTTP basic authentication. The browser answers a `401` challenge from the +app's origin with these credentials. A challenge from any other origin goes +unanswered unless `origins` lists it. ```ts import { secrets } from 'e2e'; web({ basicAuth: { username: 'staging', password: secrets.get('staging-password') } }); +web({ basicAuth: { username: 'staging', password: secrets.get('staging-password'), origins: ['https://api.staging.example.com'] } }); ``` A `secrets.get(name)` password resolves when each attempt starts and is @@ -275,18 +297,20 @@ redacted like any configured secret. So is the base64 credential of the `Authorization` header it becomes. ```ts -/** HTTP basic authentication the browser answers a `401` challenge with. */ +/** HTTP basic authentication the browser answers a `401` challenge from the app's origin with. */ export interface WebBasicAuth { /** The user name; `:` is not allowed in one (RFC 7617). */ readonly username: string; /** The password, or `secrets.get(name)` for one in `config.secrets`. */ readonly password: string | Secret; + /** More origins whose challenge the browser answers, such as `https://api.example.com`. */ + readonly origins?: readonly string[]; } ``` | Throws | When | | --- | --- | -| `INVALID_CONFIG` | A `:` in the user name, or an unknown key. | +| `INVALID_CONFIG` | A `:` in the user name, an unknown key, or an `origins` entry that is not an `http:` or `https:` origin with no path, query, or fragment. | The secret protection is text only. A page that renders the password on @@ -616,7 +640,8 @@ await browser.route('**/api/quote', async (route) => { ``` `route.fetch()` returns the upstream `{ url, status, headers, body(), text(), json() }` -with the site's headers, under the action timeout, without deciding the route. +with the configured headers when its origin gets them, under the action +timeout, without deciding the route. It does not follow redirects, which could take it past the navigation rule. - The pattern is a string or a `RegExp`, both tested against the full URL. In @@ -672,7 +697,7 @@ export interface RouteContinueOverrides { url?: string; /** Request method. */ method?: string; - /** Replaces every request header; `undefined` drops one, and the configured `headers` for the app's site are added on top. */ + /** Replaces every request header; `undefined` drops one, and the configured `headers` for an allowed origin are added on top. */ headers?: Record; /** Request body. */ postData?: string; @@ -715,7 +740,7 @@ await browser.unroute('**/api/quote'); #### `unrouteAll` Removes every route registered by the browser fixture, preserving configured -site headers. +headers. ```ts await browser.unrouteAll(); @@ -1079,16 +1104,19 @@ export interface WebOptions { */ readonly connect?: WebConnectOptions; /** - * Headers added to requests within the app's site, including subdomains. - * Useful for preview-protection tokens. Other sites never receive them. + * Headers added to every request to the app's origin (the scheme, host, + * and port of `app.url`) or one in `headerOrigins`. Useful for + * preview-protection tokens. Other origins never receive them. * Names are case-insensitive and replace existing headers of the same name. * This enables request routing, disables the browser's HTTP cache, and * blocks service workers. */ readonly headers?: Readonly>; + /** More origins that receive `headers`, such as `https://api.example.com`; requires `headers`. */ + readonly headerOrigins?: readonly string[]; /** - * HTTP basic authentication. The browser answers a `401` challenge with - * these credentials on any origin, matching Playwright's `httpCredentials`. + * HTTP basic authentication. The browser answers a `401` challenge from the + * app's origin, or one in `basicAuth.origins`, with these credentials. */ readonly basicAuth?: WebBasicAuth; /** @@ -1183,7 +1211,7 @@ export interface Browser extends Expectable { ): Promise; /** Removes matching attempt-scoped routes. */ unroute(pattern: string | RegExp): Promise; - /** Removes all routes registered by this browser fixture, preserving configured site headers. */ + /** Removes all routes registered by this browser fixture, preserving the configured headers. */ unrouteAll(): Promise; /** Waits for a matching response. */ waitForResponse( diff --git a/docs/security.mdx b/docs/security.mdx index 2ee427e49e..4b8b32549c 100644 --- a/docs/security.mdx +++ b/docs/security.mdx @@ -35,8 +35,9 @@ Redaction matches strings, and screenshots mask secure fields only: pass through. Assert the outcome, not the secret. - **Values not filled as a secret.** Only a configured secret's value is redacted. A value a sign-in sets in a cookie is not. -- **Request credentials.** `basicAuth` answers a `401` from any origin. - `headers` reach every host under a shared domain such as `vercel.app`. +- **Request credentials.** `headers` and `basicAuth` go on every request to + the app's origin and each origin you list, even one a third-party page + starts. `headers` also stay on that request's redirects to any origin. - **Committed recordings.** Cache entries store typed values verbatim, except secret fills. They aren't signed and replay with your permissions, so review them as you would test code. diff --git a/docs/web.mdx b/docs/web.mdx index efdeae1f0b..323a69a97e 100644 --- a/docs/web.mdx +++ b/docs/web.mdx @@ -132,10 +132,11 @@ app: { }, ``` -The browser sends `headers` only to the target's site: its hostname, its -subdomains, and every host under a shared suffix such as `vercel.app`. Read -[header scope](/reference/security#site-check) before you use a bypass -secret. For ngrok, use `'ngrok-skip-browser-warning': '1'`. +The browser sends `headers` only to the origin of `app.url`: its scheme, +host, and port. To send them to another origin, such as an API host behind +the same gate, list it in `headerOrigins`. See +[request credentials](/reference/security#request-credentials). For ngrok, +use `'ngrok-skip-browser-warning': '1'`. `app.identity` keeps the cache identity stable when the preview URL changes. @@ -143,9 +144,10 @@ Setting `headers` turns off the browser's HTTP cache and blocks service workers. -Use `basicAuth` for HTTP basic authentication. The browser sends the -credentials to any origin that answers with a `401` challenge. Declare the -password under `secrets` and pass `secrets.get(name)`: +Use `basicAuth` for HTTP basic authentication. The browser answers a `401` +challenge from the origin of `app.url`, and from each origin in +`basicAuth.origins`. Declare the password under `secrets` and pass +`secrets.get(name)`: ```ts title="e2e.config.ts" import type { E2EConfig } from 'e2e'; diff --git a/packages/e2e/src/config/app.ts b/packages/e2e/src/config/app.ts index 70329385f2..cc0763621a 100644 --- a/packages/e2e/src/config/app.ts +++ b/packages/e2e/src/config/app.ts @@ -50,9 +50,8 @@ export interface ResolvedApp { /** The free-port request the declared URL made; undefined when it names a port or there is no URL. */ readonly portRequest: PortRequest | undefined; /** - * The site of the base URL, as `siteOf` reads it: where configured - * headers go and whose child frames observations read. Undefined without - * a URL, which is no policy at all. + * The site of the base URL, as `siteOf` reads it: whose child frames + * observations read. Undefined without a URL, which is no policy at all. */ readonly site: string | undefined; readonly environment: 'test' | 'staging' | 'production'; @@ -242,10 +241,10 @@ export function resolveTargetApp(targetName: string, app: TargetAppDeclaration, }; } -/** What `prepare` and `init` receive about the target's app: its site policy and what a device launches. */ +/** What `prepare` and `init` receive about the target's app: its origin and site policy, and what a device launches. */ export function engineAppInfo(app: ResolvedApp): EngineAppInfo { - const { site, bundleId, appPath, launchArguments, permissions } = app; - return obj({ site, bundleId, appPath, launchArguments, permissions }); + const { base, site, bundleId, appPath, launchArguments, permissions } = app; + return obj({ origin: base?.origin, site, bundleId, appPath, launchArguments, permissions }); } /** diff --git a/packages/e2e/src/engine/index.ts b/packages/e2e/src/engine/index.ts index 00350d73a0..a6a42bce7a 100644 --- a/packages/e2e/src/engine/index.ts +++ b/packages/e2e/src/engine/index.ts @@ -139,16 +139,21 @@ export interface EngineAppCheckInfo { /** * The app the harness resolved from the target's declaration, handed to - * `prepare` and `init`: the site policy for the decisions only a surface can - * make (which nested documents enter an observation, which requests carry - * injected credentials), and what a device launches. The URL itself stays - * with the harness: a surface never learns where the app is, and opens what - * `session.open` is given. + * `prepare` and `init`: the origin and site policy for the decisions only a + * surface can make (which requests carry injected credentials, which nested + * documents enter an observation), and what a device launches. Navigation + * stays with the harness: a surface opens what `session.open` is given. */ export interface EngineAppInfo { + /** + * The origin of the app's `url` on the run's port (`scheme://host:port`, as + * `URL.origin` serializes it): where credentials an engine injects into + * requests (headers, basic auth) go by default. Absent for an app without + * a URL. + */ + readonly origin?: string; /** * The site of the app's `url`, its registrable domain as `siteOf` reads it: - * where the app's secrets, headers, and basic-auth credentials may go, and * whose child frames an observation reads; `sameSite` applies it. Absent * for an app without a URL, which is no policy at all. */ @@ -487,7 +492,7 @@ export interface EngineInitInfo { * `process.cwd()`, which an in-process run does not change. */ readonly projectRoot: string; - /** The app the target declares: the site policy of its URL, and what a device launches. */ + /** The app the target declares: the origin and site policy of its URL, and what a device launches. */ readonly app: EngineAppInfo; /** * This worker's environment: the run's, plus what this target's `prepare` diff --git a/packages/e2e/src/internal/urls.ts b/packages/e2e/src/internal/urls.ts index 724116ee31..1c14be2fa4 100644 --- a/packages/e2e/src/internal/urls.ts +++ b/packages/e2e/src/internal/urls.ts @@ -176,10 +176,9 @@ export function siteOf(hostname: string): string { } /** - * True when a URL's host is on `site` as `siteOf` reads it. This is the one - * rule for where the app's secrets, headers, and basic-auth credentials may - * go and which child frames an observation reads; an unparseable URL is off - * every site. + * True when a URL's host is on `site` as `siteOf` reads it: the rule for + * which child frames an observation reads. An unparseable URL is off every + * site. */ export function sameSite(url: string | URL, site: string): boolean { try { diff --git a/packages/e2e/tests/integration/engine-contract.test.ts b/packages/e2e/tests/integration/engine-contract.test.ts index d6fae21d14..a572def888 100644 --- a/packages/e2e/tests/integration/engine-contract.test.ts +++ b/packages/e2e/tests/integration/engine-contract.test.ts @@ -57,6 +57,7 @@ describe('runner <-> engine contract', () => { expect(fake.inits).toHaveLength(1); const info = fake.inits[0]!; expect(info.app.site).toBe('127.0.0.1'); + expect(info.app.origin).toBe(new URL(APP_URL).origin); expect((info.app as { baseUrl?: unknown }).baseUrl).toBeUndefined(); expect((info as { testIdAttribute?: unknown }).testIdAttribute).toBeUndefined(); expect(info.headed).toBe(false); diff --git a/packages/e2e/tests/unit/app-ports.test.ts b/packages/e2e/tests/unit/app-ports.test.ts index b478422c4f..db8089526b 100644 --- a/packages/e2e/tests/unit/app-ports.test.ts +++ b/packages/e2e/tests/unit/app-ports.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from 'vitest'; +import { engineAppInfo } from '../../src/config/app.ts'; import { assignPorts, resolveConfig, type PortAssignments } from '../../src/config/resolve.ts'; import { defineEngine } from '../../src/engine/index.ts'; import type { TargetApp } from '../../src/types.ts'; @@ -49,6 +50,8 @@ describe('an app URL on a free port', () => { expect(app.base).toEqual({ href: 'http://127.0.0.1:4321/shop/', origin: 'http://127.0.0.1:4321', basePath: '/shop/' }); expect(app.portRequest).toEqual({ host: '127.0.0.1', port: 4321 }); expect(app.readyUrl).toBe('http://127.0.0.1:4321/shop/'); + // Engines scope injected credentials to the origin on the assigned port, never the declared :0. + expect(engineAppInfo(app).origin).toBe('http://127.0.0.1:4321'); expect(app.identity).toBe(pending.targets[0]!.app.identity); expect(app.identity).toBe('http://127.0.0.1:0/shop/'); expect(assigned.configDigest).toBe(pending.configDigest); diff --git a/packages/web/package.json b/packages/web/package.json index 15d38d6fa5..1d48c585ee 100644 --- a/packages/web/package.json +++ b/packages/web/package.json @@ -58,7 +58,7 @@ "playwright-core": "1.65.0" }, "peerDependencies": { - "e2e": ">=0.22.1 <1" + "e2e": ">=0.23.1 <1" }, "devDependencies": { "@napi-rs/image": "1.16.0", diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index b358b0cdcc..0e99a0ee81 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -73,7 +73,7 @@ export interface RouteContinueOverrides { url?: string; /** Request method. */ method?: string; - /** Replaces every request header; `undefined` drops one, and the configured `headers` for the app's site are added on top. */ + /** Replaces every request header; `undefined` drops one, and the configured `headers` for an allowed origin are added on top. */ headers?: Record; /** Request body. */ postData?: string; @@ -269,7 +269,7 @@ export interface Browser extends Expectable { ): Promise; /** Removes matching attempt-scoped routes. */ unroute(pattern: string | RegExp): Promise; - /** Removes all routes registered by this browser fixture, preserving configured site headers. */ + /** Removes all routes registered by this browser fixture, preserving the configured headers. */ unrouteAll(): Promise; /** Waits for a matching response. */ waitForResponse( @@ -577,9 +577,9 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine fetch: async (...args: unknown[]) => { requireNoArguments('route.fetch', args); return surface.guard(context.operation(), 'route.fetch', async currentOperation => { - const site = surface.siteHeaders(request.url()); + const configured = surface.originHeaders(request.url()); const response = await route.fetch({ - headers: { ...lowercaseNames(request.headers()), ...site }, + headers: { ...lowercaseNames(request.headers()), ...configured }, timeout: currentOperation.timeoutMs, maxRedirects: 0, }); @@ -602,13 +602,13 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine continue: async (overrides) => { const { headers, ...decision } = parseContinue(overrides, request.url(), context.app.resolveUrl); // `continue` skips every route registered before this one, the - // site-header route included, so it merges those headers itself. - const site = surface.siteHeaders(decision.url ?? request.url()); + // origin-header route included, so it merges those headers itself. + const configured = surface.originHeaders(decision.url ?? request.url()); await decideWith('continue', () => route.continue({ ...decision, - ...(headers === undefined && site === undefined + ...(headers === undefined && configured === undefined ? {} - : { headers: { ...lowercaseNames(headers ?? request.headers()), ...site } }), + : { headers: { ...lowercaseNames(headers ?? request.headers()), ...configured } }), })); }, fallback: async (...args: unknown[]) => { diff --git a/packages/web/src/engine.ts b/packages/web/src/engine.ts index f6b2983444..ef8c1689c9 100644 --- a/packages/web/src/engine.ts +++ b/packages/web/src/engine.ts @@ -24,7 +24,7 @@ import { PlaywrightSurface, type WebOptions } from './surface.ts'; import { createBrowserFixture } from './browser.ts'; import { validateInitScripts } from './init-scripts.ts'; import { MEDIA_KEYS, mediaProblem } from './media.ts'; -import { FIELD_VALUE_CONTROL, headerProblem } from './protected-app.ts'; +import { FIELD_VALUE_CONTROL, headerProblem, originProblem } from './protected-app.ts'; import { validatePermissions } from './permissions.ts'; import type { BrowserName } from './browser-connection.ts'; @@ -83,6 +83,7 @@ export function web(options: WebOptions = {}): EngineHandle { ); } if (options.headers !== undefined) validateHeaders(options.headers); + if (options.headerOrigins !== undefined) validateHeaderOrigins(options.headerOrigins, options.headers); if (options.basicAuth !== undefined) validateBasicAuth(options.basicAuth); if (options.testIdAttribute !== undefined) validateTestIdAttribute(options.testIdAttribute); if (options.userAgent !== undefined) validateUserAgent(options.userAgent, options.headers); @@ -168,6 +169,7 @@ const WEB_OPTION_KEYS: readonly string[] = Object.keys({ screencast: true, connect: true, headers: true, + headerOrigins: true, basicAuth: true, testIdAttribute: true, userAgent: true, @@ -257,8 +259,8 @@ function validateBasicAuth(basicAuth: unknown): void { if (!isRecord(basicAuth)) { throw new ConfigurationError('INVALID_CONFIG', 'web({ basicAuth }) must be an object with username and password'); } - rejectUnknownKeys('web({ basicAuth })', basicAuth, ['username', 'password']); - const { username, password } = basicAuth; + rejectUnknownKeys('web({ basicAuth })', basicAuth, ['username', 'password', 'origins']); + const { username, password, origins } = basicAuth; if (typeof username !== 'string' || username === '') { throw new ConfigurationError('INVALID_CONFIG', 'web({ basicAuth }) requires a non-empty username string'); } @@ -268,12 +270,32 @@ function validateBasicAuth(basicAuth: unknown): void { if (typeof password !== 'string' && !isSecret(password)) { throw new ConfigurationError('INVALID_CONFIG', 'web({ basicAuth }) requires a password string or secrets.get(name)'); } + if (origins !== undefined) validateOrigins('web({ basicAuth: { origins } })', origins); +} + +/** Refuses extra header origins without headers to send them, and any entry that is not an exact origin. */ +function validateHeaderOrigins(headerOrigins: unknown, headers: Readonly> | undefined): void { + if (headers === undefined) { + throw new ConfigurationError('INVALID_CONFIG', 'web({ headerOrigins }) requires headers: it lists more origins that receive them'); + } + validateOrigins('web({ headerOrigins })', headerOrigins); +} + +/** Refuses a list of credential origins that is not an array of exact `http:` or `https:` origins, naming the entry. */ +function validateOrigins(label: string, origins: unknown): void { + if (!Array.isArray(origins)) { + throw new ConfigurationError('INVALID_CONFIG', `${label} must be an array of origins such as "https://preview.example.com"`); + } + for (const [index, origin] of origins.entries()) { + const problem = originProblem(origin); + if (problem !== undefined) throw new ConfigurationError('INVALID_CONFIG', `${label}[${index}] ${problem}`); + } } /** * Refuses a user agent the browser could not send (not a string, empty, or * carrying a control character) and one a `user-agent` header would override - * on the app's site while `navigator.userAgent` kept reporting it. + * on the app's origin while `navigator.userAgent` kept reporting it. */ function validateUserAgent(userAgent: unknown, headers: Readonly> | undefined): void { if (typeof userAgent !== 'string' || userAgent === '') { @@ -289,7 +311,7 @@ function validateUserAgent(userAgent: unknown, headers: Readonly> | undefined): void { diff --git a/packages/web/src/protected-app.ts b/packages/web/src/protected-app.ts index 4a48157dc1..71b35e4936 100644 --- a/packages/web/src/protected-app.ts +++ b/packages/web/src/protected-app.ts @@ -1,18 +1,20 @@ /** - * Protected-preview access, scoped to the app's site: the configured headers - * ride only requests bound for the site, and basic-auth credentials answer - * a challenge wherever one is issued. The surface calls these on every - * context it creates; nothing here holds state. + * Protected-preview access, scoped to exact origins: the app's own and the + * extras the options list. The configured headers ride only requests bound + * for one of them, and basic-auth credentials answer only a challenge one of + * them issues. The surface calls these on every context it creates; nothing + * here holds state. */ import type { BrowserContext } from 'playwright-core'; -import { sameSite, type ResolveSecretOptions, type Secret } from 'e2e/engine'; +import type { ResolveSecretOptions, Secret } from 'e2e/engine'; import type { WebBasicAuth } from './surface.ts'; -/** The credentials Playwright answers an HTTP authentication challenge with. */ +/** The credentials Playwright answers an HTTP authentication challenge from `origin` with. */ export interface PlaywrightHttpCredential { readonly username: string; readonly password: string; + readonly origin: string; } /** An HTTP header field name: one or more `token` characters (RFC 9110). */ @@ -41,36 +43,52 @@ export function lowercaseNames(headers: Readonly>): Reado } /** - * The configured headers a request to `url` carries: all of them for the - * app's site, none for any other site or when there is no site policy. + * The origin of `url` as `URL.origin` serializes it (scheme and host + * lowercased, a default port dropped), or `undefined` when it does not parse. */ -export function siteHeadersFor( +function originOf(url: string | URL): string | undefined { + try { + return (typeof url === 'string' ? new URL(url) : url).origin; + } catch { + return undefined; + } +} + +/** + * The configured headers a request to `url` carries: all of them when its + * origin is one of `origins`, none otherwise. + */ +export function originHeadersFor( url: string | URL, - site: string | undefined, + origins: ReadonlySet, headers: Readonly> | undefined, ): Readonly> | undefined { - if (headers === undefined || site === undefined) return undefined; - return sameSite(url, site) ? headers : undefined; + if (headers === undefined) return undefined; + const origin = originOf(url); + return origin !== undefined && origins.has(origin) ? headers : undefined; } /** - * Adds the configured headers to every request bound for the app's site, + * Adds the configured headers to every request bound for one of `origins`, * via a context route that falls back to the network. A request for any - * other site is not routed at all; without a site there is no policy and - * nothing is routed. Registered before any test route, so it runs last: a - * test route's `fallback` reaches it, and a `continue`, which skips it, - * merges the same headers itself (`siteHeadersFor`). Nothing awaits a route - * handler, so a fallback that fails (the page closed under the request) is - * dropped rather than left to surface as an unhandled rejection. + * other origin is not routed at all. Redirect hops are never routed either: + * Playwright carries a routed request's headers onto them, whatever origin + * they name, and a request that started elsewhere stays without them. + * Registered before any test route, so it + * runs last: a test route's `fallback` reaches it, and a `continue`, which + * skips it, merges the same headers itself (`originHeadersFor`). Nothing + * awaits a route handler, so a fallback that fails (the page closed under + * the request) is dropped rather than left to surface as an unhandled + * rejection. */ -export async function installSiteHeaders( +export async function installOriginHeaders( context: BrowserContext, - site: string | undefined, + origins: ReadonlySet, headers: Readonly> | undefined, ): Promise { - if (headers === undefined || site === undefined) return; + if (headers === undefined || origins.size === 0) return; await context.route( - (url) => siteHeadersFor(url, site, headers) !== undefined, + (url) => originHeadersFor(url, origins, headers) !== undefined, async (route) => { await route.fallback({ headers: { ...route.request().headers(), ...headers } }).catch(() => undefined); }, @@ -78,21 +96,22 @@ export async function installSiteHeaders( } /** - * The basic-auth credentials a context answers a challenge with, as - * Playwright's own `httpCredentials` does: on a 401 from any origin. A site - * cannot be enumerated into the exact origins Playwright scopes by, and a - * challenge is answered only where one is issued. A `Secret` password - * resolves through the attempt, which registers the value for redaction, and - * the `Authorization` credential Playwright sends with it too: a page that + * The basic-auth credentials a context answers a challenge with: one + * Playwright `httpCredentials` entry per origin in `origins`, so a `401` + * from any other origin goes unanswered. A `Secret` password resolves + * through the attempt, which registers the value for redaction, and the + * `Authorization` credential Playwright sends with it too: a page that * echoes its request headers shows that, not the password. */ export async function httpCredentials( basicAuth: WebBasicAuth, + origins: ReadonlySet, resolveSecret: (secret: Secret, options?: ResolveSecretOptions) => Promise, -): Promise { +): Promise { const { username, password } = basicAuth; - if (typeof password === 'string') return { username, password }; - return { username, password: await resolveSecret(password, { derived: (plaintext) => basicCredentials(username, plaintext) }) }; + const plaintext = + typeof password === 'string' ? password : await resolveSecret(password, { derived: (value) => basicCredentials(username, value) }); + return [...origins].map((origin) => ({ username, password: plaintext, origin })); } /** @@ -105,3 +124,30 @@ function basicCredentials(username: string, password: string): string[] { const unpadded = encoded.replace(/={1,2}$/, ''); return unpadded === encoded ? [encoded] : [encoded, unpadded]; } + +/** + * The exact origins a credential goes to: the app's own, when the runner + * reports one, and each extra the options list, normalized as `URL.origin` + * serializes it. Config load has checked every extra is an origin. + */ +export function credentialOrigins(appOrigin: string | undefined, extras: readonly string[] | undefined): ReadonlySet { + return new Set([...(appOrigin === undefined ? [] : [appOrigin]), ...(extras ?? []).map((origin) => new URL(origin).origin)]); +} + +/** + * Why `value` is not an origin a credential can be scoped to, or `undefined` + * when it is: an `http:` or `https:` URL with no user info, path, query, or + * fragment (`https://api.example.com`, a trailing `/` allowed). + */ +export function originProblem(value: unknown): string | undefined { + const expected = 'must be an origin such as "https://preview.example.com": an http or https URL with no path, query, or fragment'; + if (typeof value !== 'string') return `${expected}, got ${typeof value}`; + let url: URL; + try { + url = new URL(value); + } catch { + return `${expected}, got "${value}"`; + } + const bare = url.username === '' && url.password === '' && url.pathname === '/' && url.search === '' && url.hash === '' && !value.endsWith('?') && !value.endsWith('#'); + return (url.protocol === 'http:' || url.protocol === 'https:') && bare ? undefined : `${expected}, got "${value}"`; +} diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index b9a2d71594..fff9a4ebf1 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -11,6 +11,7 @@ import { mkdirSync } from 'node:fs'; import path from 'node:path'; import type { Browser, BrowserContext, ElementHandle, Frame, FrameLocator, Locator, Page, Request, Route } from 'playwright-core'; import { + ConfigurationError, Deadline, EngineError, obj, @@ -62,7 +63,7 @@ import { ConfiguredInitScripts, type WebInitScript } from './init-scripts.ts'; import type { WebMedia } from './media.ts'; import { SECURE_FIELD_SELECTOR, type RawNodeData } from './read-node.ts'; import { readSelector, takeReadsFunction } from './read-selector.ts'; -import { httpCredentials, installSiteHeaders, lowercaseNames, siteHeadersFor } from './protected-app.ts'; +import { credentialOrigins, httpCredentials, installOriginHeaders, lowercaseNames, originHeadersFor } from './protected-app.ts'; import { RefRegistry } from './refs.ts'; import { cancelled, @@ -139,7 +140,7 @@ export interface WebConnectOptions { readonly reconnectEndpoint?: (signal: AbortSignal) => string | Promise; } -/** HTTP basic authentication the browser answers a `401` challenge with. */ +/** HTTP basic authentication the browser answers a `401` challenge from the app's origin with. */ export interface WebBasicAuth { /** The user name; `:` is not allowed in one (RFC 7617). */ readonly username: string; @@ -149,6 +150,12 @@ export interface WebBasicAuth { * like any configured secret. */ readonly password: string | Secret; + /** + * More origins whose challenge the browser answers, beyond the app's own + * (`app.url`'s scheme, host, and port): an API host or a redirect target + * behind the same gate. Exact origins, such as `https://api.example.com`. + */ + readonly origins?: readonly string[]; } /** The engine's screencast of the page: the frame size and the JPEG quality of the frames it encodes. */ @@ -192,11 +199,12 @@ export interface WebOptions { */ readonly connect?: WebConnectOptions; /** - * HTTP headers added to every request the browser sends to an allowed - * origin: a preview-protection bypass token, a tunnel's interstitial skip. - * Requests to any other origin (a CDN, an analytics endpoint, an identity - * provider) never carry them, so a header that is a secret stays with the - * app it unlocks. Names are case-insensitive; a header the page already + * HTTP headers added to every request the browser sends to the app's + * origin (`app.url`'s scheme, host, and port) or one in `headerOrigins`: + * a preview-protection bypass token, a tunnel's interstitial skip. + * Requests to any other origin (another port on the same host, a sibling + * subdomain, a CDN, an identity provider) never carry them, so a header + * that is a secret stays with the app it unlocks. Names are case-insensitive; a header the page already * sends under the same name is replaced. Applies to every path onto the * page, deterministic and agent-driven alike. Injecting headers routes * every request of the attempt, which turns the browser's HTTP cache off @@ -204,11 +212,17 @@ export interface WebOptions { * page it controlled would reach the gate bare). */ readonly headers?: Readonly>; + /** + * More origins that receive `headers`, beyond the app's own: an API host + * or a redirect target behind the same gate. Exact origins, such as + * `https://api.example.com`; requires `headers`. + */ + readonly headerOrigins?: readonly string[]; /** * HTTP basic authentication for a staging app behind a browser challenge. - * The browser answers a `401` with these credentials wherever one is - * issued, as Playwright's own `httpCredentials` does. Applies to every path - * onto the page. + * The browser answers a `401` from the app's origin, or one in + * `basicAuth.origins`, with these credentials, and no other. Applies to + * every path onto the page. */ readonly basicAuth?: WebBasicAuth; /** @@ -288,6 +302,9 @@ export class PlaywrightSurface { private readonly screencast: WebScreencastOptions; /** Injected request headers, names lowercased so they replace the browser's own of the same name. */ private readonly headers: Readonly> | undefined; + private readonly headerOrigins: readonly string[] | undefined; + /** Where `headers` go: the app's origin and each of `headerOrigins`, set at `init`. */ + private headerScope: ReadonlySet = new Set(); private readonly basicAuth: WebBasicAuth | undefined; private readonly testIdAttribute: string; private readonly userAgent: string | undefined; @@ -324,6 +341,7 @@ export class PlaywrightSurface { this.viewport = options.viewport === undefined ? DEFAULT_VIEWPORT : options.viewport; this.screencast = options.screencast ?? {}; this.headers = options.headers === undefined ? undefined : lowercaseNames(options.headers); + this.headerOrigins = options.headerOrigins; this.basicAuth = options.basicAuth; this.testIdAttribute = options.testIdAttribute ?? DEFAULT_TEST_ID_ATTRIBUTE; this.userAgent = options.userAgent; @@ -368,7 +386,12 @@ export class PlaywrightSurface { /** Provisions the shared browser once per worker: a local launch, or a CDP attach. */ async init(info: EngineInitInfo): Promise { + // A runner older than the peer floor passes no origin; fail rather than send the credentials nowhere. + if (info.app.origin === undefined && (this.headers !== undefined || this.basicAuth !== undefined)) { + throw new ConfigurationError('INVALID_CONFIG', 'web({ headers, basicAuth }) needs e2e 0.23.1 or later, which tells the engine the app\'s origin; update e2e'); + } this.app = info.app; + this.headerScope = credentialOrigins(info.app.origin, this.headerOrigins); this.projectRoot = info.projectRoot; this.headed = info.headed; this.leases?.init(info); @@ -484,7 +507,11 @@ export class PlaywrightSurface { const credentials = basicAuth === undefined ? undefined - : await raceAbort(() => httpCredentials(basicAuth, context.resolveSecret), context.signal, 'resolving the basic-auth password'); + : await raceAbort( + () => httpCredentials(basicAuth, credentialOrigins(this.app.origin, basicAuth.origins), context.resolveSecret), + context.signal, + 'resolving the basic-auth password', + ); const persistent = await this.persistentBinding(context); this.artifactsDir = context.artifactsDir; this.artifactCounter = 0; @@ -525,7 +552,7 @@ export class PlaywrightSurface { ownNavigation: () => this.ownNavigations > 0, testPage: () => this.openPage(), }); - await installSiteHeaders(target, this.app.site, this.headers); + await installOriginHeaders(target, this.headerScope, this.headers); if (granted.length > 0) await target.grantPermissions(granted); for (const stored of routes) await target.route(stored.predicate, stored.handler); }, @@ -607,9 +634,9 @@ export class PlaywrightSurface { await context.route(predicate, handler); } - /** The configured headers a request to `url` carries, lowercased; `undefined` off the app's site. */ - siteHeaders(url: string): Readonly> | undefined { - return siteHeadersFor(url, this.app.site, this.headers); + /** The configured headers a request to `url` carries, lowercased; `undefined` off the app's origin and `headerOrigins`. */ + originHeaders(url: string): Readonly> | undefined { + return originHeadersFor(url, this.headerScope, this.headers); } /** Resolves a file a test names against the project root, as config paths do, never `process.cwd()`. */ diff --git a/packages/web/tests/helpers/fixture-app.ts b/packages/web/tests/helpers/fixture-app.ts index 183ab3462a..ed3c59f4d0 100644 --- a/packages/web/tests/helpers/fixture-app.ts +++ b/packages/web/tests/helpers/fixture-app.ts @@ -416,6 +416,11 @@ export function startFixtureApp(): Promise { response.end("self.addEventListener('fetch', () => {});"); return; } + if (url.pathname === '/redirect') { + response.writeHead(302, { location: url.searchParams.get('to') ?? '/' }); + response.end(); + return; + } if (url.pathname === '/headers') { const value = request.headers['x-fixture-header']; response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' }); diff --git a/packages/web/tests/integration/protected-app.test.ts b/packages/web/tests/integration/protected-app.test.ts index d5a5544e62..4afc75847a 100644 --- a/packages/web/tests/integration/protected-app.test.ts +++ b/packages/web/tests/integration/protected-app.test.ts @@ -1,10 +1,11 @@ /** * Reaching an app behind a gate: configured request headers reach the app's - * site on every context the attempt opens, and never another site; basic-auth - * credentials answer a challenge wherever one is issued, as Playwright's own - * do. Driven through the engine hooks, as the attempt executor drives them; a - * second fixture instance reached as `localhost` rather than `127.0.0.1` - * stands in for a third-party site. + * origin on every context the attempt opens, and basic-auth credentials + * answer only its challenge; neither reaches another origin unless the + * options list it. Driven through the engine hooks, as the attempt executor + * drives them; a second fixture instance stands in for another origin, on + * the same host under another port, and as `localhost` rather than + * `127.0.0.1` for a third-party site. */ import { mkdtempSync, rmSync } from 'node:fs'; @@ -36,7 +37,7 @@ async function boot( runId: 'run-protected', targetName: 'web', projectRoot: process.cwd(), - app: { site: new URL(app.url).hostname }, + app: { origin: new URL(app.url).origin, site: new URL(app.url).hostname }, env: {}, headed: false, workerSlot: 0, @@ -64,13 +65,16 @@ async function headingAt(engine: EngineHandle, attemptId: string, url: string): describe('web({ headers, basicAuth })', () => { let app: FixtureApp; let other: FixtureApp; + /** The second server under the app's host name: the same site, another origin. */ + let otherPort: string; + /** The second server under another host name: `localhost` is a site of its own, `127.0.0.1` another. */ + let otherSite: string; let artifactsDir: string; beforeAll(async () => { [app, other] = await Promise.all([startFixtureApp(), startFixtureApp()]); - // The same loopback server under another host name: `localhost` is a - // site of its own, `127.0.0.1` another. - other = { ...other, url: other.url.replace('127.0.0.1', 'localhost') }; + otherPort = other.url; + otherSite = other.url.replace('127.0.0.1', 'localhost'); artifactsDir = mkdtempSync(path.join(tmpdir(), 'e2e-protected-')); }); @@ -79,13 +83,14 @@ describe('web({ headers, basicAuth })', () => { rmSync(artifactsDir, { recursive: true, force: true }); }); - it('sends the headers to the app\'s site only, on every context of the attempt', async () => { + it('sends the headers to the app\'s origin only, on every context of the attempt', async () => { const engine = web({ headers: { 'X-Fixture-Header': 'let-me-in' } }); try { await boot(engine, app, artifactsDir, 'h1'); expect(await headingAt(engine, 'h1', `${app.url}/headers`)).toBe('let-me-in'); - // A third-party site gets the request without them. - expect(await headingAt(engine, 'h1', `${other.url}/headers`)).toBe('none'); + // Another port on the same host, and a third-party site, get the request without them. + expect(await headingAt(engine, 'h1', `${otherPort}/headers`)).toBe('none'); + expect(await headingAt(engine, 'h1', `${otherSite}/headers`)).toBe('none'); // A state reset replaces the context; the headers come along. await engine.session!.reset!(operation('h1')); expect(await headingAt(engine, 'h1', `${app.url}/headers`)).toBe('let-me-in'); @@ -94,6 +99,32 @@ describe('web({ headers, basicAuth })', () => { } }); + it('sends the headers to an origin headerOrigins lists, and no other', async () => { + const engine = web({ headers: { 'x-fixture-header': 'listed' }, headerOrigins: [`${otherPort}/`] }); + try { + await boot(engine, app, artifactsDir, 'h3'); + expect(await headingAt(engine, 'h3', `${otherPort}/headers`)).toBe('listed'); + expect(await headingAt(engine, 'h3', `${otherSite}/headers`)).toBe('none'); + } finally { + await shutdown(engine); + } + }); + + it('follows the origin a request starts on through its redirects', async () => { + const engine = web({ headers: { 'x-fixture-header': 'rides-redirects' } }); + try { + await boot(engine, app, artifactsDir, 'h4'); + // Playwright reapplies a routed request's headers to its redirects without routing them: + // they reach whatever origin a redirect names, and a redirect into the app's origin gets none. + const toOther = `${app.url}/redirect?to=${encodeURIComponent(`${otherSite}/headers`)}`; + expect(await headingAt(engine, 'h4', toOther)).toBe('rides-redirects'); + const toApp = `${otherSite}/redirect?to=${encodeURIComponent(`${app.url}/headers`)}`; + expect(await headingAt(engine, 'h4', toApp)).toBe('none'); + } finally { + await shutdown(engine); + } + }); + it('keeps the headers on a request an attempt route lets through', async () => { const engine = web({ headers: { 'x-fixture-header': 'through-the-route' } }); try { @@ -137,7 +168,7 @@ describe('web({ headers, basicAuth })', () => { } }); - it('answers a basic-auth challenge wherever one is issued', async () => { + it('answers a basic-auth challenge from the app\'s origin only', async () => { const unauthenticated = web(); try { await boot(unauthenticated, app, artifactsDir, 'b0'); @@ -149,7 +180,23 @@ describe('web({ headers, basicAuth })', () => { try { await boot(engine, app, artifactsDir, 'b1'); expect(await headingAt(engine, 'b1', `${app.url}/protected`)).toBe('Protected'); - expect(await headingAt(engine, 'b1', `${other.url}/protected`)).toBe('Protected'); + expect(await headingAt(engine, 'b1', `${otherPort}/protected`)).toBe('Unauthorized'); + expect(await headingAt(engine, 'b1', `${otherSite}/protected`)).toBe('Unauthorized'); + // The challenge comes from the origin a redirect lands on, so redirects do not carry the credential. + const toOther = `${app.url}/redirect?to=${encodeURIComponent(`${otherPort}/protected`)}`; + expect(await headingAt(engine, 'b1', toOther)).toBe('Unauthorized'); + } finally { + await shutdown(engine); + } + }); + + it('answers a challenge from an origin basicAuth.origins lists, and no other', async () => { + const engine = web({ basicAuth: { ...PROTECTED_CREDENTIAL, origins: [otherPort] } }); + try { + await boot(engine, app, artifactsDir, 'b2'); + expect(await headingAt(engine, 'b2', `${app.url}/protected`)).toBe('Protected'); + expect(await headingAt(engine, 'b2', `${otherPort}/protected`)).toBe('Protected'); + expect(await headingAt(engine, 'b2', `${otherSite}/protected`)).toBe('Unauthorized'); } finally { await shutdown(engine); } diff --git a/packages/web/tests/integration/routes.test.ts b/packages/web/tests/integration/routes.test.ts index 48f2c6b650..836c7cee34 100644 --- a/packages/web/tests/integration/routes.test.ts +++ b/packages/web/tests/integration/routes.test.ts @@ -1,7 +1,7 @@ /** * Route decisions against a server that counts what reaches it: `continue` * goes to the network past every other route and carries the configured - * site headers itself, `fallback` hands the request to the route before it, + * headers itself, `fallback` hands the request to the route before it, * the overrides each decision implements reach the wire, and an option it * does not implement fails the next step instead of being dropped. Also the * one call beside routing that takes a URL the same way: a relative cookie @@ -88,7 +88,7 @@ describe('browser.route decisions', () => { const attached: string[] = []; let server: Server; let origin: string; - let otherSite: string; + let otherOrigin: string; let page: Page; let browser: Browser; @@ -105,10 +105,10 @@ describe('browser.route decisions', () => { const started = await startCountingServer(hits); server = started.server; origin = `http://127.0.0.1:${started.port}`; - // The same server under another host name: `localhost` is a site of its own. - otherSite = `http://localhost:${started.port}`; + // The same server under another host name: another origin. + otherOrigin = `http://localhost:${started.port}`; writeFileSync(path.join(projectRoot, 'quote.json'), '{"cents":4200}\n'); - await surface.init({ runId: 'routes', targetName: 'web', projectRoot, app: { site: '127.0.0.1' }, + await surface.init({ runId: 'routes', targetName: 'web', projectRoot, app: { origin, site: '127.0.0.1' }, env: {}, headed: false, workerSlot: 0, signal, log: () => undefined }); }); @@ -119,7 +119,7 @@ describe('browser.route decisions', () => { page = await surface.ensurePage(); await page.goto(`${origin}/`); browser = createBrowserFixture(surface, { - app: { site: '127.0.0.1', resolveUrl }, + app: { origin, site: '127.0.0.1', resolveUrl }, operation: (timeoutMs = 5_000) => ({ signal, timeoutMs, runId: 'routes', attemptId: 'routes', origin: 'test' }), timeouts: { test: 5_000, assertion: 5_000 }, expectable: (target: object) => target, @@ -166,7 +166,7 @@ describe('browser.route decisions', () => { /** Waits for the latched route failure the next step reports. */ const nextStepFailure = (): Promise => browser.url().then(() => undefined, (error: unknown) => error); - it('fetches upstream once, keeps site headers, then fulfills an amended response', async () => { + it('fetches upstream once, keeps configured headers, then fulfills an amended response', async () => { await browser.route('**/echo', async route => { const upstream = await route.fetch(); expect(upstream.status).toBe(200); @@ -340,7 +340,7 @@ describe('browser.route decisions', () => { expect((page as unknown as EventEmitter).listenerCount('download')).toBe(listeners); }); - it('clears every test route, keeps configured site headers, and can register again', async () => { + it('clears every test route, keeps configured headers, and can register again', async () => { await browser.route('**/api/**', route => route.fulfill({ body: 'mock-api' })); await browser.route(/\/echo$/, route => route.fulfill({ json: { intercepted: true } })); expect(await fetchText(`${origin}/api/quote`)).toBe('mock-api'); @@ -400,13 +400,13 @@ describe('browser.route decisions', () => { it.each([ ['continue', (route: WebRoute) => route.continue()], ['fallback', (route: WebRoute) => route.fallback()], - ])('keeps the configured site header through %s', async (_name, decide) => { + ])('keeps the configured header through %s', async (_name, decide) => { await browser.route('**/echo', decide); const echo = await fetchEcho(`${origin}/echo`); expect(echo.headers['x-gate']).toBe('open-sesame'); }); - it('continue replaces the request headers and adds the site header on top', async () => { + it('continue replaces the request headers and adds the configured header on top', async () => { await browser.route('**/echo', (route) => route.continue({ headers: { ...route.request.headers, 'X-Added': 'yes', 'X-GATE': 'forged' } })); const echo = await fetchEcho(`${origin}/echo`); @@ -440,8 +440,8 @@ describe('browser.route decisions', () => { expect(hits.get('/echo')).toBe(1); }); - it('continue to another site leaves the site header behind', async () => { - await browser.route('**/api/quote', (route) => route.continue({ url: `${otherSite}/echo` })); + it('continue to another origin leaves the configured header behind', async () => { + await browser.route('**/api/quote', (route) => route.continue({ url: `${otherOrigin}/echo` })); const echo = await fetchEcho(`${origin}/api/quote`); expect(echo.headers.host).toBe(`localhost:${new URL(origin).port}`); expect(echo.headers['x-gate']).toBeUndefined(); diff --git a/packages/web/tests/unit/protected-app-options.test.ts b/packages/web/tests/unit/protected-app-options.test.ts index 60eb7e572b..d8b94713ab 100644 --- a/packages/web/tests/unit/protected-app-options.test.ts +++ b/packages/web/tests/unit/protected-app-options.test.ts @@ -1,5 +1,5 @@ /** - * The `headers`, `basicAuth`, `testIdAttribute`, `userAgent`, `locale`, `timezoneId`, `colorScheme`, `reducedMotion`, `initScripts`, and `screencast` options are checked at + * The `headers`, `headerOrigins`, `basicAuth`, `testIdAttribute`, `userAgent`, `locale`, `timezoneId`, `colorScheme`, `reducedMotion`, `initScripts`, and `screencast` options are checked at * config load, so a header the browser could never send or an attribute no * element could carry fails the run before a browser launches. What the * browser does with valid ones is in tests/integration. @@ -8,7 +8,7 @@ import { describe, expect, it } from 'vitest'; import { secrets } from 'e2e'; import { web, type WebOptions } from '../../src/index.ts'; -import { httpCredentials } from '../../src/protected-app.ts'; +import { credentialOrigins, httpCredentials } from '../../src/protected-app.ts'; describe('web({ headers })', () => { it('rejects a header name outside the token grammar as INVALID_CONFIG', () => { @@ -34,6 +34,34 @@ describe('web({ headers })', () => { }); }); +describe('web({ headerOrigins })', () => { + const headers = { 'x-preview': 'token' }; + + it('accepts exact http and https origins, a trailing slash included', () => { + expect(() => web({ headers, headerOrigins: ['https://api.example.com', 'http://127.0.0.1:4000/'] })).not.toThrow(); + }); + + it('rejects an entry that is not an origin, naming it', () => { + const cases: [unknown, RegExp][] = [ + ['https://api.example.com/v1', /\[0\] must be an origin.*got "https:\/\/api\.example\.com\/v1"/], + ['https://api.example.com?x=1', /\[0\] must be an origin/], + ['https://api.example.com#top', /\[0\] must be an origin/], + ['https://user:pass@api.example.com', /\[0\] must be an origin/], + ['ftp://api.example.com', /\[0\] must be an origin/], + ['api.example.com', /\[0\] must be an origin/], + [3, /\[0\] must be an origin.*got number/], + ]; + for (const [origin, message] of cases) { + expect(() => web({ headers, headerOrigins: [origin as string] })).toThrow(expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringMatching(message) })); + } + expect(() => web({ headers, headerOrigins: 'https://api.example.com' as unknown as string[] })).toThrowError(/must be an array of origins/); + }); + + it('rejects headerOrigins without headers to send', () => { + expect(() => web({ headerOrigins: ['https://api.example.com'] })).toThrowError(/requires headers/); + }); +}); + describe('web({ basicAuth })', () => { it('accepts a username and password', () => { expect(() => web({ basicAuth: { username: 'ada', password: '' } })).not.toThrow(); @@ -64,6 +92,13 @@ describe('web({ basicAuth })', () => { web({ basicAuth: { username: 'ada', password: { name: 'stagingPassword' } as unknown as string } }), ).toThrowError(/password string or secrets\.get\(name\)/); }); + + it('accepts exact extra origins and rejects anything else, naming the entry', () => { + expect(() => web({ basicAuth: { username: 'ada', password: 'x', origins: ['https://api.example.com'] } })).not.toThrow(); + expect(() => web({ basicAuth: { username: 'ada', password: 'x', origins: ['https://api.example.com', 'https://example.com/login'] } })).toThrowError( + /web\(\{ basicAuth: \{ origins \} \}\)\[1\] must be an origin/, + ); + }); }); describe('web({ testIdAttribute })', () => { @@ -190,7 +225,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, testIdAttribute, userAgent, locale, timezoneId, colorScheme, reducedMotion, initScripts'), + refused('web() has unknown key "launchOptions"; expected one of browser, viewport, screencast, connect, headers, headerOrigins, basicAuth, testIdAttribute, userAgent, locale, timezoneId, colorScheme, reducedMotion, initScripts'), ); }); @@ -209,23 +244,29 @@ describe('web() option keys', () => { }); }); -describe('basic-auth credentials from a secret', () => { - it('registers the Authorization credential the password becomes, padded and not, for redaction', async () => { +describe('basic-auth credentials', () => { + const app = 'http://127.0.0.1:3000'; + + it('scopes one entry to each origin: the app\'s, then the extras, normalized', async () => { + const origins = credentialOrigins(app, ['https://API.example.com:443/', 'http://127.0.0.1:3000']); + const credentials = await httpCredentials({ username: 'ada', password: 'plain-value' }, origins, async () => { + throw new Error('not a secret'); + }); + expect(credentials).toEqual([ + { username: 'ada', password: 'plain-value', origin: app }, + { username: 'ada', password: 'plain-value', origin: 'https://api.example.com' }, + ]); + }); + + it('registers the Authorization credential a secret password becomes, padded and not, for redaction', async () => { const asked: { name: string; derived: readonly string[] }[] = []; - const credentials = await httpCredentials({ username: 'ada', password: secrets.get('stagingPassword') }, async (secret, options) => { + const credentials = await httpCredentials({ username: 'ada', password: secrets.get('stagingPassword') }, credentialOrigins(app, undefined), async (secret, options) => { asked.push({ name: secret.name, derived: (await options?.derived?.('pa55word!')) ?? [] }); return 'pa55word!'; }); - expect(credentials).toEqual({ username: 'ada', password: 'pa55word!' }); + expect(credentials).toEqual([{ username: 'ada', password: 'pa55word!', origin: app }]); const encoded = Buffer.from('ada:pa55word!').toString('base64'); expect(encoded.endsWith('=')).toBe(true); expect(asked).toEqual([{ name: 'stagingPassword', derived: [encoded, encoded.replace(/=+$/, '')] }]); }); - - it('resolves nothing for a plain string password', async () => { - const credentials = await httpCredentials({ username: 'ada', password: 'plain-value' }, async () => { - throw new Error('not a secret'); - }); - expect(credentials).toEqual({ username: 'ada', password: 'plain-value' }); - }); }); diff --git a/packages/web/tests/unit/surface-lifecycle.test.ts b/packages/web/tests/unit/surface-lifecycle.test.ts index e8610cfcfb..210bfecc2a 100644 --- a/packages/web/tests/unit/surface-lifecycle.test.ts +++ b/packages/web/tests/unit/surface-lifecycle.test.ts @@ -156,9 +156,18 @@ it('rejects a focus read from a context replaced before typing dispatches', asyn expect(type).not.toHaveBeenCalled(); }); +it('refuses headers or basicAuth from a runner that passes no app origin', async () => { + for (const options of [{ headers: { 'x-gate': 'on' } }, { basicAuth: { username: 'ada', password: 'pw' } }]) { + const unscoped = new PlaywrightSurface(options); + await expect( + unscoped.init({ runId: 'run', targetName: 'web', projectRoot: process.cwd(), app: {}, env: {}, headed: false, workerSlot: 0, signal: new AbortController().signal, log: () => undefined }), + ).rejects.toMatchObject({ code: 'INVALID_CONFIG' }); + } +}); + it('opens no session for an attempt the runner gave up on while its basic-auth password resolved', async () => { const protectedSurface = new PlaywrightSurface({ basicAuth: { username: 'ada', password: secrets.get('stagingPassword') } }); - await protectedSurface.init({ runId: 'run', targetName: 'web', projectRoot: process.cwd(), app: {}, env: {}, headed: false, workerSlot: 0, signal: new AbortController().signal, log: () => undefined }); + await protectedSurface.init({ runId: 'run', targetName: 'web', projectRoot: process.cwd(), app: { origin: 'http://127.0.0.1:3000' }, env: {}, headed: false, workerSlot: 0, signal: new AbortController().signal, log: () => undefined }); try { let resolvePassword!: (value: string) => void; const slow = new Promise((resolve) => { resolvePassword = resolve; }); @@ -170,7 +179,7 @@ it('opens no session for an attempt the runner gave up on while its basic-auth p resolvePassword('late-password'); await new Promise((resolve) => setImmediate(resolve)); await protectedSurface.startAttempt({ attemptId: 'next', artifactsDir, signal: new AbortController().signal, resolveSecret: async () => 'next-password', ...ignoreTrace }); - expect(vi.mocked(browser.newContext).mock.lastCall?.[0]).toMatchObject({ httpCredentials: { username: 'ada', password: 'next-password' } }); + expect(vi.mocked(browser.newContext).mock.lastCall?.[0]).toMatchObject({ httpCredentials: [{ username: 'ada', password: 'next-password', origin: 'http://127.0.0.1:3000' }] }); } finally { await protectedSurface.dispose(cleanup()); } diff --git a/plugins/e2e/skills/e2e/references/setup.md b/plugins/e2e/skills/e2e/references/setup.md index 1ebb47cf51..a4a22cab51 100644 --- a/plugins/e2e/skills/e2e/references/setup.md +++ b/plugins/e2e/skills/e2e/references/setup.md @@ -215,8 +215,8 @@ start a script that brings them up and serves the app. | `browser` | `'chromium'` (default), `'firefox'`, `'webkit'`, or a `BrowserProvider` leasing hosted browsers over CDP (`kernel()` from `@e2e-dev/kernel`, `smol()` from `@e2e-dev/smol`, `lightpanda()` from `@e2e-dev/lightpanda`, `testmuBrowsers()` from `@e2e-dev/testmu/web`, `e2bBrowsers()` from `@e2e-dev/e2b/web`, or your own), which implies chromium and excludes `connect`. Scope `'worker'` (default): one browser per worker slot from `prepare` to `finish`; `'attempt'`: one per attempt, with `reconnectEndpoint`'s limits (`lightpanda()` and `testmuBrowsers()` are worker scope only). | | `viewport` | `{ width, height }`, default 1280x720; `null` follows the browser window (hosted live view, headed run). On a headed hosted browser (Kernel) use `null` and size the service's screen; a fixed size gives a smaller, unmaximized window. | | `connect` | `{ cdpEndpoint }` attaches to a remote Chromium over CDP; `cdpEndpoint` is required, and both it and `reconnectEndpoint` are resolvers `(signal) => url`, not strings, else `INVALID_CONFIG` at load. With `reconnectEndpoint` it rides one persistent default context, needs a fresh browser from `cdpEndpoint` every attempt, and reconnects only to the original browser and page. | -| `headers` | Sent to the app's site only (Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; disables the browser HTTP cache and service workers. | -| `basicAuth` | `{ username, password }` for a `401` challenge; `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | +| `headers` | Sent to the app's origin only (scheme, host, and port of `app.url`; Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; `headerOrigins: ['https://api.example.com']` adds exact origins. A request keeps them through its redirects, to any origin. Disables the browser HTTP cache and service workers. | +| `basicAuth` | `{ username, password, origins? }` for a `401` challenge from the app's origin, or one `origins` lists (a redirect to `www` or `https:` is another origin); `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | | `userAgent` | The `User-Agent` every attempt sends and `navigator.userAgent` reports. | | `locale`, `timezoneId` | The language (`'de-DE'`: `navigator.language`, `Intl`, `Accept-Language`) and IANA time zone (`'Europe/Berlin'`) every attempt runs in. | | `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. | diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index ba9d4e1172..1b89acfcd4 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -503,11 +503,11 @@ the app opens itself (`target="_blank"`, `window.open`) is not followed: `fulfill({ status?, headers?, contentType?, json | body | path })` (`body` a string or bytes; several cookies as one `\n`-joined `set-cookie`), `continue({ url?, method?, headers?, postData? })` (straight to the - network; a header set to `undefined` is dropped, configured site headers + network; a header set to `undefined` is dropped, configured origin headers still added), `fallback()` (the route registered before it), or `abort()`; none or two fails the next step with `ACTION_FAILED`, an unsupported option with `INVALID_ARGUMENT`. -- `unrouteAll()` removes every route; configured site headers stay. +- `unrouteAll()` removes every route; configured headers stay. - `waitForResponse(pattern, { timeout? })`: resolves once the headers arrive, with `{ url, status, headers, body(), json(), text() }`; the body readers wait for the body (up to the action timeout) and reject with diff --git a/skills/e2e/references/setup.md b/skills/e2e/references/setup.md index 1ebb47cf51..a4a22cab51 100644 --- a/skills/e2e/references/setup.md +++ b/skills/e2e/references/setup.md @@ -215,8 +215,8 @@ start a script that brings them up and serves the app. | `browser` | `'chromium'` (default), `'firefox'`, `'webkit'`, or a `BrowserProvider` leasing hosted browsers over CDP (`kernel()` from `@e2e-dev/kernel`, `smol()` from `@e2e-dev/smol`, `lightpanda()` from `@e2e-dev/lightpanda`, `testmuBrowsers()` from `@e2e-dev/testmu/web`, `e2bBrowsers()` from `@e2e-dev/e2b/web`, or your own), which implies chromium and excludes `connect`. Scope `'worker'` (default): one browser per worker slot from `prepare` to `finish`; `'attempt'`: one per attempt, with `reconnectEndpoint`'s limits (`lightpanda()` and `testmuBrowsers()` are worker scope only). | | `viewport` | `{ width, height }`, default 1280x720; `null` follows the browser window (hosted live view, headed run). On a headed hosted browser (Kernel) use `null` and size the service's screen; a fixed size gives a smaller, unmaximized window. | | `connect` | `{ cdpEndpoint }` attaches to a remote Chromium over CDP; `cdpEndpoint` is required, and both it and `reconnectEndpoint` are resolvers `(signal) => url`, not strings, else `INVALID_CONFIG` at load. With `reconnectEndpoint` it rides one persistent default context, needs a fresh browser from `cdpEndpoint` every attempt, and reconnects only to the original browser and page. | -| `headers` | Sent to the app's site only (Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; disables the browser HTTP cache and service workers. | -| `basicAuth` | `{ username, password }` for a `401` challenge; `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | +| `headers` | Sent to the app's origin only (scheme, host, and port of `app.url`; Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; `headerOrigins: ['https://api.example.com']` adds exact origins. A request keeps them through its redirects, to any origin. Disables the browser HTTP cache and service workers. | +| `basicAuth` | `{ username, password, origins? }` for a `401` challenge from the app's origin, or one `origins` lists (a redirect to `www` or `https:` is another origin); `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | | `userAgent` | The `User-Agent` every attempt sends and `navigator.userAgent` reports. | | `locale`, `timezoneId` | The language (`'de-DE'`: `navigator.language`, `Intl`, `Accept-Language`) and IANA time zone (`'Europe/Berlin'`) every attempt runs in. | | `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. | diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index ba9d4e1172..1b89acfcd4 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -503,11 +503,11 @@ the app opens itself (`target="_blank"`, `window.open`) is not followed: `fulfill({ status?, headers?, contentType?, json | body | path })` (`body` a string or bytes; several cookies as one `\n`-joined `set-cookie`), `continue({ url?, method?, headers?, postData? })` (straight to the - network; a header set to `undefined` is dropped, configured site headers + network; a header set to `undefined` is dropped, configured origin headers still added), `fallback()` (the route registered before it), or `abort()`; none or two fails the next step with `ACTION_FAILED`, an unsupported option with `INVALID_ARGUMENT`. -- `unrouteAll()` removes every route; configured site headers stay. +- `unrouteAll()` removes every route; configured headers stay. - `waitForResponse(pattern, { timeout? })`: resolves once the headers arrive, with `{ url, status, headers, body(), json(), text() }`; the body readers wait for the body (up to the action timeout) and reject with From 45063ddccb30b3640472eccc9a64acc8371f846c Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Mon, 26 Oct 2026 15:23:48 +0100 Subject: [PATCH 2/4] test(web): set fixture redirects from the test, not the request URL --- packages/web/tests/helpers/fixture-app.ts | 9 +++++++-- packages/web/tests/integration/protected-app.test.ts | 12 ++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/web/tests/helpers/fixture-app.ts b/packages/web/tests/helpers/fixture-app.ts index ed3c59f4d0..2c9edd5093 100644 --- a/packages/web/tests/helpers/fixture-app.ts +++ b/packages/web/tests/helpers/fixture-app.ts @@ -396,11 +396,14 @@ const SLOW_RESPONSE_MS = 5_000; export interface FixtureApp { readonly url: string; + /** Redirect responses by path: a request for a key answers `302` to its value. */ + readonly redirects: Map; close(): Promise; } /** Starts the fixture on an ephemeral port and resolves once it is listening. */ export function startFixtureApp(): Promise { + const redirects = new Map(); const server: Server = createServer((request, response) => { const url = new URL(request.url ?? '/', 'http://fixture.test'); if (url.pathname === '/slow') { @@ -416,8 +419,9 @@ export function startFixtureApp(): Promise { response.end("self.addEventListener('fetch', () => {});"); return; } - if (url.pathname === '/redirect') { - response.writeHead(302, { location: url.searchParams.get('to') ?? '/' }); + const redirect = redirects.get(url.pathname); + if (redirect !== undefined) { + response.writeHead(302, { location: redirect }); response.end(); return; } @@ -455,6 +459,7 @@ export function startFixtureApp(): Promise { const { port } = server.address() as AddressInfo; resolve({ url: `http://127.0.0.1:${String(port)}`, + redirects, close: () => new Promise((done) => { server.close(() => done()); diff --git a/packages/web/tests/integration/protected-app.test.ts b/packages/web/tests/integration/protected-app.test.ts index 4afc75847a..74a5a4fc1e 100644 --- a/packages/web/tests/integration/protected-app.test.ts +++ b/packages/web/tests/integration/protected-app.test.ts @@ -116,10 +116,10 @@ describe('web({ headers, basicAuth })', () => { await boot(engine, app, artifactsDir, 'h4'); // Playwright reapplies a routed request's headers to its redirects without routing them: // they reach whatever origin a redirect names, and a redirect into the app's origin gets none. - const toOther = `${app.url}/redirect?to=${encodeURIComponent(`${otherSite}/headers`)}`; - expect(await headingAt(engine, 'h4', toOther)).toBe('rides-redirects'); - const toApp = `${otherSite}/redirect?to=${encodeURIComponent(`${app.url}/headers`)}`; - expect(await headingAt(engine, 'h4', toApp)).toBe('none'); + app.redirects.set('/to-other-headers', `${otherSite}/headers`); + expect(await headingAt(engine, 'h4', `${app.url}/to-other-headers`)).toBe('rides-redirects'); + other.redirects.set('/to-app-headers', `${app.url}/headers`); + expect(await headingAt(engine, 'h4', `${otherSite}/to-app-headers`)).toBe('none'); } finally { await shutdown(engine); } @@ -183,8 +183,8 @@ describe('web({ headers, basicAuth })', () => { expect(await headingAt(engine, 'b1', `${otherPort}/protected`)).toBe('Unauthorized'); expect(await headingAt(engine, 'b1', `${otherSite}/protected`)).toBe('Unauthorized'); // The challenge comes from the origin a redirect lands on, so redirects do not carry the credential. - const toOther = `${app.url}/redirect?to=${encodeURIComponent(`${otherPort}/protected`)}`; - expect(await headingAt(engine, 'b1', toOther)).toBe('Unauthorized'); + app.redirects.set('/to-other-protected', `${otherPort}/protected`); + expect(await headingAt(engine, 'b1', `${app.url}/to-other-protected`)).toBe('Unauthorized'); } finally { await shutdown(engine); } From 601e0e3f7b46e82e8ccf23467f228c56e7901529 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 6 Nov 2026 11:29:09 +0100 Subject: [PATCH 3/4] fix(web): one credentialOrigins list, and WebKit basic auth on default ports headerOrigins and basicAuth.origins become one credentialOrigins option that covers both. WebKit never matches a scoped credential to an origin on a default port or with an IPv6 host, so there basic auth goes unscoped, as Playwright's default. A wildcard host or port 0 in the list is INVALID_CONFIG, since it would match nothing. e2e doctor leaves the origin out until a free port is assigned. Docs no longer claim headers skip other origins: a redirect keeps them. --- .changeset/engine-app-origin.md | 2 +- .changeset/web-credential-origins.md | 2 +- SECURITY.md | 9 ++- docs/migrate/playwright.mdx | 4 +- docs/reference/engine.mdx | 3 +- docs/reference/security.mdx | 18 +++-- docs/reference/web.mdx | 73 +++++++++++-------- docs/security.mdx | 8 +- docs/web.mdx | 7 +- packages/e2e/src/config/app.ts | 12 ++- packages/e2e/src/engine/index.ts | 2 +- packages/e2e/tests/unit/app-ports.test.ts | 1 + packages/web/src/browser.ts | 6 +- packages/web/src/engine.ts | 34 ++++----- packages/web/src/protected-app.ts | 52 ++++++++----- packages/web/src/route-options.ts | 2 +- packages/web/src/surface.ts | 63 ++++++++-------- .../tests/integration/protected-app.test.ts | 23 +++--- packages/web/tests/integration/routes.test.ts | 48 ++++++++++-- .../tests/unit/protected-app-options.test.ts | 53 +++++++++----- plugins/e2e/skills/e2e/references/setup.md | 4 +- .../skills/e2e/references/writing-tests.md | 5 +- skills/e2e/references/setup.md | 4 +- skills/e2e/references/writing-tests.md | 5 +- 24 files changed, 267 insertions(+), 173 deletions(-) diff --git a/.changeset/engine-app-origin.md b/.changeset/engine-app-origin.md index b2f8c06258..0c9d7bc9e2 100644 --- a/.changeset/engine-app-origin.md +++ b/.changeset/engine-app-origin.md @@ -2,4 +2,4 @@ "e2e": patch --- -Engines receive the app's origin as `EngineAppInfo.origin` in `prepare` and `init`, on the run's port when `app.url` asks for a free one, so an engine can scope a credential it injects to the exact origin. +Engines receive the app's origin as `EngineAppInfo.origin` in `prepare` and `init`, on the run's port when `app.url` asks for a free one (and left out until the run assigns it), so an engine can scope a credential it injects to the exact origin. diff --git a/.changeset/web-credential-origins.md b/.changeset/web-credential-origins.md index 76612c3dd6..eae5d5809c 100644 --- a/.changeset/web-credential-origins.md +++ b/.changeset/web-credential-origins.md @@ -4,4 +4,4 @@ **Breaking:** `web({ headers })` and `web({ basicAuth })` go only to the app's origin, the scheme, host, and port of `app.url`. Before, `headers` went to every host on the app's site (another port on the same host, sibling subdomains, every host under a shared domain such as `vercel.app`), and `basicAuth` answered a `401` from any origin, so a third-party origin the app embeds could collect the credential. -To migrate, list each other origin that needs the credential: `headerOrigins: ['https://api.example.com']` for `headers`, and `basicAuth: { username, password, origins: ['https://api.example.com'] }` for basic auth. An app whose `app.url` redirects to another origin (`http:` to `https:`, the apex to `www`) needs the origin it lands on listed, or set `app.url` to it. `headers` still ride a request's own redirects to any origin, as before. Requires `e2e` 0.23.1 or later. +To migrate, list each other origin that needs the credentials in `credentialOrigins: ['https://api.example.com']`; it covers both. An app whose `app.url` redirects to another origin (`http:` to `https:`, the apex to `www`) needs the origin it lands on listed, or set `app.url` to it. `headers` still ride a request's own redirects to any origin, as before. WebKit can't scope basic auth to an origin on a default port or an IPv6 host, so there it still answers any origin. Update `e2e` with this release: the engine needs the app's origin from the runner. diff --git a/SECURITY.md b/SECURITY.md index e61ebcee4d..1767303406 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -76,9 +76,12 @@ 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. -Two things still key on the site of the target's `url`, its registrable -domain: the browser engine's `headers` reach the site and no other host, and -child frames off the site are dropped from observations. +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 +`credentialOrigins` lists. `headers` stay on a request's redirects to any +origin, and WebKit answers a basic-auth challenge from any origin when an +allowed origin is on a default port or an IPv6 host. ## Telemetry and outbound traffic diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx index 1c030d32c5..bd1c2381ab 100644 --- a/docs/migrate/playwright.mdx +++ b/docs/migrate/playwright.mdx @@ -68,8 +68,8 @@ A Playwright key such as `testDir`, `baseURL`, `use`, `webServer`, or | --- | --- | --- | | `use.viewport`, `use.browserName` | `web({ viewport, browser })` | renamed | | `use.testIdAttribute` | `web({ testIdAttribute })` | renamed | -| `use.httpCredentials` | `web({ basicAuth })`, answered for the app's origin only; `basicAuth.origins` adds more | renamed | -| `use.extraHTTPHeaders` | `web({ headers })`, sent to the app's origin only | renamed | +| `use.httpCredentials` | `web({ basicAuth })`, answered for the app's origin only; `credentialOrigins` adds more | renamed | +| `use.extraHTTPHeaders` | `web({ headers })`, sent to the app's origin only; `credentialOrigins` adds more | renamed | | `chromium.connectOverCDP(url)` | `web({ connect: { cdpEndpoint: () => url } })`, chromium only | renamed | | `use.connectOptions` (`wsEndpoint`) | `web({ connect })` attaches over CDP only | missing | | `retries`, `workers`, `timeout` | the same names at the top level. `workers` takes an integer from 1 to 1024, not `'50%'`; `retries` stops at 10. The defaults differ, see [below](#defaults-that-differ) | renamed | diff --git a/docs/reference/engine.mdx b/docs/reference/engine.mdx index 59ea73346e..c46e83358b 100644 --- a/docs/reference/engine.mdx +++ b/docs/reference/engine.mdx @@ -1362,7 +1362,8 @@ export interface EngineAppInfo { /** * The app URL's origin on the run's port (`scheme://host:port`, as * `URL.origin` serializes it): where injected request credentials go. - * Absent when the app has no URL. + * Absent when the app has no URL, and for a free port the run has not + * assigned (`e2e doctor`). */ readonly origin?: string; /** diff --git a/docs/reference/security.mdx b/docs/reference/security.mdx index 6b200caa0f..54289b26df 100644 --- a/docs/reference/security.mdx +++ b/docs/reference/security.mdx @@ -104,12 +104,13 @@ and use the step's secrets there. ### Request credentials The browser engine sends configured request credentials only to exact -origins: the scheme, host, and port of `app.url`, plus the extras you list. +origins: the scheme, host, and port of `app.url`, plus the extras +`credentialOrigins` lists. -| Option | Goes to | Extra origins | -| --- | --- | --- | -| `headers` | Every request to an allowed origin | `headerOrigins` | -| `basicAuth` | The answer to a `401` challenge from an allowed origin | `basicAuth.origins` | +| Option | Goes to | +| --- | --- | +| `headers` | Every request that starts at an allowed origin | +| `basicAuth` | The answer to a `401` challenge from an allowed origin | - Another port on the same host, a subdomain, and a sibling host under a shared domain such as `vercel.app` are other origins. They get no @@ -120,9 +121,12 @@ origins: the scheme, host, and port of `app.url`, plus the extras you list. - `basicAuth` answers the origin that sends the `401`. A redirect to another origin, such as `http:` to `https:` or the apex to `www`, gets no answer unless you list the origin it lands on. +- On WebKit, `basicAuth` answers a `401` from any origin when an allowed + origin is on its scheme's default port (`https://staging.example.com`) or + has an IPv6 host. WebKit can't scope a credential to such an origin. - An extra is an `http:` or `https:` origin with no path, query, or - fragment, such as `https://api.example.com`. Anything else is - `INVALID_CONFIG` at config load. + fragment, such as `https://api.example.com`. Anything else, a `*` in the + host, and port `0` are `INVALID_CONFIG` at config load. ### Site check diff --git a/docs/reference/web.mdx b/docs/reference/web.mdx index 00e5675628..49183115d9 100644 --- a/docs/reference/web.mdx +++ b/docs/reference/web.mdx @@ -52,8 +52,8 @@ web({ viewport: { width: 390, height: 844 }, locale: 'de-DE' }); | [`screencast`](#screencast) | `WebScreencastOptions` | the viewport's size | | [`connect`](#connect) | `WebConnectOptions` | launches locally | | [`headers`](#headers) | `Record` | - | -| [`headerOrigins`](#headerorigins) | `string[]` | - | | [`basicAuth`](#basicauth) | `WebBasicAuth` | - | +| [`credentialOrigins`](#credentialorigins) | `string[]` | - | | [`testIdAttribute`](#testidattribute) | `string` | `'data-testid'` | | [`userAgent`](#useragent) | `string` | the browser's own | | [`locale`](#locale) | `string` | the browser's own | @@ -241,8 +241,10 @@ session state capture and restore. `app.clearState` fails with #### `headers` -Headers added to every request to the app's origin: the scheme, host, and -port of `app.url`. Another port, a subdomain, and any other host get none. +Headers added to every request that starts at the app's origin: the scheme, +host, and port of `app.url`. A request that starts at another port, a +subdomain, or any other host gets none. A redirect keeps the headers its +request started with, to any origin. ```ts web({ headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' } }); @@ -263,33 +265,16 @@ web({ headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' } }); blocks service workers. -#### `headerOrigins` - -More origins that receive [`headers`](#headers), beyond the app's own, such -as an API on another host behind the same gate. - -```ts -web({ - headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' }, - headerOrigins: ['https://api.staging.example.com'], -}); -``` - -| Throws | When | -| --- | --- | -| `INVALID_CONFIG` | No `headers`, or an entry that is not an `http:` or `https:` origin with no path, query, or fragment. | - #### `basicAuth` HTTP basic authentication. The browser answers a `401` challenge from the app's origin with these credentials. A challenge from any other origin goes -unanswered unless `origins` lists it. +unanswered unless [`credentialOrigins`](#credentialorigins) lists it. ```ts import { secrets } from 'e2e'; web({ basicAuth: { username: 'staging', password: secrets.get('staging-password') } }); -web({ basicAuth: { username: 'staging', password: secrets.get('staging-password'), origins: ['https://api.staging.example.com'] } }); ``` A `secrets.get(name)` password resolves when each attempt starts and is @@ -303,14 +288,19 @@ export interface WebBasicAuth { readonly username: string; /** The password, or `secrets.get(name)` for one in `config.secrets`. */ readonly password: string | Secret; - /** More origins whose challenge the browser answers, such as `https://api.example.com`. */ - readonly origins?: readonly string[]; } ``` | Throws | When | | --- | --- | -| `INVALID_CONFIG` | A `:` in the user name, an unknown key, or an `origins` entry that is not an `http:` or `https:` origin with no path, query, or fragment. | +| `INVALID_CONFIG` | A `:` in the user name, or an unknown key. | + + +WebKit can't scope a credential to an origin on its scheme's default port +(`https://staging.example.com`) or with an IPv6 host. When the app's origin +or one in `credentialOrigins` is such an origin, WebKit answers a `401` from +any origin, as Playwright does by default. + The secret protection is text only. A page that renders the password on @@ -318,6 +308,25 @@ screen is not masked in screenshots or model pixels ([Security rules](/reference/security#secrets-in-engine-options)). +#### `credentialOrigins` + +More origins that receive [`headers`](#headers) and +[`basicAuth`](#basicauth), beyond the app's own, such as an API on another +host behind the same gate. + +```ts +web({ + headers: { 'x-preview-token': process.env.PREVIEW_TOKEN ?? '' }, + credentialOrigins: ['https://api.staging.example.com'], +}); +``` + +List each origin exactly. A `*` in the host and port `0` match no request. + +| Throws | When | +| --- | --- | +| `INVALID_CONFIG` | No `headers` or `basicAuth`, an entry that is not an `http:` or `https:` origin with no path, query, or fragment, a `*` in the host, or port `0`. | + #### `testIdAttribute` The attribute that carries an element's test id: what the `testId` query @@ -1104,21 +1113,25 @@ export interface WebOptions { */ readonly connect?: WebConnectOptions; /** - * Headers added to every request to the app's origin (the scheme, host, - * and port of `app.url`) or one in `headerOrigins`. Useful for - * preview-protection tokens. Other origins never receive them. + * Headers added to every request that starts at the app's origin (the + * scheme, host, and port of `app.url`) or one in `credentialOrigins`. + * Useful for preview-protection tokens. A request that starts at another + * origin goes without them; a redirect keeps them, to any origin. * Names are case-insensitive and replace existing headers of the same name. * This enables request routing, disables the browser's HTTP cache, and * blocks service workers. */ readonly headers?: Readonly>; - /** More origins that receive `headers`, such as `https://api.example.com`; requires `headers`. */ - readonly headerOrigins?: readonly string[]; /** * HTTP basic authentication. The browser answers a `401` challenge from the - * app's origin, or one in `basicAuth.origins`, with these credentials. + * app's origin, or one in `credentialOrigins`, with these credentials. */ readonly basicAuth?: WebBasicAuth; + /** + * More origins that receive `headers` and `basicAuth`, such as + * `https://api.example.com`; requires `headers` or `basicAuth`. + */ + readonly credentialOrigins?: readonly string[]; /** * The attribute that carries an element's test id: what the `testId` query * (`screen.getByTestId`) resolves and what `SemanticNode.testId` reports. diff --git a/docs/security.mdx b/docs/security.mdx index 4b8b32549c..2b76cec8fc 100644 --- a/docs/security.mdx +++ b/docs/security.mdx @@ -35,9 +35,11 @@ Redaction matches strings, and screenshots mask secure fields only: pass through. Assert the outcome, not the secret. - **Values not filled as a secret.** Only a configured secret's value is redacted. A value a sign-in sets in a cookie is not. -- **Request credentials.** `headers` and `basicAuth` go on every request to - the app's origin and each origin you list, even one a third-party page - starts. `headers` also stay on that request's redirects to any origin. +- **Request credentials.** `headers` go on every request that starts at the + app's origin or one you list, even one a third-party page starts, and stay + on its redirects to any origin. `basicAuth` answers a `401` from those + origins, and from any origin on WebKit when one of those is on a default + port. - **Committed recordings.** Cache entries store typed values verbatim, except secret fills. They aren't signed and replay with your permissions, so review them as you would test code. diff --git a/docs/web.mdx b/docs/web.mdx index 323a69a97e..717598981b 100644 --- a/docs/web.mdx +++ b/docs/web.mdx @@ -134,7 +134,7 @@ app: { The browser sends `headers` only to the origin of `app.url`: its scheme, host, and port. To send them to another origin, such as an API host behind -the same gate, list it in `headerOrigins`. See +the same gate, list it in `credentialOrigins`. See [request credentials](/reference/security#request-credentials). For ngrok, use `'ngrok-skip-browser-warning': '1'`. `app.identity` keeps the cache identity stable when the preview URL changes. @@ -146,8 +146,9 @@ workers. Use `basicAuth` for HTTP basic authentication. The browser answers a `401` challenge from the origin of `app.url`, and from each origin in -`basicAuth.origins`. Declare the password under `secrets` and pass -`secrets.get(name)`: +`credentialOrigins`. WebKit answers any origin when one of those is on a +default port, such as an `https://` URL with no port. Declare the password +under `secrets` and pass `secrets.get(name)`: ```ts title="e2e.config.ts" import type { E2EConfig } from 'e2e'; diff --git a/packages/e2e/src/config/app.ts b/packages/e2e/src/config/app.ts index cc0763621a..cc1c52cc6a 100644 --- a/packages/e2e/src/config/app.ts +++ b/packages/e2e/src/config/app.ts @@ -241,10 +241,16 @@ export function resolveTargetApp(targetName: string, app: TargetAppDeclaration, }; } -/** What `prepare` and `init` receive about the target's app: its origin and site policy, and what a device launches. */ +/** + * What `prepare` and `init` receive about the target's app: its origin and + * site policy, and what a device launches. A free port the run has not + * assigned yet (`e2e doctor` assigns none) leaves the origin out rather than + * report it on port `0`. + */ export function engineAppInfo(app: ResolvedApp): EngineAppInfo { - const { base, site, bundleId, appPath, launchArguments, permissions } = app; - return obj({ origin: base?.origin, site, bundleId, appPath, launchArguments, permissions }); + const { base, portRequest, site, bundleId, appPath, launchArguments, permissions } = app; + const unassigned = portRequest !== undefined && portRequest.port === undefined; + return obj({ origin: unassigned ? undefined : base?.origin, site, bundleId, appPath, launchArguments, permissions }); } /** diff --git a/packages/e2e/src/engine/index.ts b/packages/e2e/src/engine/index.ts index a6a42bce7a..6b5e5b6f55 100644 --- a/packages/e2e/src/engine/index.ts +++ b/packages/e2e/src/engine/index.ts @@ -149,7 +149,7 @@ export interface EngineAppInfo { * The origin of the app's `url` on the run's port (`scheme://host:port`, as * `URL.origin` serializes it): where credentials an engine injects into * requests (headers, basic auth) go by default. Absent for an app without - * a URL. + * a URL, and for a free port the run has not assigned (`e2e doctor`). */ readonly origin?: string; /** diff --git a/packages/e2e/tests/unit/app-ports.test.ts b/packages/e2e/tests/unit/app-ports.test.ts index db8089526b..b168b76fc2 100644 --- a/packages/e2e/tests/unit/app-ports.test.ts +++ b/packages/e2e/tests/unit/app-ports.test.ts @@ -52,6 +52,7 @@ describe('an app URL on a free port', () => { expect(app.readyUrl).toBe('http://127.0.0.1:4321/shop/'); // Engines scope injected credentials to the origin on the assigned port, never the declared :0. expect(engineAppInfo(app).origin).toBe('http://127.0.0.1:4321'); + expect(engineAppInfo(pending.targets[0]!.app).origin).toBeUndefined(); expect(app.identity).toBe(pending.targets[0]!.app.identity); expect(app.identity).toBe('http://127.0.0.1:0/shop/'); expect(assigned.configDigest).toBe(pending.configDigest); diff --git a/packages/web/src/browser.ts b/packages/web/src/browser.ts index 0e99a0ee81..beb9b28899 100644 --- a/packages/web/src/browser.ts +++ b/packages/web/src/browser.ts @@ -577,7 +577,7 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine fetch: async (...args: unknown[]) => { requireNoArguments('route.fetch', args); return surface.guard(context.operation(), 'route.fetch', async currentOperation => { - const configured = surface.originHeaders(request.url()); + const configured = surface.configuredHeaders(request.url()); const response = await route.fetch({ headers: { ...lowercaseNames(request.headers()), ...configured }, timeout: currentOperation.timeoutMs, @@ -602,8 +602,8 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine continue: async (overrides) => { const { headers, ...decision } = parseContinue(overrides, request.url(), context.app.resolveUrl); // `continue` skips every route registered before this one, the - // origin-header route included, so it merges those headers itself. - const configured = surface.originHeaders(decision.url ?? request.url()); + // configured-headers route included, so it merges those headers itself. + const configured = surface.configuredHeaders(decision.url ?? request.url()); await decideWith('continue', () => route.continue({ ...decision, ...(headers === undefined && configured === undefined diff --git a/packages/web/src/engine.ts b/packages/web/src/engine.ts index ef8c1689c9..7c060671fb 100644 --- a/packages/web/src/engine.ts +++ b/packages/web/src/engine.ts @@ -83,8 +83,8 @@ export function web(options: WebOptions = {}): EngineHandle { ); } if (options.headers !== undefined) validateHeaders(options.headers); - if (options.headerOrigins !== undefined) validateHeaderOrigins(options.headerOrigins, options.headers); if (options.basicAuth !== undefined) validateBasicAuth(options.basicAuth); + if (options.credentialOrigins !== undefined) validateCredentialOrigins(options); if (options.testIdAttribute !== undefined) validateTestIdAttribute(options.testIdAttribute); if (options.userAgent !== undefined) validateUserAgent(options.userAgent, options.headers); if (options.locale !== undefined) validateLocale(options.locale, options.headers); @@ -169,8 +169,8 @@ const WEB_OPTION_KEYS: readonly string[] = Object.keys({ screencast: true, connect: true, headers: true, - headerOrigins: true, basicAuth: true, + credentialOrigins: true, testIdAttribute: true, userAgent: true, locale: true, @@ -259,8 +259,8 @@ function validateBasicAuth(basicAuth: unknown): void { if (!isRecord(basicAuth)) { throw new ConfigurationError('INVALID_CONFIG', 'web({ basicAuth }) must be an object with username and password'); } - rejectUnknownKeys('web({ basicAuth })', basicAuth, ['username', 'password', 'origins']); - const { username, password, origins } = basicAuth; + rejectUnknownKeys('web({ basicAuth })', basicAuth, ['username', 'password']); + const { username, password } = basicAuth; if (typeof username !== 'string' || username === '') { throw new ConfigurationError('INVALID_CONFIG', 'web({ basicAuth }) requires a non-empty username string'); } @@ -270,25 +270,23 @@ function validateBasicAuth(basicAuth: unknown): void { if (typeof password !== 'string' && !isSecret(password)) { throw new ConfigurationError('INVALID_CONFIG', 'web({ basicAuth }) requires a password string or secrets.get(name)'); } - if (origins !== undefined) validateOrigins('web({ basicAuth: { origins } })', origins); } -/** Refuses extra header origins without headers to send them, and any entry that is not an exact origin. */ -function validateHeaderOrigins(headerOrigins: unknown, headers: Readonly> | undefined): void { - if (headers === undefined) { - throw new ConfigurationError('INVALID_CONFIG', 'web({ headerOrigins }) requires headers: it lists more origins that receive them'); +/** + * Refuses extra credential origins without headers or basic auth to send + * them, a list that is not an array, and any entry that is not an exact + * `http:` or `https:` origin, naming the entry. + */ +function validateCredentialOrigins({ credentialOrigins, headers, basicAuth }: WebOptions): void { + if (headers === undefined && basicAuth === undefined) { + throw new ConfigurationError('INVALID_CONFIG', 'web({ credentialOrigins }) requires headers or basicAuth: it lists more origins that receive them'); } - validateOrigins('web({ headerOrigins })', headerOrigins); -} - -/** Refuses a list of credential origins that is not an array of exact `http:` or `https:` origins, naming the entry. */ -function validateOrigins(label: string, origins: unknown): void { - if (!Array.isArray(origins)) { - throw new ConfigurationError('INVALID_CONFIG', `${label} must be an array of origins such as "https://preview.example.com"`); + if (!Array.isArray(credentialOrigins)) { + throw new ConfigurationError('INVALID_CONFIG', 'web({ credentialOrigins }) must be an array of origins such as "https://preview.example.com"'); } - for (const [index, origin] of origins.entries()) { + for (const [index, origin] of credentialOrigins.entries()) { const problem = originProblem(origin); - if (problem !== undefined) throw new ConfigurationError('INVALID_CONFIG', `${label}[${index}] ${problem}`); + if (problem !== undefined) throw new ConfigurationError('INVALID_CONFIG', `web({ credentialOrigins })[${index}] ${problem}`); } } diff --git a/packages/web/src/protected-app.ts b/packages/web/src/protected-app.ts index 71b35e4936..c35cf2efbb 100644 --- a/packages/web/src/protected-app.ts +++ b/packages/web/src/protected-app.ts @@ -1,20 +1,21 @@ /** * Protected-preview access, scoped to exact origins: the app's own and the - * extras the options list. The configured headers ride only requests bound - * for one of them, and basic-auth credentials answer only a challenge one of - * them issues. The surface calls these on every context it creates; nothing - * here holds state. + * extras `credentialOrigins` lists. The configured headers ride requests + * that start at one of them, and basic-auth credentials answer only a + * challenge one of them issues (on WebKit, see `httpCredentials`). The + * surface calls these on every context it creates; nothing here holds state. */ import type { BrowserContext } from 'playwright-core'; import type { ResolveSecretOptions, Secret } from 'e2e/engine'; +import type { BrowserName } from './browser-connection.ts'; import type { WebBasicAuth } from './surface.ts'; -/** The credentials Playwright answers an HTTP authentication challenge from `origin` with. */ +/** The credentials Playwright answers an HTTP authentication challenge from `origin` with, or from any origin without one. */ export interface PlaywrightHttpCredential { readonly username: string; readonly password: string; - readonly origin: string; + readonly origin?: string; } /** An HTTP header field name: one or more `token` characters (RFC 9110). */ @@ -58,7 +59,7 @@ function originOf(url: string | URL): string | undefined { * The configured headers a request to `url` carries: all of them when its * origin is one of `origins`, none otherwise. */ -export function originHeadersFor( +export function configuredHeadersFor( url: string | URL, origins: ReadonlySet, headers: Readonly> | undefined, @@ -76,19 +77,19 @@ export function originHeadersFor( * they name, and a request that started elsewhere stays without them. * Registered before any test route, so it * runs last: a test route's `fallback` reaches it, and a `continue`, which - * skips it, merges the same headers itself (`originHeadersFor`). Nothing + * skips it, merges the same headers itself (`configuredHeadersFor`). Nothing * awaits a route handler, so a fallback that fails (the page closed under * the request) is dropped rather than left to surface as an unhandled * rejection. */ -export async function installOriginHeaders( +export async function installConfiguredHeaders( context: BrowserContext, origins: ReadonlySet, headers: Readonly> | undefined, ): Promise { if (headers === undefined || origins.size === 0) return; await context.route( - (url) => originHeadersFor(url, origins, headers) !== undefined, + (url) => configuredHeadersFor(url, origins, headers) !== undefined, async (route) => { await route.fallback({ headers: { ...route.request().headers(), ...headers } }).catch(() => undefined); }, @@ -98,22 +99,35 @@ export async function installOriginHeaders( /** * The basic-auth credentials a context answers a challenge with: one * Playwright `httpCredentials` entry per origin in `origins`, so a `401` - * from any other origin goes unanswered. A `Secret` password resolves - * through the attempt, which registers the value for redaction, and the - * `Authorization` credential Playwright sends with it too: a page that - * echoes its request headers shows that, not the password. + * from any other origin goes unanswered. WebKit is the exception: it never + * matches a scoped credential to an origin on its scheme's default port or + * with an IPv6 host (Playwright 1.64 compares the challenge's port 443 with + * the origin's absent port as 0), so when one of `origins` is such an + * origin, WebKit gets one unscoped credential that answers every origin, as + * Playwright's own default does. A `Secret` password resolves through the + * attempt, which registers the value for redaction, and the `Authorization` + * credential Playwright sends with it too: a page that echoes its request + * headers shows that, not the password. */ export async function httpCredentials( basicAuth: WebBasicAuth, origins: ReadonlySet, + browser: BrowserName, resolveSecret: (secret: Secret, options?: ResolveSecretOptions) => Promise, ): Promise { const { username, password } = basicAuth; const plaintext = typeof password === 'string' ? password : await resolveSecret(password, { derived: (value) => basicCredentials(username, value) }); + if (browser === 'webkit' && [...origins].some(webkitCannotScope)) return [{ username, password: plaintext }]; return [...origins].map((origin) => ({ username, password: plaintext, origin })); } +/** Whether WebKit drops a credential scoped to `origin`: a default port, which `URL.origin` leaves out, or an IPv6 host. */ +function webkitCannotScope(origin: string): boolean { + const url = new URL(origin); + return url.port === '' || url.hostname.startsWith('['); +} + /** * The credential an `Authorization: Basic` header carries for `username` and * `password`, base64 of `username:password` as Playwright encodes it, with @@ -126,8 +140,8 @@ function basicCredentials(username: string, password: string): string[] { } /** - * The exact origins a credential goes to: the app's own, when the runner - * reports one, and each extra the options list, normalized as `URL.origin` + * The exact origins the credentials go to: the app's own, when the runner + * reports one, and each of `credentialOrigins`, normalized as `URL.origin` * serializes it. Config load has checked every extra is an origin. */ export function credentialOrigins(appOrigin: string | undefined, extras: readonly string[] | undefined): ReadonlySet { @@ -137,7 +151,9 @@ export function credentialOrigins(appOrigin: string | undefined, extras: readonl /** * Why `value` is not an origin a credential can be scoped to, or `undefined` * when it is: an `http:` or `https:` URL with no user info, path, query, or - * fragment (`https://api.example.com`, a trailing `/` allowed). + * fragment (`https://api.example.com`, a trailing `/` allowed). A `*` in the + * host and port `0` parse as URLs but match no request, so they are refused + * too, rather than loading a config that sends nothing. */ export function originProblem(value: unknown): string | undefined { const expected = 'must be an origin such as "https://preview.example.com": an http or https URL with no path, query, or fragment'; @@ -148,6 +164,8 @@ export function originProblem(value: unknown): string | undefined { } catch { return `${expected}, got "${value}"`; } + if (url.hostname.includes('*')) return `must be an exact origin, got "${value}": a wildcard matches no request, so list each origin`; + if (url.port === '0') return `must name the port requests use, got "${value}": port 0 matches no request`; const bare = url.username === '' && url.password === '' && url.pathname === '/' && url.search === '' && url.hash === '' && !value.endsWith('?') && !value.endsWith('#'); return (url.protocol === 'http:' || url.protocol === 'https:') && bare ? undefined : `${expected}, got "${value}"`; } diff --git a/packages/web/src/route-options.ts b/packages/web/src/route-options.ts index 1869c635cd..f09cf823be 100644 --- a/packages/web/src/route-options.ts +++ b/packages/web/src/route-options.ts @@ -26,7 +26,7 @@ export interface FulfillDecision { /** * What `route.continue` hands Playwright once the overrides are validated; - * `headers` before the site's are merged in, a header set to `undefined` + * `headers` before the configured ones are merged in, a header set to `undefined` * left out so the request goes without it. */ export interface ContinueDecision { diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index fff9a4ebf1..3476c9ce91 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -63,7 +63,7 @@ import { ConfiguredInitScripts, type WebInitScript } from './init-scripts.ts'; import type { WebMedia } from './media.ts'; import { SECURE_FIELD_SELECTOR, type RawNodeData } from './read-node.ts'; import { readSelector, takeReadsFunction } from './read-selector.ts'; -import { credentialOrigins, httpCredentials, installOriginHeaders, lowercaseNames, originHeadersFor } from './protected-app.ts'; +import { credentialOrigins, httpCredentials, installConfiguredHeaders, lowercaseNames, configuredHeadersFor } from './protected-app.ts'; import { RefRegistry } from './refs.ts'; import { cancelled, @@ -150,12 +150,6 @@ export interface WebBasicAuth { * like any configured secret. */ readonly password: string | Secret; - /** - * More origins whose challenge the browser answers, beyond the app's own - * (`app.url`'s scheme, host, and port): an API host or a redirect target - * behind the same gate. Exact origins, such as `https://api.example.com`. - */ - readonly origins?: readonly string[]; } /** The engine's screencast of the page: the frame size and the JPEG quality of the frames it encodes. */ @@ -199,12 +193,14 @@ export interface WebOptions { */ readonly connect?: WebConnectOptions; /** - * HTTP headers added to every request the browser sends to the app's - * origin (`app.url`'s scheme, host, and port) or one in `headerOrigins`: - * a preview-protection bypass token, a tunnel's interstitial skip. - * Requests to any other origin (another port on the same host, a sibling - * subdomain, a CDN, an identity provider) never carry them, so a header - * that is a secret stays with the app it unlocks. Names are case-insensitive; a header the page already + * HTTP headers added to every request the browser starts at the app's + * origin (`app.url`'s scheme, host, and port) or one in + * `credentialOrigins`: a preview-protection bypass token, a tunnel's + * interstitial skip. A request that starts at any other origin (another + * port on the same host, a sibling subdomain, a CDN) goes without them. + * Playwright keeps a request's headers through its redirects, so a + * redirect from the app to an identity provider carries them there. + * Names are case-insensitive; a header the page already * sends under the same name is replaced. Applies to every path onto the * page, deterministic and agent-driven alike. Injecting headers routes * every request of the attempt, which turns the browser's HTTP cache off @@ -212,19 +208,22 @@ export interface WebOptions { * page it controlled would reach the gate bare). */ readonly headers?: Readonly>; - /** - * More origins that receive `headers`, beyond the app's own: an API host - * or a redirect target behind the same gate. Exact origins, such as - * `https://api.example.com`; requires `headers`. - */ - readonly headerOrigins?: readonly string[]; /** * HTTP basic authentication for a staging app behind a browser challenge. * The browser answers a `401` from the app's origin, or one in - * `basicAuth.origins`, with these credentials, and no other. Applies to - * every path onto the page. + * `credentialOrigins`, with these credentials, and no other. WebKit cannot + * scope a credential to an origin on its scheme's default port or with an + * IPv6 host, so when one of those origins is such an origin, WebKit + * answers every origin's challenge. Applies to every path onto the page. */ readonly basicAuth?: WebBasicAuth; + /** + * More origins that receive `headers` and `basicAuth`, beyond the app's + * own: an API host or a redirect target behind the same gate. Exact + * origins, such as `https://api.example.com`; requires `headers` or + * `basicAuth`. + */ + readonly credentialOrigins?: readonly string[]; /** * The attribute that carries an element's test id: what the `testId` query * (`screen.getByTestId`) resolves and what `SemanticNode.testId` reports. @@ -302,9 +301,9 @@ export class PlaywrightSurface { private readonly screencast: WebScreencastOptions; /** Injected request headers, names lowercased so they replace the browser's own of the same name. */ private readonly headers: Readonly> | undefined; - private readonly headerOrigins: readonly string[] | undefined; - /** Where `headers` go: the app's origin and each of `headerOrigins`, set at `init`. */ - private headerScope: ReadonlySet = new Set(); + private readonly credentialOrigins: readonly string[] | undefined; + /** Where `headers` and `basicAuth` go: the app's origin and each of `credentialOrigins`, set at `init`. */ + private credentialScope: ReadonlySet = new Set(); private readonly basicAuth: WebBasicAuth | undefined; private readonly testIdAttribute: string; private readonly userAgent: string | undefined; @@ -341,7 +340,7 @@ export class PlaywrightSurface { this.viewport = options.viewport === undefined ? DEFAULT_VIEWPORT : options.viewport; this.screencast = options.screencast ?? {}; this.headers = options.headers === undefined ? undefined : lowercaseNames(options.headers); - this.headerOrigins = options.headerOrigins; + this.credentialOrigins = options.credentialOrigins; this.basicAuth = options.basicAuth; this.testIdAttribute = options.testIdAttribute ?? DEFAULT_TEST_ID_ATTRIBUTE; this.userAgent = options.userAgent; @@ -388,10 +387,10 @@ export class PlaywrightSurface { async init(info: EngineInitInfo): Promise { // A runner older than the peer floor passes no origin; fail rather than send the credentials nowhere. if (info.app.origin === undefined && (this.headers !== undefined || this.basicAuth !== undefined)) { - throw new ConfigurationError('INVALID_CONFIG', 'web({ headers, basicAuth }) needs e2e 0.23.1 or later, which tells the engine the app\'s origin; update e2e'); + throw new ConfigurationError('INVALID_CONFIG', 'web({ headers, basicAuth }) needs an e2e runner that tells the engine the app\'s origin; update e2e to the release beside this @e2e-dev/web'); } this.app = info.app; - this.headerScope = credentialOrigins(info.app.origin, this.headerOrigins); + this.credentialScope = credentialOrigins(info.app.origin, this.credentialOrigins); this.projectRoot = info.projectRoot; this.headed = info.headed; this.leases?.init(info); @@ -508,7 +507,7 @@ export class PlaywrightSurface { basicAuth === undefined ? undefined : await raceAbort( - () => httpCredentials(basicAuth, credentialOrigins(this.app.origin, basicAuth.origins), context.resolveSecret), + () => httpCredentials(basicAuth, this.credentialScope, this.browserName, context.resolveSecret), context.signal, 'resolving the basic-auth password', ); @@ -552,7 +551,7 @@ export class PlaywrightSurface { ownNavigation: () => this.ownNavigations > 0, testPage: () => this.openPage(), }); - await installOriginHeaders(target, this.headerScope, this.headers); + await installConfiguredHeaders(target, this.credentialScope, this.headers); if (granted.length > 0) await target.grantPermissions(granted); for (const stored of routes) await target.route(stored.predicate, stored.handler); }, @@ -634,9 +633,9 @@ export class PlaywrightSurface { await context.route(predicate, handler); } - /** The configured headers a request to `url` carries, lowercased; `undefined` off the app's origin and `headerOrigins`. */ - originHeaders(url: string): Readonly> | undefined { - return originHeadersFor(url, this.headerScope, this.headers); + /** The configured headers a request to `url` carries, lowercased; `undefined` off the app's origin and `credentialOrigins`. */ + configuredHeaders(url: string): Readonly> | undefined { + return configuredHeadersFor(url, this.credentialScope, this.headers); } /** Resolves a file a test names against the project root, as config paths do, never `process.cwd()`. */ diff --git a/packages/web/tests/integration/protected-app.test.ts b/packages/web/tests/integration/protected-app.test.ts index 74a5a4fc1e..ee6400a655 100644 --- a/packages/web/tests/integration/protected-app.test.ts +++ b/packages/web/tests/integration/protected-app.test.ts @@ -1,11 +1,12 @@ /** - * Reaching an app behind a gate: configured request headers reach the app's - * origin on every context the attempt opens, and basic-auth credentials - * answer only its challenge; neither reaches another origin unless the - * options list it. Driven through the engine hooks, as the attempt executor - * drives them; a second fixture instance stands in for another origin, on - * the same host under another port, and as `localhost` rather than - * `127.0.0.1` for a third-party site. + * Reaching an app behind a gate: configured request headers ride requests + * that start at the app's origin, on every context the attempt opens, and + * basic-auth credentials answer only its challenge. A request that starts at + * another origin gets neither unless `credentialOrigins` lists it; a + * redirect keeps the headers its request started with. Driven through the + * engine hooks, as the attempt executor drives them; a second fixture + * instance stands in for another origin, on the same host under another + * port, and as `localhost` rather than `127.0.0.1` for a third-party site. */ import { mkdtempSync, rmSync } from 'node:fs'; @@ -99,8 +100,8 @@ describe('web({ headers, basicAuth })', () => { } }); - it('sends the headers to an origin headerOrigins lists, and no other', async () => { - const engine = web({ headers: { 'x-fixture-header': 'listed' }, headerOrigins: [`${otherPort}/`] }); + it('sends the headers to an origin credentialOrigins lists, and no other', async () => { + const engine = web({ headers: { 'x-fixture-header': 'listed' }, credentialOrigins: [`${otherPort}/`] }); try { await boot(engine, app, artifactsDir, 'h3'); expect(await headingAt(engine, 'h3', `${otherPort}/headers`)).toBe('listed'); @@ -190,8 +191,8 @@ describe('web({ headers, basicAuth })', () => { } }); - it('answers a challenge from an origin basicAuth.origins lists, and no other', async () => { - const engine = web({ basicAuth: { ...PROTECTED_CREDENTIAL, origins: [otherPort] } }); + it('answers a challenge from an origin credentialOrigins lists, and no other', async () => { + const engine = web({ basicAuth: PROTECTED_CREDENTIAL, credentialOrigins: [otherPort] }); try { await boot(engine, app, artifactsDir, 'b2'); expect(await headingAt(engine, 'b2', `${app.url}/protected`)).toBe('Protected'); diff --git a/packages/web/tests/integration/routes.test.ts b/packages/web/tests/integration/routes.test.ts index 836c7cee34..fe18b9066b 100644 --- a/packages/web/tests/integration/routes.test.ts +++ b/packages/web/tests/integration/routes.test.ts @@ -1,11 +1,12 @@ /** * Route decisions against a server that counts what reaches it: `continue` * goes to the network past every other route and carries the configured - * headers itself, `fallback` hands the request to the route before it, - * the overrides each decision implements reach the wire, and an option it - * does not implement fails the next step instead of being dropped. Also the - * one call beside routing that takes a URL the same way: a relative cookie - * URL. + * headers itself (to the app's origin and the one `credentialOrigins` lists, + * not another port on the same host), `fallback` hands the request to the + * route before it, the overrides each decision implements reach the wire, + * and an option it does not implement fails the next step instead of being + * dropped. Also the one call beside routing that takes a URL the same way: a + * relative cookie URL. */ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; @@ -81,14 +82,20 @@ function startCountingServer(hits: Map): Promise<{ server: Serve } describe('browser.route decisions', () => { - const surface = new PlaywrightSurface({ headers: { 'X-Gate': 'open-sesame' } }); + let surface: PlaywrightSurface; const projectRoot = mkdtempSync(path.join(tmpdir(), 'e2e-routes-')); const signal = new AbortController().signal; const hits = new Map(); const attached: string[] = []; + /** The app's server, then the unlisted and listed ports. */ let server: Server; + let servers: Server[]; let origin: string; let otherOrigin: string; + /** Another port on the app's host: the same site, another origin, not listed. */ + let unlistedOrigin: string; + /** A third port on the app's host, in `credentialOrigins`. */ + let listedOrigin: string; let page: Page; let browser: Browser; @@ -102,11 +109,15 @@ describe('browser.route decisions', () => { }; beforeAll(async () => { - const started = await startCountingServer(hits); + const [started, unlisted, listed] = await Promise.all([startCountingServer(hits), startCountingServer(hits), startCountingServer(hits)]); server = started.server; + servers = [server, unlisted.server, listed.server]; origin = `http://127.0.0.1:${started.port}`; // The same server under another host name: another origin. otherOrigin = `http://localhost:${started.port}`; + unlistedOrigin = `http://127.0.0.1:${unlisted.port}`; + listedOrigin = `http://127.0.0.1:${listed.port}`; + surface = new PlaywrightSurface({ headers: { 'X-Gate': 'open-sesame' }, credentialOrigins: [listedOrigin] }); writeFileSync(path.join(projectRoot, 'quote.json'), '{"cents":4200}\n'); await surface.init({ runId: 'routes', targetName: 'web', projectRoot, app: { origin, site: '127.0.0.1' }, env: {}, headed: false, workerSlot: 0, signal, log: () => undefined }); @@ -134,7 +145,7 @@ describe('browser.route decisions', () => { afterAll(async () => { await surface.dispose({ signal, timeoutMs: 5_000 }); - await new Promise((resolve) => server.close(() => resolve())); + await Promise.all(servers.map((each) => new Promise((resolve) => each.close(() => resolve())))); rmSync(projectRoot, { recursive: true, force: true }); }); @@ -440,6 +451,27 @@ describe('browser.route decisions', () => { expect(hits.get('/echo')).toBe(1); }); + it('continue to another port on the same host leaves the configured header behind, and to a listed origin keeps it', async () => { + await browser.route('**/api/unlisted', (route) => route.continue({ url: `${unlistedOrigin}/echo` })); + await browser.route('**/api/listed', (route) => route.continue({ url: `${listedOrigin}/echo` })); + expect((await fetchEcho(`${origin}/api/unlisted`)).headers['x-gate']).toBeUndefined(); + expect((await fetchEcho(`${origin}/api/listed`)).headers['x-gate']).toBe('open-sesame'); + }); + + it('fetch sends the configured header to a listed origin, not another port on the same host', async () => { + const sent = new Map(); + await browser.route('**/echo', async (route) => { + const echo = await (await route.fetch()).json(); + sent.set(new URL(route.request.url).origin, echo.headers['x-gate']); + await route.fulfill({ body: '' }); + }); + // Cross-origin from the page, so the fulfilled reply fails CORS; the route has already read the echo. + for (const target of [unlistedOrigin, listedOrigin]) { + await page.evaluate((url) => fetch(url).then(() => undefined, () => undefined), `${target}/echo`); + } + expect(Object.fromEntries(sent)).toEqual({ [unlistedOrigin]: undefined, [listedOrigin]: 'open-sesame' }); + }); + it('continue to another origin leaves the configured header behind', async () => { await browser.route('**/api/quote', (route) => route.continue({ url: `${otherOrigin}/echo` })); const echo = await fetchEcho(`${origin}/api/quote`); diff --git a/packages/web/tests/unit/protected-app-options.test.ts b/packages/web/tests/unit/protected-app-options.test.ts index d8b94713ab..d75f71fa1a 100644 --- a/packages/web/tests/unit/protected-app-options.test.ts +++ b/packages/web/tests/unit/protected-app-options.test.ts @@ -1,5 +1,5 @@ /** - * The `headers`, `headerOrigins`, `basicAuth`, `testIdAttribute`, `userAgent`, `locale`, `timezoneId`, `colorScheme`, `reducedMotion`, `initScripts`, and `screencast` options are checked at + * The `headers`, `basicAuth`, `credentialOrigins`, `testIdAttribute`, `userAgent`, `locale`, `timezoneId`, `colorScheme`, `reducedMotion`, `initScripts`, and `screencast` options are checked at * config load, so a header the browser could never send or an attribute no * element could carry fails the run before a browser launches. What the * browser does with valid ones is in tests/integration. @@ -34,11 +34,12 @@ describe('web({ headers })', () => { }); }); -describe('web({ headerOrigins })', () => { +describe('web({ credentialOrigins })', () => { const headers = { 'x-preview': 'token' }; - it('accepts exact http and https origins, a trailing slash included', () => { - expect(() => web({ headers, headerOrigins: ['https://api.example.com', 'http://127.0.0.1:4000/'] })).not.toThrow(); + it('accepts exact http and https origins beside headers or basicAuth, a trailing slash included', () => { + expect(() => web({ headers, credentialOrigins: ['https://api.example.com', 'http://127.0.0.1:4000/'] })).not.toThrow(); + expect(() => web({ basicAuth: { username: 'ada', password: 'x' }, credentialOrigins: ['https://api.example.com'] })).not.toThrow(); }); it('rejects an entry that is not an origin, naming it', () => { @@ -50,15 +51,19 @@ describe('web({ headerOrigins })', () => { ['ftp://api.example.com', /\[0\] must be an origin/], ['api.example.com', /\[0\] must be an origin/], [3, /\[0\] must be an origin.*got number/], + // These parse as URLs but match no request. + ['https://*.vercel.app', /\[0\] must be an exact origin.*wildcard/], + ['http://*:3000', /\[0\] must be an exact origin.*wildcard/], + ['http://127.0.0.1:0', /\[0\] must name the port.*port 0/], ]; for (const [origin, message] of cases) { - expect(() => web({ headers, headerOrigins: [origin as string] })).toThrow(expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringMatching(message) })); + expect(() => web({ headers, credentialOrigins: [origin as string] })).toThrow(expect.objectContaining({ code: 'INVALID_CONFIG', message: expect.stringMatching(message) })); } - expect(() => web({ headers, headerOrigins: 'https://api.example.com' as unknown as string[] })).toThrowError(/must be an array of origins/); + expect(() => web({ headers, credentialOrigins: 'https://api.example.com' as unknown as string[] })).toThrowError(/must be an array of origins/); }); - it('rejects headerOrigins without headers to send', () => { - expect(() => web({ headerOrigins: ['https://api.example.com'] })).toThrowError(/requires headers/); + it('rejects credentialOrigins without headers or basicAuth to send', () => { + expect(() => web({ credentialOrigins: ['https://api.example.com'] })).toThrowError(/requires headers or basicAuth/); }); }); @@ -92,13 +97,6 @@ describe('web({ basicAuth })', () => { web({ basicAuth: { username: 'ada', password: { name: 'stagingPassword' } as unknown as string } }), ).toThrowError(/password string or secrets\.get\(name\)/); }); - - it('accepts exact extra origins and rejects anything else, naming the entry', () => { - expect(() => web({ basicAuth: { username: 'ada', password: 'x', origins: ['https://api.example.com'] } })).not.toThrow(); - expect(() => web({ basicAuth: { username: 'ada', password: 'x', origins: ['https://api.example.com', 'https://example.com/login'] } })).toThrowError( - /web\(\{ basicAuth: \{ origins \} \}\)\[1\] must be an origin/, - ); - }); }); describe('web({ testIdAttribute })', () => { @@ -225,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, headerOrigins, basicAuth, testIdAttribute, userAgent, locale, timezoneId, colorScheme, reducedMotion, initScripts'), + refused('web() has unknown key "launchOptions"; expected one of browser, viewport, screencast, connect, headers, basicAuth, credentialOrigins, testIdAttribute, userAgent, locale, timezoneId, colorScheme, reducedMotion, initScripts'), ); }); @@ -246,21 +244,36 @@ describe('web() option keys', () => { describe('basic-auth credentials', () => { const app = 'http://127.0.0.1:3000'; + const notASecret = async (): Promise => { + throw new Error('not a secret'); + }; it('scopes one entry to each origin: the app\'s, then the extras, normalized', async () => { const origins = credentialOrigins(app, ['https://API.example.com:443/', 'http://127.0.0.1:3000']); - const credentials = await httpCredentials({ username: 'ada', password: 'plain-value' }, origins, async () => { - throw new Error('not a secret'); - }); + const credentials = await httpCredentials({ username: 'ada', password: 'plain-value' }, origins, 'chromium', notASecret); expect(credentials).toEqual([ { username: 'ada', password: 'plain-value', origin: app }, { username: 'ada', password: 'plain-value', origin: 'https://api.example.com' }, ]); }); + it('goes unscoped on WebKit when an origin is on a default port or an IPv6 host, which WebKit cannot match', async () => { + const plain = { username: 'ada', password: 'plain-value' }; + for (const extra of ['https://api.example.com', 'http://[::1]:3000']) { + expect(await httpCredentials(plain, credentialOrigins(app, [extra]), 'webkit', notASecret)).toEqual([plain]); + } + expect(await httpCredentials(plain, credentialOrigins(app, ['http://localhost:4000']), 'webkit', notASecret)).toEqual([ + { ...plain, origin: app }, + { ...plain, origin: 'http://localhost:4000' }, + ]); + expect(await httpCredentials(plain, credentialOrigins('https://example.com', undefined), 'firefox', notASecret)).toEqual([ + { ...plain, origin: 'https://example.com' }, + ]); + }); + it('registers the Authorization credential a secret password becomes, padded and not, for redaction', async () => { const asked: { name: string; derived: readonly string[] }[] = []; - const credentials = await httpCredentials({ username: 'ada', password: secrets.get('stagingPassword') }, credentialOrigins(app, undefined), async (secret, options) => { + const credentials = await httpCredentials({ username: 'ada', password: secrets.get('stagingPassword') }, credentialOrigins(app, undefined), 'chromium', async (secret, options) => { asked.push({ name: secret.name, derived: (await options?.derived?.('pa55word!')) ?? [] }); return 'pa55word!'; }); diff --git a/plugins/e2e/skills/e2e/references/setup.md b/plugins/e2e/skills/e2e/references/setup.md index a4a22cab51..a55caf38d6 100644 --- a/plugins/e2e/skills/e2e/references/setup.md +++ b/plugins/e2e/skills/e2e/references/setup.md @@ -215,8 +215,8 @@ start a script that brings them up and serves the app. | `browser` | `'chromium'` (default), `'firefox'`, `'webkit'`, or a `BrowserProvider` leasing hosted browsers over CDP (`kernel()` from `@e2e-dev/kernel`, `smol()` from `@e2e-dev/smol`, `lightpanda()` from `@e2e-dev/lightpanda`, `testmuBrowsers()` from `@e2e-dev/testmu/web`, `e2bBrowsers()` from `@e2e-dev/e2b/web`, or your own), which implies chromium and excludes `connect`. Scope `'worker'` (default): one browser per worker slot from `prepare` to `finish`; `'attempt'`: one per attempt, with `reconnectEndpoint`'s limits (`lightpanda()` and `testmuBrowsers()` are worker scope only). | | `viewport` | `{ width, height }`, default 1280x720; `null` follows the browser window (hosted live view, headed run). On a headed hosted browser (Kernel) use `null` and size the service's screen; a fixed size gives a smaller, unmaximized window. | | `connect` | `{ cdpEndpoint }` attaches to a remote Chromium over CDP; `cdpEndpoint` is required, and both it and `reconnectEndpoint` are resolvers `(signal) => url`, not strings, else `INVALID_CONFIG` at load. With `reconnectEndpoint` it rides one persistent default context, needs a fresh browser from `cdpEndpoint` every attempt, and reconnects only to the original browser and page. | -| `headers` | Sent to the app's origin only (scheme, host, and port of `app.url`; Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; `headerOrigins: ['https://api.example.com']` adds exact origins. A request keeps them through its redirects, to any origin. Disables the browser HTTP cache and service workers. | -| `basicAuth` | `{ username, password, origins? }` for a `401` challenge from the app's origin, or one `origins` lists (a redirect to `www` or `https:` is another origin); `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | +| `headers` | Sent to the app's origin only (scheme, host, and port of `app.url`; Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; `credentialOrigins: ['https://api.example.com']` adds exact origins for `headers` and `basicAuth`. A request keeps them through its redirects, to any origin. Disables the browser HTTP cache and service workers. | +| `basicAuth` | `{ username, password }` for a `401` challenge from the app's origin, or one `credentialOrigins` lists (a redirect to `www` or `https:` is another origin; WebKit answers any origin when one is on a default port or an IPv6 host); `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | | `userAgent` | The `User-Agent` every attempt sends and `navigator.userAgent` reports. | | `locale`, `timezoneId` | The language (`'de-DE'`: `navigator.language`, `Intl`, `Accept-Language`) and IANA time zone (`'Europe/Berlin'`) every attempt runs in. | | `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. | diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index 1b89acfcd4..ea12828340 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -503,8 +503,9 @@ the app opens itself (`target="_blank"`, `window.open`) is not followed: `fulfill({ status?, headers?, contentType?, json | body | path })` (`body` a string or bytes; several cookies as one `\n`-joined `set-cookie`), `continue({ url?, method?, headers?, postData? })` (straight to the - network; a header set to `undefined` is dropped, configured origin headers - still added), `fallback()` (the route registered before it), or `abort()`; + network; a header set to `undefined` is dropped, the configured `headers` + still added on an allowed origin), `fallback()` (the route registered + before it), or `abort()`; none or two fails the next step with `ACTION_FAILED`, an unsupported option with `INVALID_ARGUMENT`. - `unrouteAll()` removes every route; configured headers stay. diff --git a/skills/e2e/references/setup.md b/skills/e2e/references/setup.md index a4a22cab51..a55caf38d6 100644 --- a/skills/e2e/references/setup.md +++ b/skills/e2e/references/setup.md @@ -215,8 +215,8 @@ start a script that brings them up and serves the app. | `browser` | `'chromium'` (default), `'firefox'`, `'webkit'`, or a `BrowserProvider` leasing hosted browsers over CDP (`kernel()` from `@e2e-dev/kernel`, `smol()` from `@e2e-dev/smol`, `lightpanda()` from `@e2e-dev/lightpanda`, `testmuBrowsers()` from `@e2e-dev/testmu/web`, `e2bBrowsers()` from `@e2e-dev/e2b/web`, or your own), which implies chromium and excludes `connect`. Scope `'worker'` (default): one browser per worker slot from `prepare` to `finish`; `'attempt'`: one per attempt, with `reconnectEndpoint`'s limits (`lightpanda()` and `testmuBrowsers()` are worker scope only). | | `viewport` | `{ width, height }`, default 1280x720; `null` follows the browser window (hosted live view, headed run). On a headed hosted browser (Kernel) use `null` and size the service's screen; a fixed size gives a smaller, unmaximized window. | | `connect` | `{ cdpEndpoint }` attaches to a remote Chromium over CDP; `cdpEndpoint` is required, and both it and `reconnectEndpoint` are resolvers `(signal) => url`, not strings, else `INVALID_CONFIG` at load. With `reconnectEndpoint` it rides one persistent default context, needs a fresh browser from `cdpEndpoint` every attempt, and reconnects only to the original browser and page. | -| `headers` | Sent to the app's origin only (scheme, host, and port of `app.url`; Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; `headerOrigins: ['https://api.example.com']` adds exact origins. A request keeps them through its redirects, to any origin. Disables the browser HTTP cache and service workers. | -| `basicAuth` | `{ username, password, origins? }` for a `401` challenge from the app's origin, or one `origins` lists (a redirect to `www` or `https:` is another origin); `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | +| `headers` | Sent to the app's origin only (scheme, host, and port of `app.url`; Vercel's `x-vercel-protection-bypass`, ngrok's `ngrok-skip-browser-warning`), `agent.act` included; `credentialOrigins: ['https://api.example.com']` adds exact origins for `headers` and `basicAuth`. A request keeps them through its redirects, to any origin. Disables the browser HTTP cache and service workers. | +| `basicAuth` | `{ username, password }` for a `401` challenge from the app's origin, or one `credentialOrigins` lists (a redirect to `www` or `https:` is another origin; WebKit answers any origin when one is on a default port or an IPv6 host); `password` may be `secrets.get('name')`, resolved per attempt and redacted like any secret, the base64 `Authorization` credential too. | | `userAgent` | The `User-Agent` every attempt sends and `navigator.userAgent` reports. | | `locale`, `timezoneId` | The language (`'de-DE'`: `navigator.language`, `Intl`, `Accept-Language`) and IANA time zone (`'Europe/Berlin'`) every attempt runs in. | | `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. | diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index 1b89acfcd4..ea12828340 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -503,8 +503,9 @@ the app opens itself (`target="_blank"`, `window.open`) is not followed: `fulfill({ status?, headers?, contentType?, json | body | path })` (`body` a string or bytes; several cookies as one `\n`-joined `set-cookie`), `continue({ url?, method?, headers?, postData? })` (straight to the - network; a header set to `undefined` is dropped, configured origin headers - still added), `fallback()` (the route registered before it), or `abort()`; + network; a header set to `undefined` is dropped, the configured `headers` + still added on an allowed origin), `fallback()` (the route registered + before it), or `abort()`; none or two fails the next step with `ACTION_FAILED`, an unsupported option with `INVALID_ARGUMENT`. - `unrouteAll()` removes every route; configured headers stay. From 4ad8d7b7ae43095ddb62c77f8de5aa429c44c9f8 Mon Sep 17 00:00:00 2001 From: Krzysztof Moch Date: Fri, 6 Nov 2026 11:31:12 +0100 Subject: [PATCH 4/4] docs(web): headers follow a request through redirects; WebKit IPv6 caveat --- docs/migrate/playwright.mdx | 2 +- docs/reference/security.mdx | 11 ++++++----- docs/security.mdx | 2 +- docs/web.mdx | 11 ++++++----- 4 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/migrate/playwright.mdx b/docs/migrate/playwright.mdx index bd1c2381ab..979b8e6966 100644 --- a/docs/migrate/playwright.mdx +++ b/docs/migrate/playwright.mdx @@ -69,7 +69,7 @@ A Playwright key such as `testDir`, `baseURL`, `use`, `webServer`, or | `use.viewport`, `use.browserName` | `web({ viewport, browser })` | renamed | | `use.testIdAttribute` | `web({ testIdAttribute })` | renamed | | `use.httpCredentials` | `web({ basicAuth })`, answered for the app's origin only; `credentialOrigins` adds more | renamed | -| `use.extraHTTPHeaders` | `web({ headers })`, sent to the app's origin only; `credentialOrigins` adds more | renamed | +| `use.extraHTTPHeaders` | `web({ headers })`, sent on requests that start at the app's origin; `credentialOrigins` adds more | renamed | | `chromium.connectOverCDP(url)` | `web({ connect: { cdpEndpoint: () => url } })`, chromium only | renamed | | `use.connectOptions` (`wsEndpoint`) | `web({ connect })` attaches over CDP only | missing | | `retries`, `workers`, `timeout` | the same names at the top level. `workers` takes an integer from 1 to 1024, not `'50%'`; `retries` stops at 10. The defaults differ, see [below](#defaults-that-differ) | renamed | diff --git a/docs/reference/security.mdx b/docs/reference/security.mdx index 54289b26df..a060606c43 100644 --- a/docs/reference/security.mdx +++ b/docs/reference/security.mdx @@ -103,9 +103,9 @@ and use the step's secrets there. ### Request credentials -The browser engine sends configured request credentials only to exact -origins: the scheme, host, and port of `app.url`, plus the extras -`credentialOrigins` lists. +The browser engine scopes configured request credentials to exact origins: +the scheme, host, and port of `app.url`, plus the extras `credentialOrigins` +lists. | Option | Goes to | | --- | --- | @@ -113,8 +113,9 @@ origins: the scheme, host, and port of `app.url`, plus the extras | `basicAuth` | The answer to a `401` challenge from an allowed origin | - Another port on the same host, a subdomain, and a sibling host under a - shared domain such as `vercel.app` are other origins. They get no - credentials. + shared domain such as `vercel.app` are other origins. A request that + starts there carries no `headers`, and a `401` from there gets no answer, + except as the next bullets note. - `headers` follow the origin a request starts on. A request to an allowed origin keeps them through every redirect, to any origin. A request that starts elsewhere gets none, even when it redirects to an allowed origin. diff --git a/docs/security.mdx b/docs/security.mdx index 2b76cec8fc..53c1916726 100644 --- a/docs/security.mdx +++ b/docs/security.mdx @@ -39,7 +39,7 @@ Redaction matches strings, and screenshots mask secure fields only: app's origin or one you list, even one a third-party page starts, and stay on its redirects to any origin. `basicAuth` answers a `401` from those origins, and from any origin on WebKit when one of those is on a default - port. + port or has an IPv6 host. - **Committed recordings.** Cache entries store typed values verbatim, except secret fills. They aren't signed and replay with your permissions, so review them as you would test code. diff --git a/docs/web.mdx b/docs/web.mdx index 717598981b..311056e450 100644 --- a/docs/web.mdx +++ b/docs/web.mdx @@ -132,9 +132,10 @@ app: { }, ``` -The browser sends `headers` only to the origin of `app.url`: its scheme, -host, and port. To send them to another origin, such as an API host behind -the same gate, list it in `credentialOrigins`. See +The browser adds `headers` only to requests that start at the origin of +`app.url`: its scheme, host, and port. A request keeps them through its +redirects, to any origin. To add them for another origin, such as an API +host behind the same gate, list it in `credentialOrigins`. See [request credentials](/reference/security#request-credentials). For ngrok, use `'ngrok-skip-browser-warning': '1'`. `app.identity` keeps the cache identity stable when the preview URL changes. @@ -147,8 +148,8 @@ workers. Use `basicAuth` for HTTP basic authentication. The browser answers a `401` challenge from the origin of `app.url`, and from each origin in `credentialOrigins`. WebKit answers any origin when one of those is on a -default port, such as an `https://` URL with no port. Declare the password -under `secrets` and pass `secrets.get(name)`: +default port, such as an `https://` URL with no port, or has an IPv6 host. +Declare the password under `secrets` and pass `secrets.get(name)`: ```ts title="e2e.config.ts" import type { E2EConfig } from 'e2e';