From cb930ef5d9045980f6c3fbbd60d21119518fa85d Mon Sep 17 00:00:00 2001 From: ldm0 Date: Wed, 28 Oct 2026 16:42:26 +0800 Subject: [PATCH] fix(storage): validate BiDi cookie numeric bounds --- moli-cdp-smoke/README.md | 6 ++ .../groups/emulation_storage.py | 30 +++++++ moli-protocol-webdriver-bidi/src/commands.rs | 18 ++-- moli-protocol-webdriver-bidi/src/storage.rs | 14 ++- .../tests/script_storage_and_validation.rs | 72 +++++++++++++++ .../src/domains/storage/normalize.rs | 37 ++++++++ moli-webdriver-smoke/README.md | 13 ++- .../groups/bidi_storage.py | 90 +++++++++++++++++++ 8 files changed, 271 insertions(+), 9 deletions(-) diff --git a/moli-cdp-smoke/README.md b/moli-cdp-smoke/README.md index d37d6d1890f..4426e08a063 100644 --- a/moli-cdp-smoke/README.md +++ b/moli-cdp-smoke/README.md @@ -283,6 +283,12 @@ returns `InvalidParams` on initial admission, while its active override Moli additionally locks down the latter state-preservation case in a focused Rust protocol test. +The `emulation-storage` cookie expiry case was calibrated against Chrome for +Testing 156.0.8078.47 on 2026-10-28. It sets short-lived, maximum-safe-integer, +and far-future expiries over raw CDP, then checks that every cookie remains +persistent, short expiries stay unchanged, and large expiries are capped at +400 days rather than losing their expiry during timestamp conversion. + The default `locale-timezone-inputs` group adds input-boundary regressions for PR #369. It was calibrated on 2026-09-10 against `/usr/bin/chromium` 145.0.7632.116 using the group unchanged: four timezone overrides cover Unicode diff --git a/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py b/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py index 823455a3211..76048eddb97 100644 --- a/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py +++ b/moli-cdp-smoke/moli_cdp_smoke/groups/emulation_storage.py @@ -17,6 +17,7 @@ async def run_emulation_storage_group(browser: Any, fixture: str, results: list[ await run_geolocation_override_smoke(browser, fixture, results) await run_locale_timezone_runtime_surface_smoke(browser, fixture, results) await run_storage_and_cookie_isolation_smoke(browser, fixture, results) + await run_cookie_expiry_limit_smoke(browser, fixture, results) await run_indexeddb_baseline_smoke(browser, fixture, results) await run_browser_context_profile_smoke(browser, fixture, results) @@ -536,6 +537,35 @@ async def run_storage_and_cookie_isolation_smoke(browser: Any, fixture: str, res await context_b.close() +async def run_cookie_expiry_limit_smoke(browser: Any, fixture: str, results: list[dict[str, Any]]) -> None: + context = await browser.new_context() + try: + page = await context.new_page() + cdp = await new_cdp_session(context, page) + try: + start = time.time() + near_expiry = int(start) + 3600 + for name, expiry in (("near", near_expiry), ("safeMax", 2**53 - 1), ("farFuture", 1e100)): + response = await cdp.send("Network.setCookie", { + "name": name, "value": "persistent", "url": fixture, "expires": expiry, + }) + assert_equal(response["success"], True, f"CDP {name} cookie write") + cookies = (await cdp.send("Network.getCookies", {"urls": [fixture]}))["cookies"] + finish = time.time() + assert_equal(sorted(cookie["name"] for cookie in cookies), ["farFuture", "near", "safeMax"], "CDP expiry fixture") + for cookie in cookies: + assert_equal(cookie["session"], False, "CDP supplied future expiry remains persistent") + if cookie["name"] == "near": + assert_equal(cookie["expires"], near_expiry, "CDP short expiry is unchanged") + elif not start + 400 * 86400 <= cookie["expires"] <= finish + 400 * 86400: + raise SmokeError(f"CDP {cookie['name']} expiry was not capped at 400 days: {cookie}") + record(results, "cookie_expiry_persistence_and_lifetime_limit", {"maximumLifetimeDays": 400}) + finally: + await cdp.detach() + finally: + await context.close() + + async def run_indexeddb_baseline_smoke(browser: Any, fixture: str, results: list[dict[str, Any]]) -> None: context = await browser.new_context() try: diff --git a/moli-protocol-webdriver-bidi/src/commands.rs b/moli-protocol-webdriver-bidi/src/commands.rs index 356e4943b89..468c67f8fd0 100644 --- a/moli-protocol-webdriver-bidi/src/commands.rs +++ b/moli-protocol-webdriver-bidi/src/commands.rs @@ -3098,12 +3098,18 @@ pub(crate) fn optional_object_uint( let Some(value) = params.get(field) else { return Ok(None); }; - value.as_u64().map(Some).ok_or_else(|| { - BidiError::new( - BidiErrorCode::InvalidArgument, - format!("{field} must be a uint"), - ) - }) + // BiDi js-uint is a JavaScript safe integer, not the full Rust u64 + // range. Integer-valued JSON numbers such as 1.0 are valid as well. + value + .as_f64() + .filter(|value| (0.0..=MAX_SAFE_INTEGER as f64).contains(value) && value.fract() == 0.0) + .map(|value| Some(value as u64)) + .ok_or_else(|| { + BidiError::new( + BidiErrorCode::InvalidArgument, + format!("{field} must be an integer between 0 and {MAX_SAFE_INTEGER}"), + ) + }) } pub(crate) fn required_network_bytes_value( diff --git a/moli-protocol-webdriver-bidi/src/storage.rs b/moli-protocol-webdriver-bidi/src/storage.rs index 51cc144c204..5baac735066 100644 --- a/moli-protocol-webdriver-bidi/src/storage.rs +++ b/moli-protocol-webdriver-bidi/src/storage.rs @@ -206,6 +206,10 @@ fn bidi_storage_partition( "sourceOrigin must be a valid absolute URL", ) })?; + // Chrome's BiDi storage descriptor retains the hostname, + // including subdomains, and compares it to the serialized + // cookie site. Canonicalizing to eTLD+1 here would broaden + // get/delete beyond Chrome's selection. Ok(format!( "{}://{}", url.scheme(), @@ -257,7 +261,15 @@ fn bidi_cookie_filter(value: Option<&Value>) -> Result command.filter.expect("cookie filter"), + AutomationCommand::DeleteCookies(command) => { + let moli_protocol::automation::DevToolsCookieDeleteFilter::Properties(filter) = + command.filter + else { + panic!("BiDi property filter"); + }; + filter + } + AutomationCommand::SetCookies(command) => { + assert_eq!(command.cookies[0].expires, Some(expected as f64)); + continue; + } + _ => panic!("storage command"), + }; + assert_eq!(filter.size, Some(expected as u64)); + assert_eq!(filter.expires, Some(expected)); + } + } +} + #[test] fn rejects_chromium_wpt_invalid_storage_cookie_params() { // Mirrors the adapter-level invalid.py cases from Chromium's vendored diff --git a/moli-protocol/src/domains/storage/normalize.rs b/moli-protocol/src/domains/storage/normalize.rs index a928a977222..9d80c01d92a 100644 --- a/moli-protocol/src/domains/storage/normalize.rs +++ b/moli-protocol/src/domains/storage/normalize.rs @@ -259,10 +259,18 @@ fn offset_datetime_from_cdp_timestamp(value: f64) -> Option latest_expiry.unix_timestamp() { + return Some(latest_expiry); + } let nanos = ((value.fract()) * 1_000_000_000.0).round() as i64; time::OffsetDateTime::from_unix_timestamp(seconds) .ok() .and_then(|dt| dt.checked_add(time::Duration::nanoseconds(nanos))) + .map(|dt| dt.min(latest_expiry)) } #[cfg(test)] @@ -274,6 +282,35 @@ mod tests { stored_cookie_source_scheme_from_cdp, }; + #[test] + fn cdp_cookie_expiry_preserves_persistence_and_caps_the_lifetime() { + use super::offset_datetime_from_cdp_timestamp; + use time::{Duration, OffsetDateTime}; + + let start = OffsetDateTime::now_utc(); + let near_expiry = start.unix_timestamp() + Duration::days(1).whole_seconds(); + assert_eq!( + offset_datetime_from_cdp_timestamp(near_expiry as f64) + .expect("near expiry") + .unix_timestamp(), + near_expiry + ); + for timestamp in [9_007_199_254_740_991.0, f64::MAX] { + let expiry = offset_datetime_from_cdp_timestamp(timestamp).expect("persistent expiry"); + assert!(expiry >= start + Duration::days(400)); + assert!(expiry <= OffsetDateTime::now_utc() + Duration::days(400)); + } + assert_eq!( + offset_datetime_from_cdp_timestamp(0.0) + .expect("expired persistent cookie") + .unix_timestamp(), + 0 + ); + for timestamp in [-1.0, f64::NAN, f64::INFINITY] { + assert_eq!(offset_datetime_from_cdp_timestamp(timestamp), None); + } + } + #[test] fn cdp_cookie_same_site_tokens_are_derived_and_case_sensitive() { assert_eq!( diff --git a/moli-webdriver-smoke/README.md b/moli-webdriver-smoke/README.md index f2a5e062b4a..e8fd01d1656 100644 --- a/moli-webdriver-smoke/README.md +++ b/moli-webdriver-smoke/README.md @@ -67,7 +67,7 @@ non-yielding WebDriver timeout behavior. `emulation.setUserAgentOverride`, `emulation.setLocaleOverride`, `emulation.setTimezoneOverride`, `emulation.setNetworkConditions`, storage isolation, `storage.setCookie`, `storage.getCookies`, and `session.end`. - Thirty `bidi-storage` scenarios cover value, compound attribute, size, + Thirty-seven `bidi-storage` scenarios cover value, compound attribute, size, exact-path and expiry filters, non-ASCII string values, no matches, and empty/omitted filters that clear all cookies. Each scenario creates one unpartitioned cookie via `storage.setCookie` and two CHIPS cookies via real HTTP `Set-Cookie` responses (including a cross-site @@ -80,7 +80,16 @@ non-yielding WebDriver timeout behavior. malformed origins, invalid flags, missing user contexts and missing browsing contexts. Invalid commands must preserve every stored cookie. Writes target the supplied cookie domain even when the active document is on another site. - The identical thirty scenarios passed against Chrome for Testing and ChromeDriver + Numeric cases enforce the `js-uint` range (0 through 2^53-1), reject invalid + expiry/size values without changing any cookies, accept integer-valued JSON + numbers such as `21.0`, and preserve valid unmatched filters at the upper bound. + A maximum-safe expiry write remains persistent with Chrome's 400-day cap. + Subdomain cases retain Chrome's distinction between the descriptor's normalized + origin and the cookie's canonical site: writing with `https://shop.example.com` + creates a cookie at `https://example.com`, while querying or deleting with the + original subdomain matches nothing. This behavior is checked against Chrome + rather than inferred from the storage-key helper's canonicalization rules. + The identical thirty-seven scenarios passed against Chrome for Testing and ChromeDriver 156.0.8078.47 on 2026-10-28. The returned partition key is checked for consistency between `getCookies` and `deleteCookies`; its supported fields can vary by engine under the [WebDriver BiDi storage contract](https://www.w3.org/TR/webdriver-bidi/#module-storage). diff --git a/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi_storage.py b/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi_storage.py index 85f03dc9c6e..3e4a0dcf155 100644 --- a/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi_storage.py +++ b/moli-webdriver-smoke/moli_webdriver_smoke/groups/bidi_storage.py @@ -2,6 +2,7 @@ from __future__ import annotations import asyncio import json +import math import time from dataclasses import dataclass from functools import partial @@ -138,6 +139,10 @@ def _bidi_storage_scenarios() -> tuple[tuple[str, BidiScenario], ...]: "site", "file", "ancestor_without_origin", "opaque", )), (_check_cookie_attribute, "delete", ("expiry", "unicode_value")), + (_check_cookie_numeric_invalid, "numeric_invalid", ("expiry", "size")), + (_check_cookie_numeric_filter, "numeric_filter", ("expiry_max", "size_max", "integer_notation")), + (_check_cookie_expiry_limit, "expiry", ("lifetime_limit",)), + (_check_storage_key_subdomain, "storage_key", ("subdomain",)), ) return scenarios + tuple( ( @@ -432,3 +437,88 @@ async def _check_cookie_attribute(env: CookieFixture, *, kind: str) -> dict[str, expected = [cookie for cookie in before if cookie["value"]["value"] != target] assert_equal(await env.cookies(), expected, f"BiDi {kind} preserves all unselected identities") return {"selectedValue": target} + + +async def _check_cookie_numeric_invalid(env: CookieFixture, *, kind: str) -> dict[str, Any]: + methods = ("storage.getCookies", "storage.deleteCookies") + if kind == "expiry": + methods += ("storage.setCookie",) + invalid_values = (None, True, -1, 0.5, 2**53, 2**63, 2**64 - 1) + for value in invalid_values: + for method in methods: + params: dict[str, Any] = {"partition": env.partition} + if method == "storage.setCookie": + params["cookie"] = { + "name": "bidiDeleteSmoke", "value": {"type": "string", "value": "must-not-write"}, + "domain": "127.0.0.1", "path": "/", "secure": True, "sameSite": "none", "expiry": value, + } + else: + params["filter"] = {kind: value} + await env.command(method, params, expected_error="invalid argument") + assert_equal(await env.cookies(), env.before, f"BiDi {method} invalid {kind}={value!r} preserves every cookie") + return {"error": "invalid argument", "commandsChecked": len(methods) * len(invalid_values)} + + +async def _check_cookie_numeric_filter(env: CookieFixture, *, kind: str) -> dict[str, Any]: + values: tuple[str, ...] = () + if kind == "integer_notation": + # JSON 21.0 and 21 describe the same JavaScript integer. Use a size + # that actually matches two partitioned cookies, rather than only + # verifying acceptance of a filter which selects nothing. + cookie_filter = {"size": float(len("bidiDeleteSmoke") + len("part-a"))} + values = ("part-a", "part-b") + else: + cookie_filter = {kind.removesuffix("_max"): 2**53 - 1} + params = {"partition": env.partition, "filter": cookie_filter} + selected = await env.command("storage.getCookies", params) + assert_equal(sorted(cookie["value"]["value"] for cookie in selected["cookies"]), sorted(values), f"BiDi {kind} numeric filter") + await env.command("storage.deleteCookies", params) + expected = [cookie for cookie in env.before if cookie["value"]["value"] not in values] + assert_equal(await env.cookies(), expected, f"BiDi {kind} preserves every unselected cookie") + return {"selectedValues": list(values)} + + +async def _check_cookie_expiry_limit(env: CookieFixture, *, kind: str) -> dict[str, Any]: + lifetime = 400 * 24 * 60 * 60 + start = time.time() + await env.command("storage.setCookie", { + "partition": env.partition, + "cookie": { + "name": "bidiExpiryLimit", "value": {"type": "string", "value": "persistent"}, + "domain": "127.0.0.1", "path": "/", "secure": True, "sameSite": "none", "expiry": 2**53 - 1, + }, + }) + after = await env.cookies() + finish = time.time() + created = [cookie for cookie in after if cookie["name"] == "bidiExpiryLimit"] + assert_equal(len(created), 1, "BiDi maximum safe expiry creates one cookie") + # BiDi reports integer seconds; Chrome rounds the CDP fractional expiry. + # Use the enclosing integer interval so rounding across a second remains + # valid. The raw CDP smoke checks the original, unrounded time interval. + minimum, maximum = math.floor(start + lifetime), math.ceil(finish + lifetime) + assert_true(minimum <= created[0].get("expiry", -1) <= maximum, f"BiDi maximum safe expiry remains persistent and is capped at 400 days: {created[0]!r}, bounds=({minimum}, {maximum})") + assert_equal([cookie for cookie in after if cookie["name"] != "bidiExpiryLimit"], env.before, "BiDi maximum safe expiry preserves existing cookies") + return {"maximumLifetimeDays": 400} + + +async def _check_storage_key_subdomain(env: CookieFixture, *, kind: str) -> dict[str, Any]: + cookie = { + "name": "bidiSubdomain", "value": {"type": "string", "value": "partitioned"}, + "domain": "127.0.0.1", "path": "/", "secure": True, "sameSite": "none", + } + subdomain = env.storage_key(sourceOrigin="https://shop.example.com:8443/path?query=yes") + canonical = env.storage_key(sourceOrigin="https://example.com") + written = await env.command("storage.setCookie", {"partition": subdomain, "cookie": cookie}) + expanded = {"userContext": env.user_context, "sourceOrigin": "https://shop.example.com"} + assert_equal(written["partitionKey"], expanded, "BiDi set echoes normalized origin with subdomain intact") + before = await env.cookies() + assert_equal(len(before), len(env.before) + 1, "BiDi subdomain fixture creates one partitioned cookie") + for descriptor, values in ((subdomain, []), (canonical, ["partitioned"])): + selected = await env.command("storage.getCookies", {"partition": descriptor}) + assert_equal([cookie["value"]["value"] for cookie in selected["cookies"]], values, "BiDi sourceOrigin matches the stored serialized site exactly") + deleted = await env.command("storage.deleteCookies", {"partition": subdomain}) + assert_equal(deleted["partitionKey"], expanded, "BiDi subdomain delete keeps the original origin") + assert_equal(await env.cookies(), before, "BiDi subdomain deletion must not broaden to the registrable site") + await env.command("storage.deleteCookies", {"partition": canonical}) + assert_equal(await env.cookies(), env.before, "BiDi registrable-site deletion removes only its cookie") + return {"sourceOrigin": expanded["sourceOrigin"], "storedSite": "https://example.com"}