use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use std::time::SystemTime;
use url::Url;
static CREATION_COUNTER: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SameSite {
Strict,
Lax,
None,
}
impl From<cookie::SameSite> for SameSite {
fn from(s: cookie::SameSite) -> Self {
match s {
cookie::SameSite::Strict => Self::Strict,
cookie::SameSite::Lax => Self::Lax,
cookie::SameSite::None => Self::None,
}
}
}
#[derive(Clone)]
#[allow(
clippy::struct_excessive_bools,
reason = "the four flags are the independent RFC 6265 cookie attributes (host-only, secure, http-only, persistent) stored exactly as Set-Cookie declared them"
)]
pub struct Cookie {
pub(crate) name: String,
pub(crate) value: String,
pub(crate) domain: String,
pub(crate) host_only: bool,
pub(crate) path: String,
pub(crate) secure: bool,
pub(crate) http_only: bool,
pub(crate) same_site: Option<SameSite>,
pub(crate) expires: Option<SystemTime>,
pub(crate) persistent: bool,
pub(crate) creation_index: u64,
}
impl std::fmt::Debug for Cookie {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Cookie")
.field("name", &self.name)
.field("value", &"<redacted>")
.field("domain", &self.domain)
.field("host_only", &self.host_only)
.field("path", &self.path)
.field("secure", &self.secure)
.field("http_only", &self.http_only)
.field("same_site", &self.same_site)
.field("expires", &self.expires)
.field("persistent", &self.persistent)
.field("creation_index", &self.creation_index)
.finish()
}
}
impl Cookie {
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn value(&self) -> &str {
&self.value
}
#[must_use]
pub fn domain(&self) -> &str {
&self.domain
}
#[must_use]
pub fn is_host_only(&self) -> bool {
self.host_only
}
#[must_use]
pub fn path(&self) -> &str {
&self.path
}
#[must_use]
pub fn is_secure(&self) -> bool {
self.secure
}
#[must_use]
pub fn is_http_only(&self) -> bool {
self.http_only
}
#[must_use]
pub fn same_site(&self) -> Option<SameSite> {
self.same_site
}
#[must_use]
pub fn expires(&self) -> Option<SystemTime> {
self.expires
}
#[must_use]
pub fn is_persistent(&self) -> bool {
self.persistent
}
#[must_use]
pub fn creation_index(&self) -> u64 {
self.creation_index
}
#[must_use]
pub fn name_value_pair(&self) -> String {
format!("{}={}", self.name, self.value)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct CookieKey {
name: String,
domain: String,
path: String,
}
impl CookieKey {
fn new(name: &str, domain: &str, path: &str) -> Self {
Self {
name: name.to_owned(),
domain: domain.to_lowercase(),
path: path.to_owned(),
}
}
}
struct JarInner {
cookies: HashMap<CookieKey, Cookie>,
next_expiry: Option<SystemTime>,
}
impl JarInner {
fn recompute_next_expiry(&mut self) {
self.next_expiry = self
.cookies
.values()
.filter(|cookie| cookie.persistent)
.filter_map(|cookie| cookie.expires)
.min();
}
fn persistent_expiry(cookie: &Cookie) -> Option<SystemTime> {
cookie.persistent.then_some(cookie.expires).flatten()
}
fn insert_cookie(&mut self, key: CookieKey, cookie: Cookie) {
let old_expiry = self.cookies.get(&key).and_then(Self::persistent_expiry);
let new_expiry = Self::persistent_expiry(&cookie);
self.cookies.insert(key, cookie);
match (self.next_expiry, old_expiry, new_expiry) {
(None, _, Some(expiry)) => self.next_expiry = Some(expiry),
(Some(current), _, Some(expiry)) if expiry < current => {
self.next_expiry = Some(expiry);
}
(Some(current), Some(old), new)
if old == current && new.is_none_or(|e| e > current) =>
{
self.recompute_next_expiry();
}
_ => {}
}
}
fn remove_cookie(&mut self, key: &CookieKey) {
let removed_expiry = self.cookies.get(key).and_then(Self::persistent_expiry);
self.cookies.remove(key);
if removed_expiry == self.next_expiry {
self.recompute_next_expiry();
}
}
}
impl std::fmt::Debug for JarInner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("JarInner")
.field("len", &self.cookies.len())
.finish_non_exhaustive()
}
}
#[derive(Clone)]
pub struct CookieJar {
inner: Arc<RwLock<JarInner>>,
}
impl std::fmt::Debug for CookieJar {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let len = self.inner.try_read().map(|inner| inner.cookies.len()).ok();
f.debug_struct("CookieJar")
.field("len", &len)
.finish_non_exhaustive()
}
}
impl Default for CookieJar {
fn default() -> Self {
Self::new()
}
}
impl CookieJar {
#[must_use]
pub fn new() -> Self {
Self {
inner: Arc::new(RwLock::new(JarInner {
cookies: HashMap::new(),
next_expiry: None,
})),
}
}
#[must_use]
pub fn with_initial_cookie(cookie: Cookie) -> Self {
let jar = Self::new();
let _ = jar.set(cookie);
jar
}
pub fn update_from_response(&self, response_url: &Url, set_cookie_headers: &[String]) {
let response_host = response_url.host_str().unwrap_or("");
let now = SystemTime::now();
let mut to_insert: Vec<Cookie> = Vec::new();
let mut to_remove: Vec<CookieKey> = Vec::new();
for header_value in set_cookie_headers {
if let Some(cookie) = parse_set_cookie(header_value, response_url, response_host) {
if cookie.persistent && cookie.expires.is_some_and(|exp| now >= exp) {
to_remove.push(CookieKey::new(&cookie.name, &cookie.domain, &cookie.path));
} else {
to_insert.push(cookie);
}
}
}
if to_insert.is_empty() && to_remove.is_empty() {
return;
}
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
for key in to_remove {
jar.cookies.remove(&key);
}
for cookie in to_insert {
let key = CookieKey::new(&cookie.name, &cookie.domain, &cookie.path);
jar.cookies.insert(key, cookie);
}
jar.recompute_next_expiry();
}
#[must_use]
pub fn cookies_for_url(&self, url: &Url) -> Option<String> {
self.expire_if_due();
let jar = self
.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
let url_host = url.host_str().unwrap_or("");
let is_secure = url.scheme() == "https";
let url_path = url.path();
let mut matches: Vec<&Cookie> = jar
.cookies
.values()
.filter(|c| cookie_matches(c, url_host, url_path, is_secure))
.collect();
if matches.is_empty() {
return None;
}
matches.sort_by(|a, b| {
b.path
.len()
.cmp(&a.path.len())
.then_with(|| a.creation_index.cmp(&b.creation_index))
});
let mut seen: HashSet<(&str, &str)> = HashSet::new();
let mut result = String::new();
for c in &matches {
if seen.insert((&c.name, &c.path)) {
if !result.is_empty() {
result.push_str("; ");
}
result.push_str(&c.name);
result.push('=');
result.push_str(&c.value);
}
}
if result.is_empty() {
None
} else {
Some(result)
}
}
#[must_use]
pub fn all_cookies(&self) -> Vec<Cookie> {
self.expire_if_due();
let jar = self
.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
jar.cookies.values().cloned().collect()
}
#[must_use]
pub fn get(&self, name: &str, domain: Option<&str>, path: Option<&str>) -> Option<Cookie> {
self.expire_if_due();
let jar = self
.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let (Some(d), Some(p)) = (domain, path) {
let key = CookieKey::new(name, d, p);
return jar.cookies.get(&key).cloned();
}
let matching: Vec<&Cookie> = jar.cookies.values().filter(|c| c.name == name).collect();
(matching.len() == 1).then(|| matching[0].clone())
}
pub fn set(&self, cookie: Cookie) -> Result<(), crate::error::Error> {
if !is_valid_cookie_name(&cookie.name) {
return Err(crate::error::Error::InvalidHeaderValue(format!(
"invalid cookie name: '{}'",
cookie.name
)));
}
if !is_valid_cookie_value(&cookie.value) {
return Err(crate::error::Error::InvalidHeaderValue(
"invalid cookie value: must match RFC 6265 cookie-octet (no ';', ',', whitespace, CTLs, or non-ASCII)".into(),
));
}
if cookie.persistent {
if let Some(expires) = cookie.expires {
if SystemTime::now() >= expires {
let key = CookieKey::new(&cookie.name, &cookie.domain, &cookie.path);
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
jar.remove_cookie(&key);
return Ok(());
}
}
}
let key = CookieKey::new(&cookie.name, &cookie.domain, &cookie.path);
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
jar.insert_cookie(key, cookie);
Ok(())
}
pub fn set_default_cookie(
&self,
name: String,
value: String,
) -> Result<(), crate::error::Error> {
if !is_valid_cookie_name(&name) {
return Err(crate::error::Error::InvalidHeaderValue(format!(
"invalid cookie name: '{name}'"
)));
}
if !is_valid_cookie_value(&value) {
return Err(crate::error::Error::InvalidHeaderValue(
"invalid cookie value: must match RFC 6265 cookie-octet (no ';', ',', whitespace, CTLs, or non-ASCII)".into(),
));
}
let cookie = Cookie {
name,
value,
domain: String::new(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: CREATION_COUNTER.fetch_add(1, Ordering::Relaxed),
};
let key = CookieKey::new(&cookie.name, &cookie.domain, &cookie.path);
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
jar.insert_cookie(key, cookie);
Ok(())
}
pub fn delete(&self, name: &str, domain: &str, path: &str) {
let key = CookieKey::new(name, domain, path);
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
jar.remove_cookie(&key);
}
pub fn clear(&self) {
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
jar.cookies.clear();
jar.next_expiry = None;
}
#[must_use]
pub fn len(&self) -> usize {
self.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.cookies
.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.cookies
.is_empty()
}
pub fn expire_stale(&self) {
let now = SystemTime::now();
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
jar.cookies
.retain(|_, c| !c.persistent || c.expires.is_none_or(|exp| now < exp));
jar.recompute_next_expiry();
}
fn expire_if_due(&self) {
let now = SystemTime::now();
let due = self
.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.next_expiry
.is_some_and(|expiry| now >= expiry);
if !due {
return;
}
let mut jar = self
.inner
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if jar.next_expiry.is_some_and(|expiry| now >= expiry) {
jar.cookies
.retain(|_, c| !c.persistent || c.expires.is_none_or(|exp| now < exp));
jar.recompute_next_expiry();
}
}
}
fn cookie_matches(cookie: &Cookie, url_host: &str, url_path: &str, is_secure: bool) -> bool {
if cookie.secure && !is_secure {
return false;
}
if !cookie.host_only && cookie.domain.is_empty() {
return path_matches(url_path, &cookie.path);
}
if cookie.host_only {
if !url_host.eq_ignore_ascii_case(&cookie.domain) {
return false;
}
} else if !domain_matches(url_host, &cookie.domain) {
return false;
}
path_matches(url_path, &cookie.path)
}
fn path_matches(request_path: &str, cookie_path: &str) -> bool {
if !request_path.starts_with('/') || !cookie_path.starts_with('/') {
return false;
}
if request_path == cookie_path {
return true;
}
if !request_path.starts_with(cookie_path) {
return false;
}
if cookie_path.ends_with('/') {
true
} else {
request_path.as_bytes().get(cookie_path.len()) == Some(&b'/')
}
}
fn domain_matches(host: &str, domain: &str) -> bool {
if host.eq_ignore_ascii_case(domain) {
return true;
}
if is_ip_address(host) || is_ip_address(domain) {
return false;
}
let host = host.as_bytes();
let domain = domain.as_bytes();
host.len() > domain.len() + 1
&& host[host.len() - domain.len() - 1] == b'.'
&& host[host.len() - domain.len()..].eq_ignore_ascii_case(domain)
}
fn is_ip_address(s: &str) -> bool {
s.parse::<std::net::IpAddr>().is_ok()
}
pub(crate) fn is_valid_cookie_name(name: &str) -> bool {
if name.is_empty() {
return false;
}
!name
.bytes()
.any(|b| b <= 0x20 || b == 0x7f || b == b'"' || b == b',' || b == b';' || b == b'\\')
}
pub(crate) fn is_valid_cookie_value(value: &str) -> bool {
value.bytes().all(|b| {
b == 0x21
|| (0x23..=0x2B).contains(&b)
|| (0x2D..=0x3A).contains(&b)
|| (0x3C..=0x5B).contains(&b)
|| (0x5D..=0x7E).contains(&b)
})
}
fn default_cookie_path(url_path: &str) -> String {
if url_path.is_empty() || !url_path.starts_with('/') {
return "/".to_owned();
}
match url_path.rfind('/') {
Some(last_pos) if last_pos > 0 => url_path[..last_pos].to_owned(),
_ => "/".to_owned(),
}
}
fn parse_set_cookie(header_value: &str, response_url: &Url, response_host: &str) -> Option<Cookie> {
let Ok(parsed) = cookie::Cookie::parse_encoded(header_value) else {
#[cfg(feature = "tracing")]
tracing::debug!("eggfetch: skipped malformed Set-Cookie");
return None;
};
let name = parsed.name().to_owned();
let value = parsed.value().to_owned();
if !is_valid_cookie_name(&name) {
return None;
}
let (domain, host_only) = match parsed.domain() {
Some(raw_domain) => {
let normalized = raw_domain.trim_start_matches('.').to_owned();
if normalized.is_empty() {
return None;
}
if is_ip_address(&normalized) && !normalized.eq_ignore_ascii_case(response_host) {
return None;
}
if !domain_matches(response_host, &normalized) {
return None;
}
(normalized, false)
}
None => {
(response_host.to_owned(), true)
}
};
let path = match parsed.path() {
Some(p) if p.starts_with('/') => p.to_owned(),
_ => default_cookie_path(response_url.path()),
};
let secure = parsed.secure().unwrap_or(false);
let http_only = parsed.http_only().unwrap_or(false);
let same_site = parsed.same_site().map(SameSite::from);
let (persistent, expires) = resolve_expiration(&parsed);
Some(Cookie {
name,
value,
domain,
host_only,
path,
secure,
http_only,
same_site,
expires,
persistent,
creation_index: CREATION_COUNTER.fetch_add(1, Ordering::Relaxed),
})
}
fn resolve_expiration(parsed: &cookie::Cookie<'_>) -> (bool, Option<SystemTime>) {
const MAX_AGE_CAP_SECS: u64 = 400 * 24 * 60 * 60;
if let Some(max_age) = parsed.max_age() {
let duration_secs = max_age.whole_seconds();
if max_age.is_negative() || duration_secs == 0 {
return (true, Some(SystemTime::UNIX_EPOCH));
}
#[allow(
clippy::cast_sign_loss,
reason = "the negative and zero Max-Age cases return above, so the remaining duration is known to be non-negative"
)]
let secs = duration_secs as u64;
let capped = secs.min(MAX_AGE_CAP_SECS);
let now = SystemTime::now();
let expiry = now.checked_add(std::time::Duration::from_secs(capped));
return (true, expiry);
}
if let Some(cookie::Expiration::DateTime(dt)) = parsed.expires() {
let system_time = SystemTime::from(dt);
return (true, Some(system_time));
}
(false, None)
}
#[must_use]
pub fn parse_set_cookie_headers(response_url: &Url, set_cookie_headers: &[String]) -> Vec<Cookie> {
let response_host = response_url.host_str().unwrap_or("");
set_cookie_headers
.iter()
.filter_map(|h| parse_set_cookie(h, response_url, response_host))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
use std::time::Duration;
fn make_url(s: &str) -> Url {
Url::parse(s).unwrap()
}
#[test]
fn basic_cookie_parsing() {
let url = make_url("http://example.com/path");
let headers = vec!["session=abc123".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
let c = &cookies[0];
assert_eq!(c.name(), "session");
assert_eq!(c.value(), "abc123");
assert_eq!(c.domain(), "example.com");
assert!(c.is_host_only());
assert_eq!(c.path(), "/"); assert!(!c.is_secure());
assert!(!c.is_http_only());
assert!(c.same_site().is_none());
assert!(!c.is_persistent());
}
#[test]
fn cookie_with_domain_attribute() {
let url = make_url("http://sub.example.com/path");
let headers = vec!["key=value; Domain=example.com".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
let c = &cookies[0];
assert_eq!(c.domain(), "example.com");
assert!(!c.is_host_only());
}
#[test]
fn cookie_with_leading_dot_domain() {
let url = make_url("http://sub.example.com/path");
let headers = vec!["key=value; Domain=.example.com".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert_eq!(cookies[0].domain(), "example.com");
}
#[test]
fn domain_mismatch_rejected() {
let url = make_url("http://evil.com/path");
let headers = vec!["key=value; Domain=example.com".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert!(cookies.is_empty());
}
#[test]
fn ip_address_domain_rejected() {
let url = make_url("http://192.168.1.1/path");
let headers = vec!["key=value; Domain=192.168.1.2".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert!(cookies.is_empty());
}
#[test]
fn ip_address_domain_exact_match_accepted() {
let url = make_url("http://192.168.1.1/path");
let headers = vec!["key=value; Domain=192.168.1.1".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert_eq!(cookies[0].domain(), "192.168.1.1");
assert!(!cookies[0].is_host_only());
}
#[test]
fn host_only_cookie() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert!(cookies[0].is_host_only());
assert_eq!(cookies[0].domain(), "example.com");
}
#[test]
fn path_matching_basic() {
assert!(path_matches("/a/b/c", "/a/b"));
assert!(path_matches("/a/b/c", "/a"));
assert!(path_matches("/a/b/c", "/"));
assert!(path_matches("/a/b/c", "/a/b/c"));
assert!(!path_matches("/a/b", "/a/b/c"));
assert!(!path_matches("/xyz", "/abc"));
}
#[test]
fn path_matching_slash_prefix() {
assert!(!path_matches("/a/bc", "/a/b"));
}
#[test]
fn path_matching_root() {
assert!(path_matches("/", "/"));
assert!(path_matches("/anything", "/"));
}
#[test]
fn domain_matching() {
assert!(domain_matches("example.com", "example.com"));
assert!(domain_matches("sub.example.com", "example.com"));
assert!(domain_matches("a.b.example.com", "example.com"));
assert!(!domain_matches("notexample.com", "example.com"));
assert!(!domain_matches("example.com", "sub.example.com"));
assert!(!domain_matches("evil-example.com", "example.com"));
}
#[test]
fn secure_only_cookie() {
let url = make_url("https://example.com/path");
let headers = vec!["key=secret; Secure".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert!(cookies[0].is_secure());
let jar = CookieJar::with_initial_cookie(cookies.into_iter().next().unwrap());
assert!(jar
.cookies_for_url(&make_url("https://example.com/"))
.is_some());
assert!(jar
.cookies_for_url(&make_url("http://example.com/"))
.is_none());
}
#[test]
fn http_only_cookie() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value; HttpOnly".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert!(cookies[0].is_http_only());
}
#[test]
fn same_site_strict() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value; SameSite=Strict".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert_eq!(cookies[0].same_site(), Some(SameSite::Strict));
}
#[test]
fn same_site_lax() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value; SameSite=Lax".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert_eq!(cookies[0].same_site(), Some(SameSite::Lax));
}
#[test]
fn same_site_none() {
let url = make_url("https://example.com/path");
let headers = vec!["key=value; SameSite=None; Secure".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert_eq!(cookies[0].same_site(), Some(SameSite::None));
}
#[test]
fn max_age_precedence_over_expires() {
let url = make_url("http://example.com/path");
let headers =
vec!["key=value; Max-Age=3600; Expires=Thu, 01 Jan 1970 00:00:00 GMT".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
let c = &cookies[0];
assert!(c.is_persistent());
if let Some(exp) = c.expires() {
assert!(exp > SystemTime::now());
} else {
panic!("expected expiry");
}
}
#[test]
fn max_age_zero_deletes() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value".to_owned()];
let jar = CookieJar::new();
jar.update_from_response(&url, &headers);
assert_eq!(jar.len(), 1);
let headers = vec!["key=anything; Max-Age=0".to_owned()];
jar.update_from_response(&url, &headers);
assert_eq!(jar.len(), 0);
}
#[test]
fn max_age_negative_deletes() {
let url = make_url("http://example.com/path");
let jar = CookieJar::new();
let headers = vec!["key=value".to_owned()];
jar.update_from_response(&url, &headers);
assert_eq!(jar.len(), 1);
let headers = vec!["key=anything; Max-Age=-1".to_owned()];
jar.update_from_response(&url, &headers);
assert_eq!(jar.len(), 0);
}
#[test]
fn max_age_overflow_does_not_panic() {
let url = make_url("http://example.com/path");
let result = std::panic::catch_unwind(|| {
parse_set_cookie_headers(
&url,
&["key=value; Max-Age=99999999999999999999999".to_owned()],
)
});
let cookies = result.expect("an unrepresentable Max-Age must not panic");
assert_eq!(cookies.len(), 1);
assert!(cookies[0].persistent);
assert!(cookies[0].expires().is_some());
}
#[test]
fn expired_cookie_not_stored() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value; Expires=Thu, 01 Jan 1970 00:00:00 GMT".to_owned()];
let jar = CookieJar::new();
jar.update_from_response(&url, &headers);
assert_eq!(jar.len(), 0);
}
#[test]
fn default_path_derivation() {
assert_eq!(default_cookie_path("/a/b/c"), "/a/b");
assert_eq!(default_cookie_path("/a/b"), "/a");
assert_eq!(default_cookie_path("/a"), "/");
assert_eq!(default_cookie_path("/"), "/");
assert_eq!(default_cookie_path(""), "/");
assert_eq!(default_cookie_path("/a/"), "/a");
}
#[test]
fn default_path_from_url() {
let url = make_url("http://example.com/a/b/c");
let headers = vec!["key=value".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert_eq!(cookies[0].path(), "/a/b");
}
#[test]
fn same_name_different_paths_ordering() {
let jar = CookieJar::new();
let url = make_url("http://example.com/a/b/c");
let c1 = Cookie {
name: "key".to_owned(),
value: "short".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/a".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
};
let c2 = Cookie {
name: "key".to_owned(),
value: "long".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/a/b".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 2,
};
jar.set(c1).expect("valid test cookie");
jar.set(c2).expect("valid test cookie");
let header = jar.cookies_for_url(&url).unwrap();
assert_eq!(header, "key=long; key=short");
}
#[test]
fn cookie_serialization_format() {
let jar = CookieJar::new();
let url = make_url("http://example.com/");
jar.set(Cookie {
name: "a".to_owned(),
value: "1".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
jar.set(Cookie {
name: "b".to_owned(),
value: "2".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 2,
})
.expect("valid test cookie");
let header = jar.cookies_for_url(&url).unwrap();
assert_eq!(header, "a=1; b=2");
}
#[test]
fn cookie_names_are_case_sensitive() {
let jar = CookieJar::new();
jar.set_default_cookie("Session".to_owned(), "upper".to_owned())
.expect("valid test cookie");
jar.set_default_cookie("session".to_owned(), "lower".to_owned())
.expect("valid test cookie");
assert_eq!(jar.all_cookies().len(), 2);
let upper = jar.get("Session", None, None).expect("Session stored");
let lower = jar.get("session", None, None).expect("session stored");
assert_eq!(upper.value, "upper");
assert_eq!(lower.value, "lower");
let url = make_url("http://example.com/");
let header = jar.cookies_for_url(&url).unwrap();
assert!(header.contains("Session=upper"), "header: {header}");
assert!(header.contains("session=lower"), "header: {header}");
}
#[test]
fn longer_path_wins_across_names() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "a".to_owned(),
value: "1".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
jar.set(Cookie {
name: "b".to_owned(),
value: "2".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/a/b".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 2,
})
.expect("valid test cookie");
let url = make_url("http://example.com/a/b/c");
let header = jar.cookies_for_url(&url).unwrap();
assert_eq!(header, "b=2; a=1");
}
#[test]
fn invalid_cookie_name_rejected() {
let url = make_url("http://example.com/path");
let headers = vec!["bad;name=value".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert!(cookies.is_empty());
}
#[test]
fn invalid_empty_cookie_name_rejected() {
let url = make_url("http://example.com/path");
let headers = vec!["=value".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert!(cookies.is_empty());
}
#[test]
fn jar_get_with_domain_and_path() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "key".to_owned(),
value: "val".to_owned(),
domain: "example.com".to_owned(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
let c = jar.get("key", Some("example.com"), Some("/"));
assert!(c.is_some());
assert_eq!(c.unwrap().value(), "val");
assert!(jar.get("key", Some("other.com"), Some("/")).is_none());
assert!(jar
.get("key", Some("example.com"), Some("/other"))
.is_none());
}
#[test]
fn jar_delete() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "key".to_owned(),
value: "val".to_owned(),
domain: "example.com".to_owned(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
assert_eq!(jar.len(), 1);
jar.delete("key", "example.com", "/");
assert_eq!(jar.len(), 0);
}
#[test]
fn jar_set_rejects_already_expired_cookie() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
let jar = CookieJar::new();
let mut live = cookies[0].clone();
live.domain = "example.com".to_owned();
live.host_only = false;
jar.set(live).expect("valid test cookie");
assert_eq!(jar.len(), 1);
let expired = Cookie {
name: "key".to_owned(),
value: "stale".to_owned(),
domain: "example.com".to_owned(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: Some(SystemTime::UNIX_EPOCH),
persistent: true,
creation_index: 2,
};
jar.set(expired)
.expect("expired replacement is still well-formed");
assert_eq!(jar.len(), 0, "expired cookie must not be stored");
assert!(jar.get("key", Some("example.com"), Some("/")).is_none());
}
#[test]
fn jar_clear() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "a".to_owned(),
value: "1".to_owned(),
domain: "example.com".to_owned(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
jar.set(Cookie {
name: "b".to_owned(),
value: "2".to_owned(),
domain: "example.com".to_owned(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 2,
})
.expect("valid test cookie");
assert_eq!(jar.len(), 2);
jar.clear();
assert!(jar.is_empty());
}
#[test]
fn jar_clone_shares_state() {
let jar1 = CookieJar::new();
jar1.set(Cookie {
name: "key".to_owned(),
value: "val".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
let jar2 = jar1.clone();
assert_eq!(jar2.len(), 1);
jar2.clear();
assert!(jar1.is_empty());
}
#[test]
fn host_only_cookie_not_sent_cross_host() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "key".to_owned(),
value: "val".to_owned(),
domain: "a.example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
assert!(jar
.cookies_for_url(&make_url("http://a.example.com/"))
.is_some());
assert!(jar
.cookies_for_url(&make_url("http://b.example.com/"))
.is_none());
}
#[test]
fn domain_cookie_sent_to_subdomains() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "key".to_owned(),
value: "val".to_owned(),
domain: "example.com".to_owned(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
assert!(jar
.cookies_for_url(&make_url("http://example.com/"))
.is_some());
assert!(jar
.cookies_for_url(&make_url("http://sub.example.com/"))
.is_some());
assert!(jar
.cookies_for_url(&make_url("http://a.b.example.com/"))
.is_some());
assert!(jar
.cookies_for_url(&make_url("http://notexample.com/"))
.is_none());
}
#[test]
fn cookie_replacement_same_identity() {
let url = make_url("http://example.com/path");
let jar = CookieJar::new();
let headers1 = vec!["key=old".to_owned()];
jar.update_from_response(&url, &headers1);
assert_eq!(jar.len(), 1);
let headers2 = vec!["key=new".to_owned()];
jar.update_from_response(&url, &headers2);
assert_eq!(jar.len(), 1);
let c = jar.get("key", Some("example.com"), Some("/")).unwrap();
assert_eq!(c.value(), "new");
}
#[test]
fn name_value_pair() {
let c = Cookie {
name: "foo".to_owned(),
value: "bar".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
};
assert_eq!(c.name_value_pair(), "foo=bar");
}
#[test]
fn multiple_set_cookie_headers() {
let url = make_url("http://example.com/path");
let headers = vec![
"a=1".to_owned(),
"b=2; Path=/".to_owned(),
"c=3; Domain=example.com; Secure".to_owned(),
];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 3);
}
#[test]
fn all_cookies_returns_vec() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "x".to_owned(),
value: "1".to_owned(),
domain: "a.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
jar.set(Cookie {
name: "y".to_owned(),
value: "2".to_owned(),
domain: "b.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 2,
})
.expect("valid test cookie");
let all = jar.all_cookies();
assert_eq!(all.len(), 2);
}
#[test]
fn cookies_for_url_none_when_empty() {
let jar = CookieJar::new();
assert!(jar
.cookies_for_url(&make_url("http://example.com/"))
.is_none());
}
#[test]
fn cookie_with_explicit_path() {
let url = make_url("http://example.com/a/b/c");
let headers = vec!["key=value; Path=/a".to_owned()];
let cookies = parse_set_cookie_headers(&url, &headers);
assert_eq!(cookies.len(), 1);
assert_eq!(cookies[0].path(), "/a");
}
#[test]
fn domain_case_insensitive() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "key".to_owned(),
value: "val".to_owned(),
domain: "Example.COM".to_owned(),
host_only: false,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
assert!(jar
.cookies_for_url(&make_url("http://example.com/"))
.is_some());
}
#[test]
fn is_ip_address_check() {
assert!(is_ip_address("192.168.1.1"));
assert!(is_ip_address("127.0.0.1"));
assert!(is_ip_address("::1"));
assert!(is_ip_address("2001:db8::1"));
assert!(!is_ip_address("example.com"));
assert!(!is_ip_address("not-an-ip"));
}
#[test]
fn cookie_header_not_sent_when_no_match() {
let jar = CookieJar::new();
jar.set(Cookie {
name: "key".to_owned(),
value: "val".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
assert!(jar
.cookies_for_url(&make_url("http://other.com/"))
.is_none());
}
#[test]
fn persistent_cookie_expiry() {
let url = make_url("http://example.com/path");
let headers = vec!["key=value; Max-Age=-1".to_owned()];
let jar = CookieJar::new();
jar.update_from_response(&url, &headers);
assert_eq!(jar.len(), 0);
}
#[test]
fn with_initial_cookie() {
let c = Cookie {
name: "init".to_owned(),
value: "val".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
};
let jar = CookieJar::with_initial_cookie(c);
assert_eq!(jar.len(), 1);
}
#[test]
fn creation_index_monotonically_increases() {
let url = make_url("http://example.com/path");
let headers1 = vec!["a=1".to_owned()];
let headers2 = vec!["b=2".to_owned()];
let cookies1 = parse_set_cookie_headers(&url, &headers1);
let cookies2 = parse_set_cookie_headers(&url, &headers2);
assert!(cookies2[0].creation_index() > cookies1[0].creation_index());
}
#[test]
fn same_name_different_creation_index_ordering() {
let jar = CookieJar::new();
let url = make_url("http://example.com/");
jar.set(Cookie {
name: "key".to_owned(),
value: "second".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 2,
})
.expect("valid test cookie");
jar.set(Cookie {
name: "key".to_owned(),
value: "first".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
let header = jar.cookies_for_url(&url).unwrap();
assert_eq!(header, "key=first");
}
#[test]
fn path_match_no_prefix_without_slash() {
assert!(!path_matches("/abc", "/ab"));
assert!(path_matches("/ab/c", "/ab"));
}
#[test]
fn jar_len_and_is_empty() {
let jar = CookieJar::new();
assert!(jar.is_empty());
assert_eq!(jar.len(), 0);
jar.set(Cookie {
name: "x".to_owned(),
value: "1".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires: None,
persistent: false,
creation_index: 1,
})
.expect("valid test cookie");
assert!(!jar.is_empty());
assert_eq!(jar.len(), 1);
}
#[test]
fn cookie_display_via_name_value_pair() {
let c = Cookie {
name: "session".to_owned(),
value: "abc123".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: true,
http_only: true,
same_site: Some(SameSite::Lax),
expires: None,
persistent: false,
creation_index: 1,
};
assert_eq!(c.name_value_pair(), "session=abc123");
assert!(c.is_secure());
assert!(c.is_http_only());
assert_eq!(c.same_site(), Some(SameSite::Lax));
}
proptest::proptest! {
#[test]
fn parse_set_cookie_returns_some_for_valid_cookies(name in "[a-zA-Z][a-zA-Z0-9_]{0,15}", value in "[a-zA-Z0-9]{1,20}") {
let url = make_url("http://example.com/path");
let header = format!("{name}={value}");
let cookies = parse_set_cookie_headers(&url, &[header]);
prop_assert_eq!(cookies.len(), 1);
}
#[test]
fn parse_set_cookie_returns_none_for_garbage(input in ".{0,100}") {
let url = make_url("http://example.com/path");
let _ = parse_set_cookie_headers(&url, &[input]);
}
#[test]
fn domain_matches_symmetric_for_exact(domain in "[a-z]{1,10}\\.[a-z]{1,5}") {
prop_assert!(domain_matches(&domain, &domain));
}
#[test]
fn path_matches_monotonic(path_a in "/[a-z]{1,5}", extra in "/[a-z]{1,5}") {
let path_b = format!("{path_a}{extra}");
prop_assert!(path_matches(&path_b, &path_a));
}
#[test]
fn default_cookie_path_starts_with_slash(url_path in "/[a-z]{0,20}(/[a-z]{0,10}){0,3}") {
let result = default_cookie_path(&url_path);
prop_assert!(result.starts_with('/'));
}
#[test]
fn is_valid_cookie_name_rejects_empty(name in "") {
prop_assert!(!is_valid_cookie_name(&name));
}
}
#[test]
fn cookie_debug_redacts_value() {
let url = make_url("http://example.com/path");
let cookies = parse_set_cookie_headers(&url, &["session=super-secret-token".to_owned()]);
assert_eq!(cookies.len(), 1);
let debug = format!("{:?}", cookies[0]);
assert!(
!debug.contains("super-secret-token"),
"Cookie Debug must not leak the value: {debug}"
);
assert!(
debug.contains("session"),
"Cookie Debug keeps the name: {debug}"
);
assert!(
debug.contains("<redacted>"),
"Cookie Debug marks redaction: {debug}"
);
}
#[test]
fn cookie_jar_debug_redacts_values() {
let jar = CookieJar::new();
jar.set_default_cookie("session".to_owned(), "super-secret-token".to_owned())
.expect("valid test cookie");
let debug = format!("{jar:?}");
assert!(
!debug.contains("super-secret-token"),
"CookieJar Debug must not leak values: {debug}"
);
}
#[test]
fn programmatic_cookie_value_with_separator_is_rejected() {
let jar = CookieJar::new();
let err = jar
.set_default_cookie("k".to_owned(), "a; b=1".to_owned())
.expect_err("separator in value must be rejected");
assert_eq!(err.kind(), "invalid_header_value");
assert_eq!(jar.len(), 0);
}
#[test]
fn cookie_value_validation_rejects_control_and_non_ascii() {
assert!(is_valid_cookie_value("abc123"));
assert!(is_valid_cookie_value(""));
assert!(is_valid_cookie_value("a=b"));
assert!(!is_valid_cookie_value("a; b=1"));
assert!(!is_valid_cookie_value("a,b"));
assert!(!is_valid_cookie_value("a b"));
assert!(!is_valid_cookie_value("a\nb"));
assert!(!is_valid_cookie_value("a\rb"));
assert!(!is_valid_cookie_value("caf\u{e9}"));
assert!(!is_valid_cookie_value("\"quoted\""));
}
fn watermark_cookie(name: &str, expires: Option<SystemTime>) -> Cookie {
Cookie {
name: name.to_owned(),
value: "value".to_owned(),
domain: "example.com".to_owned(),
host_only: true,
path: "/".to_owned(),
secure: false,
http_only: false,
same_site: None,
expires,
persistent: expires.is_some(),
creation_index: 1,
}
}
#[test]
fn expiry_watermark_tracks_mutation_without_changing_cookie_visibility() {
let jar = CookieJar::new();
let now = SystemTime::now();
let earliest = now + Duration::from_secs(10);
let later = now + Duration::from_secs(20);
jar.set(watermark_cookie("later", Some(later))).unwrap();
jar.set(watermark_cookie("earliest", Some(earliest)))
.unwrap();
assert_eq!(
jar.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.next_expiry,
Some(earliest)
);
jar.set(watermark_cookie("earliest", Some(later))).unwrap();
assert_eq!(
jar.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.next_expiry,
Some(later)
);
jar.set(watermark_cookie("session", None)).unwrap();
assert_eq!(
jar.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.next_expiry,
Some(later)
);
jar.delete("later", "example.com", "/");
assert_eq!(
jar.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.next_expiry,
Some(later)
);
jar.delete("earliest", "example.com", "/");
assert_eq!(
jar.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.next_expiry,
None
);
}
#[test]
fn expiry_watermark_preserves_equal_minimums_and_rejects_expired_insertions() {
let jar = CookieJar::new();
let expiry = SystemTime::now() + Duration::from_secs(10);
jar.set(watermark_cookie("first", Some(expiry))).unwrap();
jar.set(watermark_cookie("second", Some(expiry))).unwrap();
jar.delete("first", "example.com", "/");
assert_eq!(
jar.inner
.read()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.next_expiry,
Some(expiry)
);
let expired = SystemTime::now() - Duration::from_secs(1);
jar.set(watermark_cookie("expired", Some(expired))).unwrap();
assert_eq!(jar.len(), 1);
assert_eq!(
jar.cookies_for_url(&make_url("http://example.com/")),
Some("second=value".to_owned())
);
}
}