Skip to content

The headless browser for AI agents and web scraping

fix(net): canonicalize the cookie domain on every jar key

aech892398a8084d
diff --git a/crates/obscura-mcp/src/lib.rs b/crates/obscura-mcp/src/lib.rs
index e45e1a2d..13cc98bf 100644
--- a/crates/obscura-mcp/src/lib.rs
+++ b/crates/obscura-mcp/src/lib.rs
@@ -1300,7 +1300,7 @@ fn tool_get_cookies(args: &Value, state: &BrowserState) -> Result<String, String
let domain_filter = args.get("domain").and_then(Value::as_str);
let cookies = state.context.cookie_jar.get_all_cookies();
let lines: Vec<String> = cookies.iter()
- .filter(|c| domain_filter.is_none_or(|d| c.domain == d || c.domain.trim_start_matches('.') == d))
+ .filter(|c| domain_filter.is_none_or(|d| c.domain == obscura_net::canonical_domain(d)))
.map(|c| serde_json::to_string(&json!({
"name": c.name,
"value": c.value,
diff --git a/crates/obscura-net/src/cookies.rs b/crates/obscura-net/src/cookies.rs
index e35758fc..b1c6ed5a 100644
--- a/crates/obscura-net/src/cookies.rs
+++ b/crates/obscura-net/src/cookies.rs
@@ -16,6 +16,14 @@ fn normalize_same_site(value: &str) -> String {
.to_string()
}
+/// The jar key for a domain. RFC 6265 4.1.2.3 ignores a leading dot, and hosts are
+/// case-insensitive, so both spellings have to collapse before they reach the map.
+/// Not intended for `domain_matches`, which compares without allocating on the
+/// per-request path.
+pub fn canonical_domain(domain: &str) -> String {
+ domain.trim().trim_start_matches('.').to_lowercase()
+}
+
pub struct CookieJar {
/// domain -> (name, path) -> entry. RFC 6265 §5.3 identifies a cookie by
/// (name, domain, path); the outer map scopes by domain and the inner key
@@ -70,7 +78,7 @@ impl CookieJar {
if let Some((key, val)) = attr.split_once('=') {
match key.trim().to_lowercase().as_str() {
"domain" => {
- domain_attr = Some(val.trim().trim_start_matches('.').to_lowercase());
+ domain_attr = Some(canonical_domain(val));
}
"path" => {
path = val.trim().to_string();
@@ -219,20 +227,16 @@ impl CookieJar {
.unwrap_or_default()
.as_secs() as i64;
for cookie in cookies {
+ // RFC 6265 4.1.2.3: the leading dot is ignored. The Set-Cookie path already strips
+ // it, but this code did not, which is why one cookie became two entries.
+ let domain = canonical_domain(&cookie.domain);
if cookie.expires.is_some_and(|expires| {
expires == 0 || (expires > 0 && expires <= now)
}) {
- let domains_to_try = [
- cookie.domain.clone(),
- format!(".{}", cookie.domain.trim_start_matches('.')),
- cookie.domain.trim_start_matches('.').to_string(),
- ];
- for domain in &domains_to_try {
- if let Some(domain_cookies) = jar.get_mut(domain) {
- domain_cookies.retain(|_key, entry| {
- entry.name != cookie.name || entry.path != cookie.path
- });
- }
+ if let Some(domain_cookies) = jar.get_mut(&domain) {
+ domain_cookies.retain(|_key, entry| {
+ entry.name != cookie.name || entry.path != cookie.path
+ });
}
continue;
}
@@ -246,7 +250,7 @@ impl CookieJar {
name: cookie.name.clone(),
value: cookie.value,
path: cookie.path.clone(),
- domain: cookie.domain.clone(),
+ domain: domain.clone(),
// CDP/persisted import is trusted; honor the explicit domain as
// domain-scoped (matches the prior behavior).
host_only: false,
@@ -255,7 +259,7 @@ impl CookieJar {
expires,
same_site,
};
- jar.entry(cookie.domain).or_default().insert((cookie.name, cookie.path), entry);
+ jar.entry(domain).or_default().insert((cookie.name, cookie.path), entry);
}
}
@@ -322,7 +326,7 @@ impl CookieJar {
if let Some((key, val)) = attr.split_once('=') {
match key.trim().to_lowercase().as_str() {
"domain" => {
- domain_attr = Some(val.trim().trim_start_matches('.').to_lowercase());
+ domain_attr = Some(canonical_domain(val));
}
"path" => {
path = val.trim().to_string();
@@ -400,17 +404,8 @@ impl CookieJar {
for domain_cookies in cookies.values_mut() {
domain_cookies.retain(|_k, e| e.name != name);
}
- } else {
- let domains_to_try = [
- domain.to_string(),
- format!(".{}", domain.trim_start_matches('.')),
- domain.trim_start_matches('.').to_string(),
- ];
- for d in &domains_to_try {
- if let Some(domain_cookies) = cookies.get_mut(d.as_str()) {
- domain_cookies.retain(|_k, e| e.name != name);
- }
- }
+ } else if let Some(domain_cookies) = cookies.get_mut(canonical_domain(domain).as_str()) {
+ domain_cookies.retain(|_k, e| e.name != name);
}
}
@@ -424,17 +419,8 @@ impl CookieJar {
for domain_cookies in cookies.values_mut() {
domain_cookies.retain(|_k, e| !(e.name == name && matches_path(&e.path)));
}
- } else {
- let domains_to_try = [
- domain.to_string(),
- format!(".{}", domain.trim_start_matches('.')),
- domain.trim_start_matches('.').to_string(),
- ];
- for d in &domains_to_try {
- if let Some(domain_cookies) = cookies.get_mut(d.as_str()) {
- domain_cookies.retain(|_k, e| !(e.name == name && matches_path(&e.path)));
- }
- }
+ } else if let Some(domain_cookies) = cookies.get_mut(canonical_domain(domain).as_str()) {
+ domain_cookies.retain(|_k, e| !(e.name == name && matches_path(&e.path)));
}
}
@@ -575,13 +561,13 @@ fn parse_http_date(s: &str) -> Result<u64, ()> {
/// blocks the reported cross-domain attack, and single-label suffixes (com,
/// local) are rejected.
fn resolve_cookie_domain(origin_host: &str, domain_attr: Option<&str>) -> Option<(String, bool)> {
- let origin = origin_host.trim().trim_start_matches('.').to_lowercase();
+ let origin = canonical_domain(origin_host);
if origin.is_empty() {
return None;
}
let dom = match domain_attr {
None => return Some((origin, true)),
- Some(raw) => raw.trim().trim_start_matches('.').to_lowercase(),
+ Some(raw) => canonical_domain(raw),
};
if dom.is_empty() || dom == origin {
return Some((origin, true));
@@ -888,6 +874,97 @@ mod tests {
assert_eq!(cookies[0].expires, None);
}
+ fn cdp(name: &str, value: &str, domain: &str, path: &str) -> CookieInfo {
+ CookieInfo {
+ name: name.to_string(),
+ value: value.to_string(),
+ domain: domain.to_string(),
+ path: path.to_string(),
+ secure: false,
+ http_only: false,
+ same_site: String::new(),
+ expires: None,
+ }
+ }
+
+ fn marker(jar: &CookieJar) -> Vec<CookieInfo> {
+ jar.get_all_cookies().into_iter().filter(|c| c.name == "marker").collect()
+ }
+
+ #[test]
+ fn test_cdp_domain_leading_dot_is_not_a_separate_cookie() {
+ // The two entrances disagreed: CDP retained the dot, while Set-Cookie stripped it.
+ let jar = CookieJar::new();
+ let url = Url::parse("https://app.example.com/").unwrap();
+
+ jar.set_cookies_from_cdp(vec![cdp("marker", "stale", ".example.com", "/")]);
+ jar.set_cookie("marker=fresh; Domain=example.com; Path=/", &url);
+
+ assert_eq!(marker(&jar).len(), 1, "one cookie, one entry, got: {:?}", marker(&jar));
+ let header = jar.get_cookie_header(&url);
+ assert_eq!(header.matches("marker=").count(), 1, "header: {header:?}");
+ assert!(header.contains("marker=fresh"), "newer value must win: {header:?}");
+ }
+
+ #[test]
+ fn test_cdp_stored_domain_field_carries_no_dot() {
+ // The dotted spelling comes LAST. That is why an implementation which only
+ // canonicalizes the map key and leaves `entry.domain` raw also fails here.
+ let jar = CookieJar::new();
+ jar.set_cookies_from_cdp(vec![cdp("marker", "one", "example.com", "/")]);
+ jar.set_cookies_from_cdp(vec![cdp("marker", "two", ".EXAMPLE.com", "/")]);
+
+ let all = marker(&jar);
+ assert_eq!(all.len(), 1, "both spellings collapse, got: {all:?}");
+ assert_eq!(all[0].domain, "example.com", "entry.domain is canonical, got: {:?}", all[0].domain);
+ assert_eq!(all[0].value, "two", "newer value must win");
+ }
+
+ #[test]
+ fn test_cdp_domain_leading_dot_repairs_a_persisted_store() {
+ // load_from_file() imports through here, so an old store must not resurrect the
+ // duplicate.
+ let jar = CookieJar::new();
+ jar.set_cookies_from_cdp(vec![
+ cdp("marker", "one", ".example.com", "/"),
+ cdp("marker", "two", "example.com", "/"),
+ ]);
+ assert_eq!(marker(&jar).len(), 1, "got: {:?}", marker(&jar));
+ }
+
+ #[test]
+ fn test_cdp_zero_expiry_deletes_across_domain_spellings() {
+ // The insert canonicalizes the key, so every delete path has to canonicalize its
+ // lookup too. Otherwise the cookie becomes unreachable and keeps going out.
+ for (stored, deleted) in [
+ ("Example.COM", "Example.COM"),
+ (".example.com", "example.com"),
+ ("example.com", ".EXAMPLE.com"),
+ ] {
+ let jar = CookieJar::new();
+ jar.set_cookies_from_cdp(vec![cdp("marker", "current", stored, "/")]);
+ let mut gone = cdp("marker", "", deleted, "/");
+ gone.expires = Some(0);
+ jar.set_cookies_from_cdp(vec![gone]);
+ assert!(marker(&jar).is_empty(), "stored {stored:?}, deleted {deleted:?}: {:?}", marker(&jar));
+ }
+ }
+
+ #[test]
+ fn test_delete_cookie_canonicalizes_its_lookup() {
+ for spelling in ["Example.COM", ".example.com", "example.com"] {
+ let jar = CookieJar::new();
+ jar.set_cookies_from_cdp(vec![cdp("marker", "current", "Example.COM", "/")]);
+ jar.delete_cookie("marker", spelling);
+ assert!(marker(&jar).is_empty(), "delete_cookie({spelling:?}): {:?}", marker(&jar));
+
+ let jar = CookieJar::new();
+ jar.set_cookies_from_cdp(vec![cdp("marker", "current", "Example.COM", "/")]);
+ jar.delete_cookies_filtered("marker", spelling, Some("/"));
+ assert!(marker(&jar).is_empty(), "delete_cookies_filtered({spelling:?}): {:?}", marker(&jar));
+ }
+ }
+
#[test]
fn test_set_cookies_from_cdp_zero_expiry_deletes_matching_cookie() {
let jar = CookieJar::new();
diff --git a/crates/obscura-net/src/lib.rs b/crates/obscura-net/src/lib.rs
index ea906576..b9d0b96d 100644
--- a/crates/obscura-net/src/lib.rs
+++ b/crates/obscura-net/src/lib.rs
@@ -12,7 +12,7 @@ pub use client::{
ObscuraNetError, RequestCallback, RequestCredentials, RequestInfo, RequestMode,
ResourceRequest, ResourceType, Response, ResponseCallback, SsrfGuardResolver,
};
-pub use cookies::{default_cookie_path, CookieInfo, CookieJar};
+pub use cookies::{canonical_domain, default_cookie_path, CookieInfo, CookieJar};
pub use encoding::{
decode_non_html, decode_response, decode_response_with_name, decode_with_label, label_name,
url_encode_query,