Skip to content

fix(web): validate browser.setCookies cookies before the browser sees them - #2159

Merged
kdy1 merged 6 commits into
e2e-inc:mainfrom
kunalgoesbyken:fix/set-cookies-validation
Nov 24, 2026
Merged

kdy1 merged 6 commits into
e2e-inc:mainfrom
kunalgoesbyken:fix/set-cookies-validation

Conversation

@kunalgoesbyken

@kunalgoesbyken kunalgoesbyken commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

What

  • browser.setCookies checks every cookie against the Cookie type before the URL rule or the browser sees it, and refuses the first bad one with INVALID_ARGUMENT naming the index and the field. nothing is set when any cookie is refused.
  • the docs already said it "validates every cookie, then sets them", this makes that true.

Why

  • on main the cookies go to playwright unchecked:
    • sameSite: 'lax' is ENGINE_FAILURE ... cookies[0].sameSite: expected one of (Strict|Lax|None), exit 3
    • no url and no domain is Cannot read properties of undefined (reading 'replace')
    • url plus domain plus path passes, but domain and path are dropped, so a session cookie lands on a different scope than the one written and the test runs logged out
  • tests can be plain js and fixture data isn't typed, so the Cookie type alone doesn't catch these.

How it works

  1. new packages/web/src/cookies.ts validateCookies: an array with no holes, of objects with only the Cookie keys (unknown keys go through the shared rejectUnknownKeys, so samesite says did you mean sameSite); name / value strings; url / path strings; domain a bare host that parses back as itself in the http://<domain> origin the URL rule checks, changed at most in case or to punycode and with no empty label, so a scheme, port, path, space, a..b.com or a host the parser rewrites (1.2.3, %41.com) is refused while [::1], .example.com, punycode and unicode hosts still work; url or domain (+ optional path) but not both, matching the type's union; expires whole Unix seconds from 0 through the end of 9999 (what playwright takes), or the -1 playwright reads as a session cookie, so a millisecond Date.now() + ... is refused; httpOnly / secure booleans; sameSite one of Strict, Lax, None.
  2. packages/web/src/browser.ts setCookies calls it first, so a refusal is INVALID_ARGUMENT (category test) and not wrapped by surface.guard into ENGINE_FAILURE.
  3. browser.cookies() only returns keys the type allows, so setCookies(await browser.cookies()) still works. there's a test for that round trip.
  4. docs/reference/web.mdx: a throws row under setCookies.

Issue

Fixes #2154

Verified

Ran it locally: yes

the repro on published e2e 0.24.0:

main this PR
sameSite: 'lax' ENGINE_FAILURE, exit 3 INVALID_ARGUMENT: browser.setCookies cookies[0] sameSite must be "Strict", "Lax", or "None", got "lax"
no url, no domain ERROR: Cannot read properties of undefined (reading 'replace') INVALID_ARGUMENT: ... cookies[0] needs a url, or a domain with an optional path
url + domain + path passes, stored as domain 127.0.0.1 path / INVALID_ARGUMENT: ... cookies[0] takes url, or domain with an optional path, not both
domain: 'https://127.0.0.1' passes, stored as domain https INVALID_ARGUMENT: ... cookies[0] domain must be a host name like "example.com" or ".example.com"
expires: Date.now() + 86_400_000 ENGINE_FAILURE: ... Cookie should have a valid expires, exit 3 INVALID_ARGUMENT: ... cookies[0] expires must be a Unix timestamp in seconds (not milliseconds), got ...

tests/integration/set-cookies.test.ts runs a real browser: every valid shape the type allows is stored as written, a leading-dot, uppercase, punycode, unicode and IPv6 domain, expires: -1 and the year 9999 limit, the cookies() round trip, and 26 refused inputs (not an array, null / array entries, a hole, no target, url+domain, url+path, an empty domain or one with a scheme / path / port / space or one the parser rewrites or with an empty label, missing name, number value, string / NaN / millisecond / negative / past-9999 expires, string httpOnly, lowercase sameSite, unknown and misspelled keys, a bad second cookie), each checking no cookie was set. the refused ones fail on main. mutants (no -1, exclusive max, no lower or upper bound, no rewrite check, no punycode allowance) each fail at least one test.

pnpm --filter @e2e-dev/web test: the failures are the same as on main for me on Windows (install.test.ts, the SIGTERM cli test, and provider-downloads which is timing and fails on main too). pnpm check passes.

Checklist

  • Changeset added (pnpm changeset) for any change to a published package, or the change is testbed, docs, or CI only.
  • Breaking change: title carries !, the changeset body names what breaks and what replaces it, and the deprecation warning landed a window earlier (stability policy in CONTRIBUTING.md).
  • Docs updated in the same PR: the docs/**/*.mdx page for the behavior, and skills/e2e/ if the skill describes it.
  • Contract change: emitted .d.ts reviewed, tests/types/sdk-types.ts updated; wire change edits the schema and both fixtures.
  • Engine contract change (e2e/engine): changesets for e2e, @e2e-dev/web, and @e2e-dev/mobile.

@github-actions github-actions Bot added the size:M Up to 99 changed lines, not counting tests, fixtures, translated docs, or the lockfile label Nov 23, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 5 files

Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.

View guided diff | Re-trigger cubic

Comment thread packages/web/src/cookies.ts Resolved
Comment thread packages/web/src/cookies.ts Resolved
…n the array

reuse rejectUnknownKeys for unknown keys so a typo like samesite names sameSite

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

0 issues found across 3 files (changes from recent commits).

Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.

View guided diff | Re-trigger cubic

@okwasniewski okwasniewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[claude-opus-5-5] automated review on behalf of @okwasniewski

Reviewed at 5dbadf3 against main 97b51a2. Repro is real on main: lowercase sameSite is ENGINE_FAILURE exit 3, a cookie with no target is a bare TypeError, and url + domain/path drops domain and path without a word (Playwright refuses that pair itself, e2e drops the fields before Playwright sees them). The check is in the right place: a driver-free validator ahead of the URL rule, same sync-throw shape as clearCookies and emulateMedia. Tests are good. One gap left in the same class.

Must fix

  • packages/web/src/cookies.ts:48 - expires only has to be finite, but Playwright's addCookies also refuses anything below 0 or above 253402300799 (year 9999). The common case is milliseconds: expires: Date.now() + 86_400_000 still fails as ENGINE_FAILURE: setCookies failed: browserContext.addCookies: Cookie should have a valid expires..., exit 3. Same for expires: -5. I checked both on this branch. The Cookie type documents seconds, and the docs row this PR adds says expires is validated. Suggest: refuse expires < 0 || expires > 253_402_300_799 with a message along the lines of expires must be a Unix timestamp in seconds (not milliseconds), got .... Add rows for a millisecond value and a negative one, and update the docs row.

Nits

  • docs/reference/web.mdx:889 - the throws row lists every field. Shorter works: "Not an array, or a cookie the Cookie type does not allow (a wrong field type, neither or both of url and domain/path, a domain that is not a bare host, an unknown key). Nothing is set."
  • isHostName passes inputs the URL parser rewrites, like 1.2.3 (checked as 1.2.0.3) or %41.com (checked as a.com), so the URL rule checks a different host than the cookie gets. Edge case only, fine to leave.

Verified

  • vitest run tests/integration/set-cookies.test.ts: 24/24 pass.
  • Mutants: dropping the validateCookies call fails 21 tests, dropping the url+domain rule fails 2, isHostName always true fails 5, skipping holes fails 1.
  • oxlint is clean on the touched files. tsc shows no errors in them.
  • CI is green at this head. Both cubic findings were fixed in 7422ee0 and are real fixes.
  • Carries over to #1503: the validator only uses TestError and rejectUnknownKeys, so it moves with one line to fixture/browser.ts setCookies once browser.ts is gone. #1503's cookieTargets has the same url+domain drop, so this is needed there too.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

All reported issues were addressed across 4 files (changes from recent commits).

Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.

View guided diff | Re-trigger cubic

Comment thread packages/web/src/cookies.ts Resolved
Comment thread packages/web/src/cookies.ts Resolved
@kunalgoesbyken

Copy link
Copy Markdown
Contributor Author

thanks, fixed in 079ad54.

  • expires: refused outside 0 through 253402300799 with expires must be a Unix timestamp in seconds (not milliseconds), got .... one change from the suggestion: -1 is still taken, playwright reads it as a session cookie (its addCookies check is expires < 0 && expires !== -1). rows for a millisecond value, -5 and 253402300800, and a test that sets -1 and the year 9999 max.
  • docs row: shortened the way you wrote it, plus "an expires that is not in seconds".
  • isHostName: fixed that too. the host has to come back from the url parser changed only in case or to punycode, so 1.2.3 and %41.com are refused. punycode, unicode, uppercase and [::1] hosts still work, and the test checks what they're stored as.
  • changeset trimmed to its first sentence.

mutants (no -1, exclusive max, no lower or upper bound, no rewrite check, no punycode allowance) each fail at least one test.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

0 issues found across 2 files (changes from recent commits).

Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.

Requires human review: Auto-approval blocked by 1 unresolved issue from previous reviews.

View guided diff | Re-trigger cubic

@okwasniewski
okwasniewski dismissed their stale review November 24, 2026 04:16

Superseded by the latest automated re-check.

@okwasniewski okwasniewski left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[claude-opus-5-5] automated review on behalf of @okwasniewski

Re-checked at c3129f8 against main 51cbd2e. The earlier ask is done, and so are both later cubic findings.

Earlier ask

  • expires range: done in 079ad54. isExpiry takes 0 through 253402300799, plus -1. Keeping -1 is right: Playwright 1.65.1's addCookies refuses expires < 0 && expires !== -1 and anything above kMaxCookieExpiresDateInSeconds (253402300799), and this matches it exactly. Rows cover a millisecond value, -5 and 253402300800, and a test sets -1 and the max. The docs row is shortened and lists "an expires that is not in seconds".
  • cubic empty-label finding: fixed in c3129f8. a..example.com and ..example.com are refused, and example.test. is still taken and stored as written.
  • cubic fractional expires finding: not real, and the author's reply is correct. Playwright takes fractional seconds and browser.cookies() floors them. I checked: Date.now() / 1000 + 3600.5 sets fine on this branch.

Nits

  • packages/web/src/cookies.ts:83 - url.href === \http://${url.hostname}/`can never be the deciding check. Any scheme, port, path, userinfo or space also makesurl.hostnamediffer fromwritten`, so the rewrite check below already refuses it. With this line deleted, all 37 tests still pass. Drop it and remove "A scheme, port, path, or whitespace would be dropped" from the doc comment, or keep it as a belt and say so.

Verified

  • vitest run tests/integration/set-cookies.test.ts: 37/37 pass.
  • Behavior with the validateCookies call removed (same as main) vs this branch, against a real context: domain: 'https://127.0.0.1' is stored as domain https, and 127.0.0.1:4399 / 127.0.0.1/app are stored as 127.0.0.1 path /, all without an error. On this branch all three are INVALID_ARGUMENT. A millisecond expires or -5 is ENGINE_FAILURE on main with Playwright's "unix timestamp in seconds" message, and INVALID_ARGUMENT here.
  • Mutants: dropping the empty-label check fails 2 tests, the upper bound 2, the -1 allowance 1, the rewrite check 2, the url+domain rule 2. Dropping the href check fails none (nit above).
  • oxlint is clean on the touched files. tsc shows no errors in them.
  • CI is green at c3129f8. mergeable is true. blocked only reflects the standing change request.

Waiting on a maintainer scope call (not on you). The code is ready. Most of what the validator checks (wrong field types, lowercase sameSite, url + domain, no target, not an array) is already refused by the Cookie type, and a millisecond expires already fails loudly on main with Playwright's own "seconds" message. The part only this PR catches for typed code is a domain with a scheme, port or path, which main stores wrong without an error. A maintainer will decide whether to land the whole validator or only the domain and expires checks.

@kunalgoesbyken

Copy link
Copy Markdown
Contributor Author

dropped the href line in ffcb393, and the bit of the doc comment that went with it. you're right that it never decided anything: a scheme, port, path, userinfo or stray whitespace all change url.hostname, so the rewrite check refuses them anyway. 37/37 still pass.

on scope, the domain part is the real bug. https://127.0.0.1, 127.0.0.1:4399 and 127.0.0.1/app all get stored wrong on main without an error. if you'd rather land only the domain and expires checks, i can cut it down to those and drop the rest of the validator, just say the word

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

0 issues found across 1 file (changes from recent commits).

Heads up: you’ve reached your flex budget. Increase your flex budget or wait for usage to reset.

View guided diff | Re-trigger cubic

@kunalgoesbyken

Copy link
Copy Markdown
Contributor Author

/ready

@github-actions github-actions Bot added the Ready for Human Review Green, conflict-free, every thread handled. Waiting on a maintainer. label Nov 24, 2026

@kdy1 kdy1 left a comment

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.

Note

This text was drafted with AI and posted after human approval.

  • Harness: T3 Code
  • AI agents: coordinator: Claude Opus 5.5 (claude-opus-5-5), reviewer: GPT-6.2 Astra (gpt-6.2-astra), reviewer: GPT-6.2 Sol (gpt-6.2-sol), reviewer: Claude Opus 5.5 (claude-opus-5-5), reviewer: Claude Sonnet 5.5 (claude-sonnet-5-5)

Verdict: Approve

This review approves the pull request. The P3 items are optional and do not block the merge.

This PR adds validateCookies, which runs first in browser.setCookies and refuses a malformed cookie with INVALID_ARGUMENT before Playwright sees it. I ran the same inputs on main (the validateCookies call removed) and on this head against a real Chromium context. All five cases in the PR table are fixed: lowercase sameSite, no target, url with domain/path, a domain with a scheme, and a millisecond expires. set-cookies.test.ts and clear-cookies.test.ts pass (43/43).

Reasons for the approval:

  • It fixes a silent bug that types do not catch. On main, a domain with a scheme or a path is stored with a wrong domain or path, and there is no error (domain: 'https://127.0.0.1' is stored as domain https). The Cookie type allows any string for domain, so TypeScript users can make this mistake too.
  • The Cookie type is not a guard at run time. The runner never type-checks (docs/reference/config.mdx:1543): it removes the types and runs the file. Cookies also come from untyped sources, for example saved cookies read from JSON and JavaScript that a coding agent runs through e2e mcp's run_code.
  • It follows the convention of the file. Other methods in browser.ts already check their arguments at run time and throw INVALID_ARGUMENT: clearCookies (lines 894-898), emulateMedia (lines 910-915), and waitForDownloads (lines 937-940), with rejectUnknownOptions for unknown keys. setCookies was the exception. The new validator uses the same TestError and rejectUnknownKeys helpers.
  • The error category becomes correct. On main, a test's cookie mistake is ENGINE_FAILURE, category infrastructure, exit 3. That code takes precedence over exit 1 in a run, so CI shows the failure as an infrastructure fault. With this PR it is INVALID_ARGUMENT, category test, exit 1.

I found only small items, listed below. None of them blocks the merge.

Reviewed commit: ffcb3931bf8e07b1975fe0a96dd108f0775212c7

  • P3 (non-blocking): 4 (2 inline)

Items that cannot be inline

  • P3 · Non-blocking · The Cookies section of the browser guide still lists only POLICY_DENIED — docs/browser.mdx:178

    This PR adds the INVALID_ARGUMENT row to docs/reference/web.mdx only. The ## Cookies section of docs/browser.mdx (lines 178-180) still names POLICY_DENIED as the only refusal. A reader of the guide does not learn that a malformed cookie now fails before anything is set. AGENTS.md says that a behavior change updates the matching docs/**/*.mdx page in the same change.

  • P3 · Non-blocking · The PR description says expires must be whole seconds, but the code accepts fractions — the whole change

    Step 1 of "How it works" says that expires must be "whole Unix seconds from 0 through the end of 9999". isExpiry (packages/web/src/cookies.ts:66) checks only the range. On main and on this head, expires: Math.floor(Date.now() / 1000) + 300.5 is accepted, and browser.cookies() returns the value rounded down. The code behavior is acceptable, because Playwright accepts fractional seconds. The description must match the code.

Comment on lines +69 to +86
/**
* Whether `domain`, less a leading dot, parses back as only that host in the
* origin `setCookies` checks it under, changed at most in case or to punycode,
* with no empty label but a trailing dot's. A host the parser rewrites
* (`1.2.3` to `1.2.0.3`, `%41.com` to `a.com`) would put the URL rule on
* another host than the cookie's.
*/
function isHostName(domain: string): boolean {
const host = domain.replace(/^\./, '');
if (!URL.canParse(`http://${host}`)) return false;
const url = new URL(`http://${host}`);
const written = host.toLowerCase();
const labels = url.hostname.replace(/\.$/, '').split('.');
return (
!labels.includes('') &&
(url.hostname === written || domainToUnicode(url.hostname) === written)
);
}

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 · The domain check refuses host spellings that main stored correctly, and its comment gives a wrong reason

Optional. This does not block the merge.

isHostName refuses every host that the URL parser changes in a way other than case or punycode. Some of these hosts worked on main. Results on main and on this head, against a real Chromium context:

domain main this head
[2001:0db8:0000:0000:0000:0000:0000:0001] stored as [2001:db8::1] INVALID_ARGUMENT
café.xn--bcher-kva.example stored as xn--caf-dma.xn--bcher-kva.example INVALID_ARGUMENT
127.0.0.1. stored as 127.0.0.1 INVALID_ARGUMENT
example.test. stored as example.test. stored as example.test.

The last two rows are not consistent: the head accepts a trailing dot on a DNS name but refuses one on an IPv4 address.

The cookies() round trip also fails in one case. Set { url: 'http://a..example.com/' }, read it back with browser.cookies(), which returns domain: 'a..example.com', clear the cookies, and call setCookies(saved). Main restores the cookie. This head throws INVALID_ARGUMENT.

The doc comment (lines 69-75) says that a rewritten host "would put the URL rule on another host than the cookie's". The URL rule in setCookies checks only the scheme (browser.ts:870), and AGENTS.md says that there is no origin or host allowlist. So a host mismatch has no effect on what the rule admits. If these spellings are refused only to catch probable typos, the comment and the PR description must give that reason.

These inputs are rare, and the error message is clear, so the impact is small.

Comment on lines +39 to +41
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))}`;
}

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.

@kdy1
kdy1 added this pull request to the merge queue Nov 24, 2026
Merged via the queue into e2e-inc:main with commit 4378e24 Nov 24, 2026
31 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Ready for Human Review Green, conflict-free, every thread handled. Waiting on a maintainer. size:M Up to 99 changed lines, not counting tests, fixtures, translated docs, or the lockfile

Projects

None yet

Development

Successfully merging this pull request may close these issues.

browser.setCookies doesn't validate cookies: ENGINE_FAILURE, TypeError, and silently dropped domain/path

3 participants