use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Cookie {
pub name: String,
pub value: String,
pub path: String,
pub domain: Option<String>,
pub secure: bool,
pub http_only: bool,
pub same_site: SameSite,
pub max_age: Option<i64>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SameSite {
Strict,
Lax,
#[default]
None,
}
impl Cookie {
pub fn new(name: impl Into<String>, value: impl Into<String>) -> Self {
Self {
name: name.into(),
value: value.into(),
path: "/".to_string(),
domain: None,
secure: false,
http_only: true,
same_site: SameSite::Lax,
max_age: None,
}
}
pub fn path(mut self, path: impl Into<String>) -> Self {
self.path = path.into();
self
}
pub fn domain(mut self, domain: impl Into<String>) -> Self {
self.domain = Some(domain.into());
self
}
pub fn with_secure(mut self, secure: bool) -> Self {
self.secure = secure;
self
}
pub fn with_http_only(mut self, http_only: bool) -> Self {
self.http_only = http_only;
self
}
pub fn with_same_site(mut self, same_site: SameSite) -> Self {
self.same_site = same_site;
self
}
pub fn with_max_age(mut self, seconds: i64) -> Self {
self.max_age = Some(seconds);
self
}
pub fn to_set_cookie(&self) -> String {
let mut out = format!("{}={}", self.name, self.value);
out.push_str(&format!("; Path={}", self.path));
if let Some(domain) = &self.domain {
out.push_str(&format!("; Domain={}", domain));
}
if self.secure {
out.push_str("; Secure");
}
if self.http_only {
out.push_str("; HttpOnly");
}
let same_site = match self.same_site {
SameSite::Strict => "Strict",
SameSite::Lax => "Lax",
SameSite::None => "None",
};
out.push_str(&format!("; SameSite={}", same_site));
if let Some(max_age) = self.max_age {
out.push_str(&format!("; Max-Age={}", max_age));
}
out
}
}
pub type CookieKey = (String, String);
#[derive(Debug, Clone, Default)]
pub struct CookieJar {
queued: HashMap<CookieKey, Cookie>,
}
impl CookieJar {
pub fn new() -> Self {
Self::default()
}
pub fn queue(&mut self, cookie: impl Into<Cookie>) {
let cookie = cookie.into();
let key = (cookie.name.clone(), cookie.path.clone());
self.queued.insert(key, cookie);
}
pub fn unqueue(&mut self, name: &str, path: Option<&str>) {
let path = path.unwrap_or("/").to_string();
self.queued.remove(&(name.to_string(), path));
}
pub fn get_queued_cookies(&self) -> &HashMap<CookieKey, Cookie> {
&self.queued
}
pub fn queued(&self, name: &str, path: Option<&str>) -> Option<&Cookie> {
let path = path.unwrap_or("/").to_string();
self.queued
.get(&(name.to_string(), path))
.or_else(|| self.queued.values().find(|c| c.name == name))
}
pub fn queued_cookies(&self) -> impl Iterator<Item = &Cookie> {
self.queued.values()
}
pub fn has_queued(&self, name: &str) -> bool {
self.queued.keys().any(|(n, _)| n == name)
}
pub fn forget(&mut self, name: &str, path: Option<&str>) {
self.unqueue(name, path);
}
pub fn to_set_cookie_headers(&self) -> Vec<String> {
self.queued.values().map(|c| c.to_set_cookie()).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn queue_and_queued_by_default_path() {
let mut jar = CookieJar::new();
jar.queue(Cookie::new("session", "abc"));
let cookie = jar.queued("session", None);
assert!(cookie.is_some());
assert_eq!(cookie.unwrap().value, "abc");
}
#[test]
fn same_name_different_paths_do_not_clobber() {
let mut jar = CookieJar::new();
jar.queue(Cookie::new("token", "root").path("/"));
jar.queue(Cookie::new("token", "admin").path("/admin"));
assert_eq!(jar.queued("token", Some("/")).unwrap().value, "root");
assert_eq!(jar.queued("token", Some("/admin")).unwrap().value, "admin");
assert_eq!(jar.queued_cookies().count(), 2);
}
#[test]
fn queued_falls_back_to_any_path_for_name() {
let mut jar = CookieJar::new();
jar.queue(Cookie::new("token", "v").path("/weird"));
assert_eq!(jar.queued("token", None).unwrap().value, "v");
}
#[test]
fn unqueue_removes_by_name_and_path() {
let mut jar = CookieJar::new();
jar.queue(Cookie::new("a", "1").path("/"));
jar.queue(Cookie::new("a", "2").path("/admin"));
jar.unqueue("a", Some("/admin"));
assert_eq!(jar.queued_cookies().count(), 1);
assert_eq!(jar.queued("a", Some("/")).unwrap().value, "1");
}
#[test]
fn forget_removes_cookie() {
let mut jar = CookieJar::new();
jar.queue(Cookie::new("sid", "x"));
jar.forget("sid", None);
assert!(!jar.has_queued("sid"));
}
#[test]
fn to_set_cookie_header_renders_attributes() {
let cookie = Cookie::new("name", "value")
.path("/app")
.domain("example.com")
.with_secure(true)
.with_http_only(true)
.with_same_site(SameSite::Strict)
.with_max_age(3600);
let header = cookie.to_set_cookie();
assert!(header.starts_with("name=value; Path=/app"));
assert!(header.contains("Domain=example.com"));
assert!(header.contains("Secure"));
assert!(header.contains("HttpOnly"));
assert!(header.contains("SameSite=Strict"));
assert!(header.contains("Max-Age=3600"));
}
#[test]
fn builder_queues_cookie() {
let mut jar = CookieJar::new();
jar.queue(Cookie::new("legacy", "v").path("/legacy"));
jar.queue(Cookie::new("legacy", "root"));
assert_eq!(jar.queued("legacy", Some("/")).unwrap().value, "root");
assert_eq!(jar.queued("legacy", None).unwrap().value, "root");
assert_eq!(jar.queued_cookies().count(), 2);
}
}