use std::{
io::{BufRead, Write},
sync::{Mutex, PoisonError},
};
use http::{
HeaderMap, HeaderValue, Uri,
header::{COOKIE, SET_COOKIE},
};
use url::Url;
use crate::{Error, Result};
pub struct CookieJar {
store: Mutex<cookie_store::CookieStore>,
}
impl CookieJar {
#[must_use]
pub fn new() -> Self {
Self {
store: Mutex::new(cookie_store::CookieStore::default()),
}
}
pub fn clear(&self) {
self.store
.lock()
.unwrap_or_else(PoisonError::into_inner)
.clear();
}
pub fn from_json(reader: impl BufRead) -> Result<Self> {
cookie_store::serde::json::load(reader)
.map(|store| Self {
store: Mutex::new(store),
})
.map_err(|_| Error::request("cookie jar JSON could not be loaded"))
}
pub fn save_json(&self, writer: &mut impl Write) -> Result<()> {
let store = self.store.lock().unwrap_or_else(PoisonError::into_inner);
cookie_store::serde::json::save(&store, writer).map_err(|_| Error::body())
}
pub(crate) fn add_request_header(&self, headers: &mut HeaderMap, uri: &Uri) {
if headers.contains_key(COOKIE) {
return;
}
let Ok(url) = Url::parse(&uri.to_string()) else {
return;
};
let store = self.store.lock().unwrap_or_else(PoisonError::into_inner);
let value = store
.get_request_values(&url)
.map(|(name, value)| format!("{name}={value}"))
.collect::<Vec<_>>()
.join("; ");
if !value.is_empty()
&& let Ok(value) = HeaderValue::from_str(&value)
{
headers.insert(COOKIE, value);
}
}
pub(crate) fn store_response_headers(&self, headers: &HeaderMap, uri: &Uri) {
let Ok(url) = Url::parse(&uri.to_string()) else {
return;
};
let mut store = self.store.lock().unwrap_or_else(PoisonError::into_inner);
for value in headers.get_all(SET_COOKIE) {
if let Ok(value) = value.to_str() {
let _ = store.parse(value, &url);
}
}
}
}
impl Default for CookieJar {
fn default() -> Self {
Self::new()
}
}
impl std::fmt::Debug for CookieJar {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.debug_struct("CookieJar").finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn persistent_cookies_round_trip_without_exposing_values_in_debug() {
let jar = CookieJar::new();
let mut response = HeaderMap::new();
response.append(
SET_COOKIE,
"session=secret; Path=/; Max-Age=3600".parse().unwrap(),
);
jar.store_response_headers(&response, &"https://example.com/login".parse().unwrap());
let mut json = Vec::new();
jar.save_json(&mut json).unwrap();
let restored = CookieJar::from_json(json.as_slice()).unwrap();
let mut request = HeaderMap::new();
restored.add_request_header(
&mut request,
&"https://example.com/account".parse().unwrap(),
);
assert_eq!(request[COOKIE], "session=secret");
assert!(!format!("{restored:?}").contains("secret"));
}
}