fix(storage): validate BiDi cookie numeric bounds

This commit is contained in:
ldm0
2026-10-28 19:32:35 +08:00
committed by Donough Liu
parent 7b94c7459e
commit cb930ef5d9
8 changed files with 271 additions and 9 deletions
+6
View File
@@ -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
@@ -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:
+12 -6
View File
@@ -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(
+13 -1
View File
@@ -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<Option<DevToolsCookieFilt
same_site,
size: optional_object_uint(filter, "size")?,
expires: optional_object_uint(filter, "expiry")?
.and_then(|value| i64::try_from(value).ok()),
.map(|value| {
i64::try_from(value).map_err(|_| {
BidiError::new(
BidiErrorCode::InvalidArgument,
"expiry must fit in a signed 64-bit timestamp",
)
})
})
.transpose()?,
}))
}
@@ -1804,6 +1804,78 @@ fn rejects_chromium_wpt_invalid_preload_target_params() {
}
}
#[test]
fn storage_cookie_numeric_fields_reject_values_outside_js_uint() {
for value in [
Value::Null,
json!(true),
json!(-1),
json!(0.5),
json!(9_007_199_254_740_992_u64),
json!(9_223_372_036_854_775_808_u64),
json!(u64::MAX),
] {
for field in ["expiry", "size"] {
for method in ["storage.getCookies", "storage.deleteCookies"] {
assert_bidi_adapter_invalid(method, json!({"filter": {field: value}}));
}
}
assert_bidi_adapter_invalid(
"storage.setCookie",
json!({"cookie": {
"name": "sid", "value": {"type": "string", "value": "keep"},
"domain": "example.test", "expiry": value,
}}),
);
}
}
#[test]
fn storage_cookie_numeric_fields_preserve_valid_js_uint_values() {
use moli_protocol::automation::AutomationCommand;
let context = super::super::BidiDevToolsCommandContext::new("bidi-cookie-numeric");
for (value, expected) in [
(json!(0), 0),
(json!(-0.0), 0),
(json!(1.0), 1),
(json!(9_007_199_254_740_991_u64), 9_007_199_254_740_991),
] {
for method in [
"storage.getCookies",
"storage.deleteCookies",
"storage.setCookie",
] {
let command = super::super::parse_bidi_command(json!({
"id": 304, "method": method, "params": {
"filter": {"size": value, "expiry": value},
"cookie": {"name": "sid", "value": {"type": "string", "value": "keep"}, "domain": "example.test", "expiry": value},
},
})).expect("numeric storage command");
let shared = super::super::automation_command_from_bidi_command(&command, &context)
.expect("valid js-uint");
let filter = match shared {
AutomationCommand::GetCookies(command) => 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
@@ -259,10 +259,18 @@ fn offset_datetime_from_cdp_timestamp(value: f64) -> Option<time::OffsetDateTime
}
let seconds = value.trunc() as i64;
// Chromium caps persistent cookies at 400 days. Clamp before converting
// the timestamp so large, valid protocol values cannot silently become
// session cookies when they exceed OffsetDateTime's supported range.
let latest_expiry = time::OffsetDateTime::now_utc() + time::Duration::days(400);
if seconds > 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!(
+11 -2
View File
@@ -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).
@@ -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"}