use std::fmt;
use std::time::Duration;
use super::SessionId;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SameSite {
Strict,
Lax,
None,
}
impl fmt::Display for SameSite {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Self::Strict => "Strict",
Self::Lax => "Lax",
Self::None => "None",
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CookieConfig {
pub name: String,
pub path: String,
pub domain: Option<String>,
pub secure: bool,
pub http_only: bool,
pub same_site: SameSite,
}
impl Default for CookieConfig {
fn default() -> Self {
Self {
name: "__Host-id_session".to_owned(),
path: "/".to_owned(),
domain: None,
secure: true,
http_only: true,
same_site: SameSite::Lax,
}
}
}
impl CookieConfig {
pub fn set_cookie(&self, id: &SessionId, max_age: Duration) -> String {
self.render(id.as_str(), max_age.as_secs())
}
pub fn clear_cookie(&self) -> String {
self.render("", 0)
}
fn render(&self, value: &str, max_age: u64) -> String {
let mut out = format!(
"{}={value}; Path={}; Max-Age={max_age}",
self.name, self.path
);
if let Some(domain) = &self.domain {
out.push_str("; Domain=");
out.push_str(domain);
}
if self.secure {
out.push_str("; Secure");
}
if self.http_only {
out.push_str("; HttpOnly");
}
out.push_str("; SameSite=");
out.push_str(&self.same_site.to_string());
out
}
pub fn find(&self, cookie_header: &str) -> Option<SessionId> {
cookie_header
.split(';')
.filter_map(|pair| pair.trim().split_once('='))
.filter(|(name, _)| *name == self.name)
.find_map(|(_, value)| SessionId::parse(value.trim_matches('"')))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_cookie_is_host_prefixed_secure_http_only_lax() {
let id = SessionId::generate().unwrap();
let header = CookieConfig::default().set_cookie(&id, Duration::from_secs(1800));
assert_eq!(
header,
format!(
"__Host-id_session={}; Path=/; Max-Age=1800; Secure; HttpOnly; SameSite=Lax",
id.as_str()
)
);
}
#[test]
fn clear_cookie_expires_it_now() {
let header = CookieConfig::default().clear_cookie();
assert!(
header.starts_with("__Host-id_session=; Path=/; Max-Age=0;"),
"{header}"
);
}
#[test]
fn optional_attributes_render() {
let cfg = CookieConfig {
name: "sid".into(),
domain: Some("example.com".into()),
secure: false,
http_only: false,
same_site: SameSite::Strict,
..CookieConfig::default()
};
let id = SessionId::generate().unwrap();
let header = cfg.set_cookie(&id, Duration::from_secs(5));
assert!(
header.ends_with("; Domain=example.com; SameSite=Strict"),
"{header}"
);
assert!(!header.contains("Secure") && !header.contains("HttpOnly"));
assert_eq!(SameSite::None.to_string(), "None");
}
#[test]
fn find_reads_the_id_from_a_cookie_header() {
let cfg = CookieConfig::default();
let id = SessionId::generate().unwrap();
let header = format!("theme=dark; __Host-id_session={}; other=1", id.as_str());
assert_eq!(cfg.find(&header), Some(id.clone()));
let quoted = format!("__Host-id_session=\"{}\"", id.as_str());
assert_eq!(cfg.find("ed), Some(id.clone()));
let dup = format!("__Host-id_session=junk; __Host-id_session={}", id.as_str());
assert_eq!(cfg.find(&dup), Some(id));
assert_eq!(cfg.find("theme=dark"), None);
assert_eq!(cfg.find(""), None);
assert_eq!(cfg.find("__Host-id_session=nope"), None);
}
}