203 lines
7.3 KiB
Rust
203 lines
7.3 KiB
Rust
//! Cookies of one download: those it was given and those servers set on the way.
|
|
|
|
use crate::site::same_site;
|
|
use chrono::{DateTime, Utc};
|
|
use reqwest::header::HeaderValue;
|
|
use url::{Host, Url};
|
|
|
|
/// Enough for any sign-in; a server can't make it grow.
|
|
const MOST: usize = 100;
|
|
|
|
#[derive(Default)]
|
|
pub struct Jar(Vec<Cookie>);
|
|
|
|
struct Cookie {
|
|
name: String,
|
|
value: String,
|
|
domain: String,
|
|
/// For `domain` only, not for hosts below it.
|
|
exact: bool,
|
|
path: String,
|
|
secure: bool,
|
|
expires: Option<DateTime<Utc>>,
|
|
/// Given for this link, not set by a server: for its site only, port and TLS included.
|
|
given: Option<Url>,
|
|
}
|
|
|
|
impl Jar {
|
|
/// Takes a `Cookie` header meant for the site of `url`.
|
|
pub fn give(&mut self, url: &Url, header: &str) {
|
|
for (name, value) in header.split(';').filter_map(|pair| pair.split_once('=')) {
|
|
self.put(Cookie {
|
|
name: name.trim().into(),
|
|
value: value.trim().into(),
|
|
domain: host(url),
|
|
exact: true,
|
|
path: "/".into(),
|
|
secure: false,
|
|
expires: None,
|
|
given: Some(url.clone()),
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Takes the value of a `Set-Cookie` header.
|
|
pub fn set(&mut self, url: &Url, header: &str, now: DateTime<Utc>) {
|
|
let mut pieces = header.split(';');
|
|
let Some((name, value)) = pieces.next().and_then(|p| p.split_once('=')) else { return };
|
|
let mut cookie = Cookie {
|
|
name: name.trim().into(),
|
|
value: value.trim().into(),
|
|
domain: host(url),
|
|
exact: true,
|
|
path: default_path(url),
|
|
secure: false,
|
|
expires: None,
|
|
given: None,
|
|
};
|
|
let mut max_age = None;
|
|
for piece in pieces {
|
|
let (key, value) = piece.split_once('=').unwrap_or((piece, ""));
|
|
let value = value.trim();
|
|
match key.trim().to_ascii_lowercase().as_str() {
|
|
"domain" => {
|
|
let domain = value.trim_start_matches('.').to_ascii_lowercase();
|
|
if domain == cookie.domain && !is_name(url) {
|
|
continue;
|
|
}
|
|
// Not its own domain, or a whole top-level one.
|
|
if !is_name(url) || !domain.contains('.') || !below(&cookie.domain, &domain) {
|
|
return;
|
|
}
|
|
(cookie.domain, cookie.exact) = (domain, false);
|
|
}
|
|
"path" if value.starts_with('/') => cookie.path = value.into(),
|
|
"secure" => cookie.secure = true,
|
|
"max-age" => max_age = value.parse::<i64>().ok(),
|
|
"expires" => cookie.expires = date(value),
|
|
_ => {}
|
|
}
|
|
}
|
|
if let Some(seconds) = max_age {
|
|
let life = chrono::Duration::try_seconds(seconds).unwrap_or(chrono::Duration::MAX);
|
|
cookie.expires = now.checked_add_signed(life);
|
|
}
|
|
if cookie.secure && url.scheme() != "https" {
|
|
return;
|
|
}
|
|
self.put(cookie);
|
|
}
|
|
|
|
/// The `Cookie` header for `url`.
|
|
pub fn header(&self, url: &Url, now: DateTime<Utc>) -> Option<HeaderValue> {
|
|
let name = host(url);
|
|
let mut fit: Vec<&Cookie> = self
|
|
.0
|
|
.iter()
|
|
.filter(|c| c.domain == name || (!c.exact && below(&name, &c.domain)))
|
|
.filter(|c| c.given.as_ref().is_none_or(|at| same_site(at, url)))
|
|
.filter(|c| !c.secure || url.scheme() == "https")
|
|
.filter(|c| c.expires.is_none_or(|at| at > now) && under(url.path(), &c.path))
|
|
.collect();
|
|
fit.sort_by_key(|c| std::cmp::Reverse(c.path.len()));
|
|
let all: Vec<String> = fit.iter().map(|c| format!("{}={}", c.name, c.value)).collect();
|
|
let mut value = HeaderValue::try_from(all.join("; ")).ok().filter(|v| !v.is_empty())?;
|
|
value.set_sensitive(true);
|
|
Some(value)
|
|
}
|
|
|
|
fn put(&mut self, cookie: Cookie) {
|
|
self.0.retain(|c| (&c.name, &c.domain, &c.path) != (&cookie.name, &cookie.domain, &cookie.path));
|
|
if self.0.len() < MOST && !cookie.name.is_empty() {
|
|
self.0.push(cookie);
|
|
}
|
|
}
|
|
}
|
|
|
|
fn host(url: &Url) -> String {
|
|
url.host_str().unwrap_or_default().to_ascii_lowercase()
|
|
}
|
|
|
|
fn is_name(url: &Url) -> bool {
|
|
matches!(url.host(), Some(Host::Domain(_)))
|
|
}
|
|
|
|
fn below(host: &str, domain: &str) -> bool {
|
|
host == domain || host.strip_suffix(domain).is_some_and(|rest| rest.ends_with('.'))
|
|
}
|
|
|
|
fn under(path: &str, of: &str) -> bool {
|
|
path.strip_prefix(of).is_some_and(|rest| rest.is_empty() || of.ends_with('/') || rest.starts_with('/'))
|
|
}
|
|
|
|
fn default_path(url: &Url) -> String {
|
|
match url.path().rfind('/') {
|
|
None | Some(0) => "/".into(),
|
|
Some(i) => url.path()[..i].into(),
|
|
}
|
|
}
|
|
|
|
/// `Wed, 21 Oct 2015 07:28:00 GMT`, also with dashes.
|
|
fn date(text: &str) -> Option<DateTime<Utc>> {
|
|
DateTime::parse_from_rfc2822(&text.replace('-', " ")).ok().map(|t| t.to_utc())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn url(text: &str) -> Url {
|
|
Url::parse(text).unwrap()
|
|
}
|
|
|
|
fn sent(jar: &Jar, to: &str) -> String {
|
|
jar.header(&url(to), Utc::now()).map_or(String::new(), |v| v.to_str().unwrap().into())
|
|
}
|
|
|
|
#[test]
|
|
fn given_cookies_stay_with_their_host() {
|
|
let mut jar = Jar::default();
|
|
jar.give(&url("https://h.example/f"), "a=1; b=x=y; junk");
|
|
assert_eq!(sent(&jar, "https://h.example/other?q"), "a=1; b=x=y");
|
|
for other in ["http://h.example/f", "https://cdn.h.example/f", "https://h.example:444/f", "https://example/f", "https://evilh.example/"] {
|
|
assert_eq!(sent(&jar, other), "", "{other}");
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn set_cookies_keep_their_bounds() {
|
|
let (mut jar, now) = (Jar::default(), Utc::now());
|
|
let at = url("https://a.h.example/login/in");
|
|
for header in [
|
|
"host=1",
|
|
"wide=1; Domain=.H.example; Path=/",
|
|
"deep=1; Path=/files",
|
|
"tls=1; Path=/; Secure",
|
|
"other=1; Domain=evil.example; Path=/",
|
|
"top=1; Domain=example; Path=/",
|
|
"old=1; Path=/; Max-Age=0",
|
|
"past=1; Path=/; Expires=Wed, 21-Oct-2015 07:28:00 GMT",
|
|
"fresh=1; Path=/; Max-Age=100",
|
|
"fresh=2; Path=/; Max-Age=100",
|
|
"nothing",
|
|
] {
|
|
jar.set(&at, header, now);
|
|
}
|
|
assert_eq!(sent(&jar, "https://a.h.example/files/x"), "deep=1; wide=1; tls=1; fresh=2");
|
|
assert_eq!(sent(&jar, "https://a.h.example/filesx"), "wide=1; tls=1; fresh=2");
|
|
assert_eq!(sent(&jar, "https://a.h.example/login/x"), "host=1; wide=1; tls=1; fresh=2");
|
|
assert_eq!(sent(&jar, "http://b.h.example/"), "wide=1");
|
|
assert_eq!(sent(&jar, "https://example/"), "");
|
|
assert!(jar.header(&at, now + chrono::Duration::seconds(200)).unwrap().is_sensitive());
|
|
|
|
jar.set(&at, "wide=; Domain=h.example; Path=/; Max-Age=-1", now);
|
|
assert_eq!(sent(&jar, "http://b.h.example/"), "");
|
|
let ip = url("http://127.0.0.1/");
|
|
jar.set(&ip, "a=1; Domain=0.0.1", now);
|
|
assert_eq!(sent(&jar, "http://127.0.0.1/"), "");
|
|
for i in 0..1000 {
|
|
jar.set(&ip, &format!("n{i}=1"), now);
|
|
}
|
|
assert!(jar.0.len() <= MOST);
|
|
}
|
|
}
|