Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/set-cookies-validation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@e2e-dev/web': patch
---

`browser.setCookies` checks each cookie against the `Cookie` type before the browser sees it, and refuses one it does not allow with `INVALID_ARGUMENT` naming the field. Before, a lowercase `sameSite: 'lax'`, a number `value` or a string `expires` was an `ENGINE_FAILURE` with exit code 3, a cookie with neither `url` nor `domain` failed with a bare `TypeError`, and one with both `url` and `domain` or `path` was set on the `url` with the `domain` and `path` silently dropped.
1 change: 1 addition & 0 deletions docs/reference/web.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -886,6 +886,7 @@ await browser.setCookies([{ url: 'http://localhost:3000', name: 'tz', value: 'UT

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | Not an array, or a cookie the `Cookie` type does not allow: a `name` or `value` that is not a string, neither or both of `url` and `domain`/`path`, an empty `domain`, an `expires` that is not a finite number, an `httpOnly` or `secure` that is not a boolean, a `sameSite` other than `'Strict'`, `'Lax'`, or `'None'`, or an unknown key. Nothing is set. |
| `POLICY_DENIED` | An unparseable target or a forbidden scheme. Nothing is set. |

```ts
Expand Down
2 changes: 2 additions & 0 deletions packages/web/src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import {
type OperationContext,
} from '@e2e-dev/core/engine';
import { classifyInputError } from './actions.ts';
import { validateCookies } from './cookies.ts';
import type { AttemptTab } from './attempt-session.ts';
import type { DialogHandler } from './dialogs.ts';
import { saveDownloadsTo, saveFromBrowser, saveLocally } from './downloads.ts';
Expand Down Expand Up @@ -857,6 +858,7 @@ export function createBrowserFixture(surface: PlaywrightSurface, context: Engine
);
}),
setCookies(cookies) {
validateCookies(cookies);
const scheme = new URL(baseHref()).protocol === 'https:' ? 'https' : 'http';
// The harness's URL rule decides which cookie targets are admitted; a
// domain cookie is checked as the origin it would be sent to. The rule
Expand Down
60 changes: 60 additions & 0 deletions packages/web/src/cookies.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* The cookies `browser.setCookies` takes, checked before the URL rule or the
* browser sees them. Tests run as JavaScript, so the `Cookie` type alone is no
* guard, and a cookie the browser would refuse is the test's mistake, not the
* engine's.
*/

import { TestError } from '@e2e-dev/core/engine';
import type { Cookie } from './browser.ts';
import { describe } from './support.ts';

const COOKIE_KEYS = ['name', 'value', 'url', 'domain', 'path', 'expires', 'httpOnly', 'secure', 'sameSite'] as const;
const SAME_SITE = ['Strict', 'Lax', 'None'] as const;

/** Throws `INVALID_ARGUMENT` naming the first field the `Cookie` type does not allow. */
export function validateCookies(cookies: unknown): asserts cookies is readonly Cookie[] {
if (!Array.isArray(cookies)) {
throw new TestError('INVALID_ARGUMENT', `browser.setCookies takes an array of cookies, got ${describe(cookies)}`);
}
cookies.forEach((cookie: unknown, index) => {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
const problem = cookieProblem(cookie);
if (problem !== undefined) throw new TestError('INVALID_ARGUMENT', `browser.setCookies cookies[${index}] ${problem}`);
});
}

function cookieProblem(cookie: unknown): string | undefined {
if (typeof cookie !== 'object' || cookie === null || Array.isArray(cookie)) {
return `must be an object, got ${describe(cookie)}`;
}
const known: readonly string[] = COOKIE_KEYS;
const unknown = Object.getOwnPropertyNames(cookie).find((key) => !known.includes(key));
if (unknown !== undefined) return `has no key ${JSON.stringify(unknown)}; it takes ${COOKIE_KEYS.join(', ')}`;
const field = (key: (typeof COOKIE_KEYS)[number]): unknown => Reflect.get(cookie, key);
for (const key of ['name', 'value'] as const) {
if (typeof field(key) !== 'string') return `${key} must be a string, got ${describe(field(key))}`;
}
for (const key of ['url', 'path'] as const) {
if (field(key) !== undefined && typeof field(key) !== 'string') return `${key} must be a string, got ${describe(field(key))}`;
}
Comment on lines +39 to +41

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3 · Non-blocking · Some cookies that the browser refuses still fail as ENGINE_FAILURE

Optional. This does not block the merge.

The header comment (lines 2-5) says that a cookie the browser would refuse is the test's mistake, not the engine's. A domain cookie with a path that is a string but not a valid path passes this check and reaches Playwright. Main and this head behave the same:

  • path: '' gives ENGINE_FAILURE: setCookies failed: browserContext.addCookies: Cookie should have a url or a domain/path pair. The message is also wrong, because the cookie has a domain.
  • path: 'account' gives ENGINE_FAILURE: ... Protocol error (Storage.setCookies): Invalid cookie fields.
  • sameSite: 'None' without secure: true resolves, but Chromium does not store the cookie, and there is no error.

The Cookie type allows these values, so they are outside the scope of the docs row. They are in the scope of the header comment.

const domain = field('domain');
if (domain !== undefined && (typeof domain !== 'string' || domain.trim() === '')) {
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
return `domain must be a non-empty string, got ${describe(domain)}`;
}
if (field('url') !== undefined && (domain !== undefined || field('path') !== undefined)) {
return 'takes url, or domain with an optional path, not both';
}
if (field('url') === undefined && domain === undefined) return 'needs a url, or a domain with an optional path';
const expires = field('expires');
if (expires !== undefined && (typeof expires !== 'number' || !Number.isFinite(expires))) {
return `expires must be a Unix timestamp in seconds, got ${describe(expires)}`;
}
for (const key of ['httpOnly', 'secure'] as const) {
if (field(key) !== undefined && typeof field(key) !== 'boolean') return `${key} must be a boolean, got ${describe(field(key))}`;
}
const sameSite = field('sameSite');
if (sameSite !== undefined && !(SAME_SITE as readonly unknown[]).includes(sameSite)) {
return `sameSite must be "Strict", "Lax", or "None", got ${describe(sameSite)}`;
}
return undefined;
}
120 changes: 120 additions & 0 deletions packages/web/tests/integration/set-cookies.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/**
* `browser.setCookies` against a real browser context: every shape the
* `Cookie` type allows lands as written, and anything else is
* `INVALID_ARGUMENT` naming the field, before the browser is asked, so a
* test's cookie mistake is not reported as an engine failure.
*/

import { mkdtempSync, rmSync } from 'node:fs';
import { createServer, type Server } from 'node:http';
import type { AddressInfo } from 'node:net';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from 'vitest';
import type { EngineFixtureContext } from '@e2e-dev/core/engine';
import { PlaywrightSurface } from '../../src/surface.ts';
import { createBrowserFixture, type Browser, type Cookie } from '../../src/browser.ts';
import { ignoreTrace, noSecrets } from '../helpers/secrets.ts';

/** Answers every path with an empty page. */
function startServer(): Promise<{ server: Server; port: number }> {
const server = createServer((_request, response) => {
response.writeHead(200, { 'content-type': 'text/html' });
response.end('<!doctype html><title>Cookies</title>');
});
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => resolve({ server, port: (server.address() as AddressInfo).port }));
});
}

describe('browser.setCookies', () => {
const surface = new PlaywrightSurface({});
const projectRoot = mkdtempSync(path.join(tmpdir(), 'e2e-set-cookies-'));
const signal = new AbortController().signal;
let server: Server;
let origin: string;
let browser: Browser;

beforeAll(async () => {
const started = await startServer();
server = started.server;
origin = `http://127.0.0.1:${started.port}`;
await surface.init({ runId: 'cookies', targetName: 'web', projectRoot, app: { site: '127.0.0.1' },
env: {}, headed: false, workerSlot: 0, signal, log: () => undefined });
});

beforeEach(async () => {
await surface.startAttempt({ attemptId: 'cookies', artifactsDir: projectRoot, signal, resolveSecret: noSecrets, ...ignoreTrace });
const page = await surface.ensurePage();
await page.goto(`${origin}/`);
browser = createBrowserFixture(surface, {
app: { site: '127.0.0.1', resolveUrl: (url: string) => new URL(url, `${origin}/`).href },
operation: (timeoutMs = 5_000) => ({ signal, timeoutMs, runId: 'cookies', attemptId: 'cookies', origin: 'test' }),
expectable: (target: object) => target,
fixture: (_name: string, target: object) => target,
} as unknown as EngineFixtureContext);
});

afterEach(async () => {
await surface.endAttempt({ signal, timeoutMs: 5_000 });
});

afterAll(async () => {
await surface.dispose({ signal, timeoutMs: 5_000 });
await new Promise<void>((resolve) => server.close(() => resolve()));
rmSync(projectRoot, { recursive: true, force: true });
});

it('sets every shape the Cookie type allows as written', async () => {
const tomorrow = Math.floor(Date.now() / 1000) + 86_400;
await browser.setCookies([
{ name: 'session', value: 'root', domain: '127.0.0.1' },
{ name: 'admin', value: '', domain: '127.0.0.1', path: '/admin', httpOnly: true, secure: false, sameSite: 'Strict' },
{ name: 'theme', value: 'dark', url: `${origin}/settings`, expires: tomorrow, sameSite: 'Lax' },
{ name: 'lang', value: 'en', url: '/' },
]);
const cookies = (await browser.cookies()).map(({ name, value, path: at, httpOnly, sameSite, expires }) => ({ name, value, at, httpOnly, sameSite, expires }));
expect(cookies.toSorted((a, b) => a.name.localeCompare(b.name))).toEqual([
{ name: 'admin', value: '', at: '/admin', httpOnly: true, sameSite: 'Strict', expires: undefined },
{ name: 'lang', value: 'en', at: '/', httpOnly: false, sameSite: 'Lax', expires: undefined },
{ name: 'session', value: 'root', at: '/', httpOnly: false, sameSite: 'Lax', expires: undefined },
{ name: 'theme', value: 'dark', at: '/', httpOnly: false, sameSite: 'Lax', expires: tomorrow },
]);
});

it('takes back the cookies browser.cookies returns', async () => {
await browser.setCookies([
{ name: 'session', value: 'root', domain: '127.0.0.1', httpOnly: true, sameSite: 'Strict' },
{ name: 'theme', value: 'dark', url: '/settings', expires: Math.floor(Date.now() / 1000) + 86_400 },
]);
const saved = await browser.cookies();
await browser.clearCookies();
await browser.setCookies(saved);
expect(await browser.cookies()).toEqual(saved);
});

const base = { name: 'session', value: 'root', domain: '127.0.0.1' };

it.each<[string, unknown, string]>([
['a single cookie, not an array', base, 'browser.setCookies takes an array of cookies, got an object'],
['a null entry', [null], 'browser.setCookies cookies[0] must be an object, got null'],
['an array entry', [['session', 'root']], 'cookies[0] must be an object, got an array'],
['no url and no domain', [{ name: 'session', value: 'root' }], 'cookies[0] needs a url, or a domain with an optional path'],
['url and domain', [{ ...base, url: '/' }], 'cookies[0] takes url, or domain with an optional path, not both'],
['url and path', [{ name: 'session', value: 'root', url: '/', path: '/admin' }], 'cookies[0] takes url, or domain with an optional path, not both'],
['an empty domain', [{ ...base, domain: '' }], 'cookies[0] domain must be a non-empty string, got ""'],
['a missing name', [{ value: 'root', domain: '127.0.0.1' }], 'cookies[0] name must be a string, got undefined'],
['a number value', [{ ...base, value: 5 }], 'cookies[0] value must be a string, got 5'],
['a string expires', [{ ...base, expires: '1999999999' }], 'cookies[0] expires must be a Unix timestamp in seconds, got "1999999999"'],
['a NaN expires', [{ ...base, expires: Number.NaN }], 'cookies[0] expires must be a Unix timestamp in seconds, got NaN'],
['a string httpOnly', [{ ...base, httpOnly: 'true' }], 'cookies[0] httpOnly must be a boolean, got "true"'],
['a lowercase sameSite', [{ ...base, sameSite: 'strict' }], 'cookies[0] sameSite must be "Strict", "Lax", or "None", got "strict"'],
['an unknown key', [{ ...base, maxAge: 60 }], 'cookies[0] has no key "maxAge"'],
['a bad second cookie', [base, { ...base, sameSite: 'lax' }], 'browser.setCookies cookies[1] sameSite'],
])('refuses %s with INVALID_ARGUMENT, setting nothing', async (_name, cookies, message) => {
expect(() => browser.setCookies(cookies as readonly Cookie[])).toThrow(
expect.objectContaining({ code: 'INVALID_ARGUMENT', message: expect.stringContaining(message) }),
);
expect(await browser.cookies()).toEqual([]);
});
});
Loading