//! Cookie (M2.6): il minimo che serve perché un sito si ricordi di te fra due //! richieste. //! //! Ambito dichiarato: `Set-Cookie` con `Domain`, `Path`, `Secure`, `Max-Age` e //! `Expires`; invio della riga `Cookie` sulle richieste che corrispondono. //! Fuori ambito: persistenza su disco (i cookie vivono quanto la sessione), //! `SameSite`, `HttpOnly`, prefissi `__Host-`/`__Secure-`, Public Suffix List — //! quindi un dominio pubblico come `co.uk` non è trattato con la cautela che //! meriterebbe. È scritto qui perché non diventi una sorpresa. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Cookie { pub nome: String, pub valore: String, /// dominio di appartenenza, senza punto iniziale pub dominio: String, pub percorso: String, pub scaduto: bool, pub solo_https: bool, } #[derive(Debug, Default)] pub struct CookieJar { pub biscotti: Vec, } impl CookieJar { pub fn new() -> Self { CookieJar::default() } /// Registra i cookie di una risposta. `url` è l'indirizzo che li ha emessi. pub fn raccogli(&mut self, url: &str, intestazioni: &[(String, String)]) { let Some((host, percorso)) = host_e_percorso(url) else { return; }; for (k, v) in intestazioni { if !k.eq_ignore_ascii_case("set-cookie") { continue; } if let Some(c) = analizza(v, &host, &percorso, url.starts_with("https://")) { // lo stesso nome sullo stesso dominio e percorso si sostituisce self.biscotti.retain(|x| { !(x.nome == c.nome && x.dominio == c.dominio && x.percorso == c.percorso) }); if !c.scaduto { self.biscotti.push(c); } } } } /// Riga `Cookie` da mandare a quell'indirizzo ("" se non ce ne sono). pub fn riga_per(&self, url: &str) -> String { let Some((host, percorso)) = host_e_percorso(url) else { return String::new(); }; let https = url.starts_with("https://"); self.biscotti .iter() .filter(|c| !c.scaduto) .filter(|c| host == c.dominio || host.ends_with(&format!(".{}", c.dominio))) .filter(|c| percorso.starts_with(&c.percorso)) .filter(|c| !c.solo_https || https) .map(|c| format!("{}={}", c.nome, c.valore)) .collect::>() .join("; ") } pub fn quanti(&self) -> usize { self.biscotti.len() } } fn host_e_percorso(url: &str) -> Option<(String, String)> { let resto = url .strip_prefix("https://") .or_else(|| url.strip_prefix("http://"))?; let (autorita, percorso) = match resto.find('/') { Some(i) => (&resto[..i], &resto[i..]), None => (resto, "/"), }; let host = autorita .rsplit_once(':') .map(|(h, _)| h) .unwrap_or(autorita) .to_ascii_lowercase(); Some((host, percorso.to_string())) } /// `nome=valore; Domain=…; Path=…; Secure; Max-Age=…` fn analizza(valore: &str, host: &str, percorso_richiesta: &str, https: bool) -> Option { let mut pezzi = valore.split(';'); let prima = pezzi.next()?.trim(); let (nome, valore) = prima.split_once('=')?; let nome = nome.trim().to_string(); if nome.is_empty() { return None; } let mut c = Cookie { nome, valore: valore.trim().to_string(), dominio: host.to_string(), // il percorso predefinito è la cartella della richiesta percorso: match percorso_richiesta.rfind('/') { Some(i) => percorso_richiesta[..=i].to_string(), None => "/".to_string(), }, scaduto: false, solo_https: false, }; let mut max_age: Option = None; for attributo in pezzi { let a = attributo.trim(); let (chiave, valore) = match a.split_once('=') { Some((k, v)) => (k.trim(), v.trim()), None => (a, ""), }; match chiave.to_ascii_lowercase().as_str() { "domain" => { let d = valore.trim_start_matches('.').to_ascii_lowercase(); if !d.is_empty() { c.dominio = d; } } "path" => { if valore.starts_with('/') { c.percorso = valore.to_string(); } } "secure" => c.solo_https = true, "max-age" => max_age = valore.parse::().ok(), _ => {} } } if let Some(n) = max_age { if n <= 0 { c.scaduto = true; } } let _ = https; Some(c) } #[cfg(test)] mod tests { use super::*; fn risposta(url: &str, righe: &[&str]) -> CookieJar { let mut j = CookieJar::new(); let intestazioni: Vec<(String, String)> = righe .iter() .map(|r| ("Set-Cookie".to_string(), r.to_string())) .collect(); j.raccogli(url, &intestazioni); j } #[test] fn cookie_semplice_torna_al_mittente() { let j = risposta("https://a.test/pagina", &["sessione=abc123; Path=/"]); assert_eq!(j.riga_per("https://a.test/altra"), "sessione=abc123"); // un altro dominio non lo riceve assert_eq!(j.riga_per("https://b.test/"), ""); } #[test] fn dominio_con_punto_iniziale_e_sottodomini() { let j = risposta("https://www.a.test/", &["x=1; Domain=.a.test"]); assert_eq!(j.riga_per("https://a.test/"), "x=1"); assert_eq!(j.riga_per("https://www.a.test/"), "x=1"); assert_eq!(j.riga_per("https://altro.test/"), ""); } #[test] fn percorso_limita_l_invio() { let j = risposta("https://a.test/area/pagina", &["y=2; Path=/area"]); assert_eq!(j.riga_per("https://a.test/area/x"), "y=2"); assert_eq!(j.riga_per("https://a.test/altrove"), ""); } #[test] fn secure_non_esce_in_chiaro() { let j = risposta("https://a.test/", &["z=3; Secure; Path=/"]); assert_eq!(j.riga_per("https://a.test/"), "z=3"); assert_eq!(j.riga_per("http://a.test/"), ""); } #[test] fn max_age_zero_cancella() { let mut j = risposta("https://a.test/", &["k=1; Path=/"]); assert_eq!(j.quanti(), 1); j.raccogli( "https://a.test/", &[( "Set-Cookie".to_string(), "k=; Max-Age=0; Path=/".to_string(), )], ); assert_eq!(j.quanti(), 0); assert_eq!(j.riga_per("https://a.test/"), ""); } #[test] fn stesso_nome_si_sostituisce() { let mut j = risposta("https://a.test/", &["k=vecchio; Path=/"]); j.raccogli( "https://a.test/", &[("Set-Cookie".to_string(), "k=nuovo; Path=/".to_string())], ); assert_eq!(j.quanti(), 1); assert_eq!(j.riga_per("https://a.test/"), "k=nuovo"); } #[test] fn piu_cookie_insieme() { let j = risposta("https://a.test/", &["a=1; Path=/", "b=2; Path=/"]); let riga = j.riga_per("https://a.test/"); assert!(riga == "a=1; b=2" || riga == "b=2; a=1", "{}", riga); } #[test] fn senza_set_cookie_non_si_inventa_nulla() { let mut j = CookieJar::new(); j.raccogli( "https://a.test/", &[("Content-Type".to_string(), "text/html".to_string())], ); assert_eq!(j.quanti(), 0); assert_eq!(j.riga_per("https://a.test/"), ""); } }