Repository navigation
fix(web): validate browser.setCookies cookies before the browser sees them #2159
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 1 commit
2e2ff31
7422ee0
5dbadf3
079ad54
c3129f8
ffcb393
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| 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. |
| 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) => { | ||
| 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
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
The |
||
| const domain = field('domain'); | ||
| if (domain !== undefined && (typeof domain !== 'string' || domain.trim() === '')) { | ||
|
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; | ||
| } | ||
| 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([]); | ||
| }); | ||
| }); |
Uh oh!
There was an error while loading. Please reload this page.