cataclysm 0.5.5

A simple http framework
Documentation
use openssl::{
    pkey::PKey,
    symm::Cipher
};
use crate::Error;
use rand::Rng;
use std::time::Duration;
use chrono::{DateTime, Utc};

pub use self::signed_cookie_session::SignedCookieSession;
mod signed_cookie_session;

pub use self::encrypted_cookie_session::EncryptedCookieSession;
mod encrypted_cookie_session;

/// Enum to indicate a same site policy in the cookie builder
#[derive(Clone)]
pub enum SameSite {
    Strict,
    Lax,
    None
}

impl SameSite {
    fn to_cookie_same_site(&self) -> cookie::SameSite {
        match self {
            SameSite::Strict => cookie::SameSite::Strict,
            SameSite::Lax => cookie::SameSite::Lax,
            SameSite::None => cookie::SameSite::None
        }
    }
}

/// Session builder implementation, cookie based.
#[derive(Clone)]
pub struct CookieSessionBuilder {
    cookie_name: String,
    path: Option<String>,
    domain: Option<String>,
    expires: Option<DateTime<Utc>>,
    max_age: Option<Duration>,
    secure: Option<bool>,
    http_only: Option<bool>,
    same_site: Option<SameSite>,
    force_failure: bool
}

impl CookieSessionBuilder {
    /// Creates a new cookie session creator
    ///
    /// By default, the following rules apply to the cookie parameters
    ///
    /// * `path`: No path provided (`None`)
    /// * `domain`: No domain provided (`None`)
    /// * `expires`: No expiration provided (`None`)
    /// * `max_age`: No max age provided (`None`)
    /// * `secure`: The secure flag is se to false
    /// * `http_only`: The http only flag is set to false
    /// * `same_site`: No same site policy is provided
    /// * `force_failure`: The force failure flag is set to false
    pub fn new() -> Self {
        CookieSessionBuilder {
            cookie_name: "cataclysm-session".to_string(),
            path: None,
            domain: None,
            expires: None,
            max_age: None,
            secure: None,
            http_only: None,
            same_site: None,
            force_failure: false
        }
    }

    /// Sets a custom `name` for the cookie.
    ///
    /// By default, `cataclysm-session` is used.
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// 
    /// let cookie_session = CookieSessionBuilder::new()
    ///     .name("my-app-session");
    /// ```
    pub fn name<A: Into<String>>(mut self, name: A) -> Self {
        self.cookie_name = name.into();
        self
    }

    /// Sets a custom `path` for generated cookies
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// 
    /// let cookie_session = CookieSessionBuilder::new()
    ///     .path("/applies/only/here");
    /// ```
    pub fn path<A: Into<String>>(mut self, path: A) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Sets a custom `domain` for generated cookies
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// 
    /// let cookie_session = CookieSessionBuilder::new()
    ///     .domain("example.com");
    /// ```
    pub fn domain<A: Into<String>>(mut self, domain: A) -> Self {
        self.domain = Some(domain.into());
        self
    }

    /// Sets a duration for the cookie (that is, using the `expires` field)
    ///
    /// You should try to avoid this method, and use `max_age` instead.
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// use chrono::{DateTime, Utc, Duration};
    /// 
    /// let cookie_session = CookieSessionBuilder::new().expires(Utc::now() + Duration::weeks(52));
    /// ```
    ///
    /// Please note that the "expires" field will not update the provided date as time goes by. Use the [max_age](CookieSessionBuilder::max_age) method instead.
    pub fn expires(mut self, expires: DateTime<Utc>) -> Self {
        self.expires = Some(expires);
        self
    }

    /// Sets a duration for the cookie (that is, using the `max_age` field)
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// use std::time::Duration;
    /// 
    /// let cookie_session = CookieSessionBuilder::new().max_age(Duration::from_secs(3_600 * 6));
    /// ```
    pub fn max_age(mut self, max_age: Duration) -> Self {
        self.max_age = Some(max_age);
        self
    }

    /// Sets the `secure` field in the cookie
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// 
    /// let cookie_session = CookieSessionBuilder::new().secure(true);
    /// ```
    pub fn secure(mut self, secure: bool) -> Self {
        self.secure = Some(secure);
        self
    }

    /// Sets the `http_only` field in the cookie
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// 
    /// let cookie_session = CookieSessionBuilder::new().http_only(true);
    /// ```
    pub fn http_only(mut self, http_only: bool) -> Self {
        self.http_only = Some(http_only);
        self
    }

    /// Sets the `same_site` field in the cookie
    ///
    /// ```rust,no_run
    /// use cataclysm::session::{CookieSessionBuilder, SameSite};
    /// 
    /// let cookie_session = CookieSessionBuilder::new().same_site(SameSite::Lax);
    /// ```
    pub fn same_site(mut self, same_site: SameSite) -> Self {
        self.same_site = Some(same_site);
        self
    }

    /// Forces errors at cookie parsing to return an error response instead of an empty session
    ///
    /// ```rust,no_run
    /// use cataclysm::session::{CookieSessionBuilder};
    /// 
    /// let cookie_session = CookieSessionBuilder::new().force_failure(true);
    /// ```
    pub fn force_failure(mut self, force_failure: bool) -> Self {
        self.force_failure = force_failure;
        self
    }

    /// Creates a cookie handler with signed cookies
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// 
    /// let signed_cookie_session = CookieSessionBuilder::new()
    ///     .signed(Some("really secret!".to_string()));
    ///     // Much better to use `.signed(None)`
    /// ```
    ///
    /// If no secret is provided, a random 32 bit key will be used. It is recommended to use the function this way. Signatures are performed using the hmac algorithm, with sha256 as hash function.
    pub fn signed(self, secret: Option<String>) -> Result<SignedCookieSession, Error> {
        let raw_key = if let Some(secret) = secret {
            secret.into_bytes()
        } else {
            let mut random_key: Vec<u8> = vec![0;32];
            let mut rng = rand::rng();
            rng.fill_bytes(random_key.as_mut_slice());
            random_key
        };

        let key = PKey::hmac(&raw_key[..])?;
        Ok(SignedCookieSession {
            raw_key,
            key,
            cookie_name: self.cookie_name,
            path: self.path,
            domain: self.domain,
            expires: self.expires,
            max_age: self.max_age,
            secure: self.secure,
            http_only: self.http_only,
            same_site: self.same_site,
            force_failure: self.force_failure
        })
    }

    /// Creates a cookie handler with signed cookies
    ///
    /// ```rust,no_run
    /// use cataclysm::session::CookieSessionBuilder;
    /// 
    /// let signed_cookie_session = CookieSessionBuilder::new()
    ///     .encrypted(Some("really secret!".to_string()));
    ///     // Much better to use `.encrypted(None)`
    /// ```
    ///
    /// If no secret is provided, a random 32 bit key will be used. It is recommended to use the function this way. Encryption is performed with AES-256 in CBC mode, with a 32 bit random initialization vector.
    pub fn encrypted(self, secret: Option<String>) -> Result<EncryptedCookieSession, Error> {
        let key = if let Some(secret) = secret {
            secret.into_bytes()
        } else {
            let mut rng = rand::rng();
            let mut random_key: Vec<u8> = vec![0;32];
            rng.fill_bytes(random_key.as_mut_slice());
            random_key
        };
        Ok(EncryptedCookieSession {
            cipher: Cipher::aes_256_cbc(),
            key,
            cookie_name: self.cookie_name,
            path: self.path,
            domain: self.domain,
            expires: self.expires,
            max_age: self.max_age,
            secure: self.secure,
            http_only: self.http_only,
            same_site: self.same_site,
            force_failure: self.force_failure
        })
    }
}