Repository navigation
fix(web): validate browser.setCookies cookies before the browser sees them - #2159
Conversation
There was a problem hiding this comment.
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
…n the array reuse rejectUnknownKeys for unknown keys so a typo like samesite names sameSite
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
[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-expiresonly has to be finite, but Playwright'saddCookiesalso refuses anything below 0 or above 253402300799 (year 9999). The common case is milliseconds:expires: Date.now() + 86_400_000still fails asENGINE_FAILURE: setCookies failed: browserContext.addCookies: Cookie should have a valid expires..., exit 3. Same forexpires: -5. I checked both on this branch. TheCookietype documents seconds, and the docs row this PR adds saysexpiresis validated. Suggest: refuseexpires < 0 || expires > 253_402_300_799with a message along the lines ofexpires 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 theCookietype does not allow (a wrong field type, neither or both ofurlanddomain/path, adomainthat is not a bare host, an unknown key). Nothing is set."isHostNamepasses inputs the URL parser rewrites, like1.2.3(checked as1.2.0.3) or%41.com(checked asa.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
validateCookiescall fails 21 tests, dropping the url+domain rule fails 2,isHostNamealways 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
TestErrorandrejectUnknownKeys, so it moves with one line tofixture/browser.tssetCookiesoncebrowser.tsis gone. #1503'scookieTargetshas the same url+domain drop, so this is needed there too.
There was a problem hiding this comment.
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
|
thanks, fixed in 079ad54.
mutants (no |
There was a problem hiding this comment.
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
Superseded by the latest automated re-check.
okwasniewski
left a comment
There was a problem hiding this comment.
[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
expiresrange: done in 079ad54.isExpirytakes 0 through 253402300799, plus-1. Keeping-1is right: Playwright 1.65.1'saddCookiesrefusesexpires < 0 && expires !== -1and anything abovekMaxCookieExpiresDateInSeconds(253402300799), and this matches it exactly. Rows cover a millisecond value,-5and 253402300800, and a test sets-1and the max. The docs row is shortened and lists "anexpiresthat is not in seconds".- cubic empty-label finding: fixed in c3129f8.
a..example.comand..example.comare refused, andexample.test.is still taken and stored as written. - cubic fractional
expiresfinding: not real, and the author's reply is correct. Playwright takes fractional seconds andbrowser.cookies()floors them. I checked:Date.now() / 1000 + 3600.5sets 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
validateCookiescall removed (same as main) vs this branch, against a real context:domain: 'https://127.0.0.1'is stored as domainhttps, and127.0.0.1:4399/127.0.0.1/appare stored as127.0.0.1path/, all without an error. On this branch all three areINVALID_ARGUMENT. A millisecondexpiresor-5isENGINE_FAILUREon main with Playwright's "unix timestamp in seconds" message, andINVALID_ARGUMENThere. - Mutants: dropping the empty-label check fails 2 tests, the upper bound 2, the
-1allowance 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.
blockedonly 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.
|
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 on scope, the domain part is the real bug. |
There was a problem hiding this comment.
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
|
/ready |
kdy1
left a comment
There was a problem hiding this comment.
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
domainwith 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 domainhttps). TheCookietype allows any string fordomain, so TypeScript users can make this mistake too. - The
Cookietype 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 throughe2e mcp'srun_code. - It follows the convention of the file. Other methods in
browser.tsalready check their arguments at run time and throwINVALID_ARGUMENT:clearCookies(lines 894-898),emulateMedia(lines 910-915), andwaitForDownloads(lines 937-940), withrejectUnknownOptionsfor unknown keys.setCookieswas the exception. The new validator uses the sameTestErrorandrejectUnknownKeyshelpers. - 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 isINVALID_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:178This PR adds the
INVALID_ARGUMENTrow todocs/reference/web.mdxonly. The## Cookiessection ofdocs/browser.mdx(lines 178-180) still namesPOLICY_DENIEDas 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 matchingdocs/**/*.mdxpage 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
expiresmust 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.5is accepted, andbrowser.cookies()returns the value rounded down. The code behavior is acceptable, because Playwright accepts fractional seconds. The description must match the code.
| /** | ||
| * 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) | ||
| ); | ||
| } |
There was a problem hiding this comment.
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.
| 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))}`; | ||
| } |
There was a problem hiding this comment.
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: ''givesENGINE_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'givesENGINE_FAILURE: ... Protocol error (Storage.setCookies): Invalid cookie fields.sameSite: 'None'withoutsecure: trueresolves, 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.
What
browser.setCookieschecks every cookie against theCookietype before the URL rule or the browser sees it, and refuses the first bad one withINVALID_ARGUMENTnaming the index and the field. nothing is set when any cookie is refused.Why
sameSite: 'lax'isENGINE_FAILURE ... cookies[0].sameSite: expected one of (Strict|Lax|None), exit 3urland nodomainisCannot read properties of undefined (reading 'replace')urlplusdomainpluspathpasses, butdomainandpathare dropped, so a session cookie lands on a different scope than the one written and the test runs logged outCookietype alone doesn't catch these.How it works
packages/web/src/cookies.tsvalidateCookies: an array with no holes, of objects with only theCookiekeys (unknown keys go through the sharedrejectUnknownKeys, sosamesitesays did you meansameSite);name/valuestrings;url/pathstrings;domaina bare host that parses back as itself in thehttp://<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.comor a host the parser rewrites (1.2.3,%41.com) is refused while[::1],.example.com, punycode and unicode hosts still work;urlordomain(+ optionalpath) but not both, matching the type's union;expireswhole Unix seconds from 0 through the end of 9999 (what playwright takes), or the-1playwright reads as a session cookie, so a millisecondDate.now() + ...is refused;httpOnly/securebooleans;sameSiteone ofStrict,Lax,None.packages/web/src/browser.tssetCookiescalls it first, so a refusal isINVALID_ARGUMENT(categorytest) and not wrapped bysurface.guardintoENGINE_FAILURE.browser.cookies()only returns keys the type allows, sosetCookies(await browser.cookies())still works. there's a test for that round trip.docs/reference/web.mdx: a throws row undersetCookies.Issue
Fixes #2154
Verified
Ran it locally: yes
the repro on published e2e 0.24.0:
sameSite: 'lax'ENGINE_FAILURE, exit 3INVALID_ARGUMENT: browser.setCookies cookies[0] sameSite must be "Strict", "Lax", or "None", got "lax"url, nodomainERROR: Cannot read properties of undefined (reading 'replace')INVALID_ARGUMENT: ... cookies[0] needs a url, or a domain with an optional pathurl+domain+pathdomain 127.0.0.1 path /INVALID_ARGUMENT: ... cookies[0] takes url, or domain with an optional path, not bothdomain: 'https://127.0.0.1'httpsINVALID_ARGUMENT: ... cookies[0] domain must be a host name like "example.com" or ".example.com"expires: Date.now() + 86_400_000ENGINE_FAILURE: ... Cookie should have a valid expires, exit 3INVALID_ARGUMENT: ... cookies[0] expires must be a Unix timestamp in seconds (not milliseconds), got ...tests/integration/set-cookies.test.tsruns a real browser: every valid shape the type allows is stored as written, a leading-dot, uppercase, punycode, unicode and IPv6 domain,expires: -1and the year 9999 limit, thecookies()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, stringhttpOnly, lowercasesameSite, 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, andprovider-downloadswhich is timing and fails on main too).pnpm checkpasses.Checklist
pnpm changeset) for any change to a published package, or the change is testbed, docs, or CI only.!, the changeset body names what breaks and what replaces it, and the deprecation warning landed a window earlier (stability policy in CONTRIBUTING.md).docs/**/*.mdxpage for the behavior, andskills/e2e/if the skill describes it..d.tsreviewed,tests/types/sdk-types.tsupdated; wire change edits the schema and both fixtures.e2e/engine): changesets fore2e,@e2e-dev/web, and@e2e-dev/mobile.