glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Request cookies, with signed and encrypted variants.
//!
//! Changes made through `Cookies` are written back as `Set-Cookie` headers
//! when the response is sent. Cookies default to `Path=/` and `HttpOnly`.

use std::sync::{Arc, Mutex, MutexGuard};

use cookie::CookieJar;
use http::HeaderMap;
use http::header::{COOKIE, SET_COOKIE};

pub use cookie::{Cookie, Key, SameSite};

#[derive(Clone)]
pub struct Cookies {
    jar: Arc<Mutex<CookieJar>>,
    key: Arc<Key>,
}

impl Cookies {
    pub(crate) fn from_headers(headers: &HeaderMap, key: Arc<Key>) -> Self {
        let mut jar = CookieJar::new();
        for value in headers.get_all(COOKIE) {
            let Ok(value) = value.to_str() else { continue };
            for cookie in Cookie::split_parse_encoded(value.to_owned()).flatten() {
                jar.add_original(cookie.into_owned());
            }
        }
        Self {
            jar: Arc::new(Mutex::new(jar)),
            key,
        }
    }

    fn jar(&self) -> MutexGuard<'_, CookieJar> {
        // A poisoned jar only means another holder panicked mid-update; the
        // jar itself is still structurally valid.
        self.jar.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// A plain cookie's value. The client can read and forge these.
    pub fn get(&self, name: &str) -> Option<String> {
        self.jar().get(name).map(|c| c.value().to_owned())
    }

    pub fn add(&self, cookie: impl Into<Cookie<'static>>) {
        self.jar().add(with_defaults(cookie.into()));
    }

    pub fn remove(&self, name: &str) {
        self.jar().remove(removal(name));
    }

    /// A signed cookie's value: readable by the client but tamper-proof.
    /// One signed with a previous `secret_key_base` still reads.
    pub fn get_signed(&self, name: &str) -> Option<String> {
        let jar = self.jar();
        std::iter::once((*self.key).clone())
            .chain(crate::request::previous_keys())
            .find_map(|key| jar.signed(&key).get(name).map(|c| c.value().to_owned()))
    }

    pub fn add_signed(&self, cookie: impl Into<Cookie<'static>>) {
        self.jar()
            .signed_mut(&self.key)
            .add(with_defaults(cookie.into()));
    }

    /// An encrypted cookie's value: neither readable nor forgeable. One
    /// encrypted with a previous `secret_key_base` still reads.
    pub fn get_private(&self, name: &str) -> Option<String> {
        self.get_private_rotated(name).map(|(value, _)| value)
    }

    /// An encrypted cookie's value, and whether an old key encrypted it
    /// (so it's worth writing again with the current one).
    pub(crate) fn get_private_rotated(&self, name: &str) -> Option<(String, bool)> {
        let jar = self.jar();
        if let Some(cookie) = jar.private(&self.key).get(name) {
            return Some((cookie.value().to_owned(), false));
        }
        crate::request::previous_keys().iter().find_map(|key| {
            jar.private(key)
                .get(name)
                .map(|c| (c.value().to_owned(), true))
        })
    }

    pub fn add_private(&self, cookie: impl Into<Cookie<'static>>) {
        self.jar()
            .private_mut(&self.key)
            .add(with_defaults(cookie.into()));
    }

    pub(crate) fn write_to(&self, headers: &mut HeaderMap) {
        for cookie in self.jar().delta() {
            match cookie.encoded().to_string().try_into() {
                Ok(value) => {
                    headers.append(SET_COOKIE, value);
                }
                Err(_) => tracing::warn!("dropping cookie `{}` with invalid value", cookie.name()),
            }
        }
    }
}

fn with_defaults(mut cookie: Cookie<'static>) -> Cookie<'static> {
    if cookie.path().is_none() {
        cookie.set_path("/");
    }
    if cookie.http_only().is_none() {
        cookie.set_http_only(true);
    }
    cookie
}

fn removal(name: &str) -> Cookie<'static> {
    Cookie::build(name.to_owned()).path("/").build()
}