ch-auth 0.1.0

Authentication and session primitives with explicit security policies
Documentation
use std::borrow::Cow;
use std::fmt;

use axum_session::databases::SessionNullPool;
use axum_session::{Key, SameSite, SessionConfig, SessionMode};
use axum_session_auth::AuthSession as AxumAuthSession;
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD};
use getrandom::fill;
use thiserror::Error;
use zeroize::Zeroizing;

const SESSION_KEY_LENGTH: usize = 64;

/// Secret key material used to sign and encrypt session cookies.
///
/// The wrapper deliberately does not expose the decoded bytes. Its backing
/// allocation is cleared when it is dropped, including after
/// [`build_session_config`] has transferred the material into `axum_session`.
pub struct SessionKey(Zeroizing<Vec<u8>>);

impl SessionKey {
    /// Decodes an exactly 64-byte key from standard or URL-safe base64.
    pub fn decode(encoded: &str) -> Result<Self, SessionKeyError> {
        let encoded = encoded.trim();
        let decoded = Zeroizing::new(
            [STANDARD, STANDARD_NO_PAD, URL_SAFE, URL_SAFE_NO_PAD]
                .into_iter()
                .find_map(|engine| engine.decode(encoded).ok())
                .ok_or(SessionKeyError::InvalidBase64)?,
        );

        if decoded.len() != SESSION_KEY_LENGTH {
            return Err(SessionKeyError::InvalidLength {
                actual: decoded.len(),
            });
        }

        Ok(Self(decoded))
    }

    /// Loads the conventional `SESSION_KEY` value or its `SESSION_KEY_FILE`
    /// companion.
    ///
    /// Non-debug builds require a persistent key. Debug builds generate a
    /// process-local cryptographic key when neither source is configured, so
    /// restarting the process invalidates its development sessions.
    pub fn from_environment() -> Result<Self, SessionKeyEnvironmentError> {
        resolve_session_key(
            ch_config::environment::value("SESSION_KEY")?,
            cfg!(debug_assertions),
        )
    }

    /// Generates a process-local key for explicitly ephemeral sessions.
    pub fn generate_ephemeral() -> Result<Self, SessionKeyError> {
        let mut bytes = Zeroizing::new(vec![0_u8; SESSION_KEY_LENGTH]);
        fill(bytes.as_mut_slice()).map_err(SessionKeyError::Generation)?;
        Ok(Self(bytes))
    }
}

impl fmt::Debug for SessionKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("SessionKey").field(&"[REDACTED]").finish()
    }
}

/// Failure to decode or generate session key material.
#[derive(Debug, Error)]
pub enum SessionKeyError {
    /// The configured value is not valid supported base64.
    #[error("session key must be valid base64")]
    InvalidBase64,
    /// The decoded key does not have the required size.
    #[error("session key must decode to exactly 64 bytes, got {actual}")]
    InvalidLength {
        /// Number of bytes produced by decoding the configured value.
        actual: usize,
    },
    /// The operating system could not provide cryptographic randomness.
    #[error("failed to generate an ephemeral session key")]
    Generation(#[source] getrandom::Error),
}

/// Failure to load session key material from the process environment.
#[derive(Debug, Error)]
pub enum SessionKeyEnvironmentError {
    /// The configured environment source could not be resolved safely.
    #[error(transparent)]
    Configuration(#[from] ch_config::config::ConfigError),
    /// The configured or generated key material is invalid.
    #[error(transparent)]
    Key(#[from] SessionKeyError),
    /// A persistent key is mandatory outside debug builds.
    #[error("SESSION_KEY or SESSION_KEY_FILE is required outside debug builds")]
    Missing,
}

fn resolve_session_key(
    configured: Option<String>,
    allow_ephemeral: bool,
) -> Result<SessionKey, SessionKeyEnvironmentError> {
    match configured {
        Some(encoded) => Ok(SessionKey::decode(&encoded)?),
        None if allow_ephemeral => {
            tracing::warn!(
                "SESSION_KEY is not configured; using an ephemeral development session key"
            );
            Ok(SessionKey::generate_ephemeral()?)
        }
        None => Err(SessionKeyEnvironmentError::Missing),
    }
}

/// Explicit cookie policy for authenticated sessions.
///
/// There is intentionally no default implementation: each application owns
/// its cookie name and transport policy.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SessionPolicy {
    cookie_name: Cow<'static, str>,
    same_site: SameSite,
    secure: bool,
    http_only: bool,
    path: Cow<'static, str>,
}

impl SessionPolicy {
    /// Validates and constructs a complete session-cookie policy.
    pub fn new(
        cookie_name: impl Into<Cow<'static, str>>,
        same_site: SameSite,
        secure: bool,
        http_only: bool,
        path: impl Into<Cow<'static, str>>,
    ) -> Result<Self, SessionPolicyError> {
        let cookie_name = cookie_name.into();
        let path = path.into();

        if !is_cookie_name(cookie_name.as_ref()) {
            return Err(SessionPolicyError::InvalidCookieName);
        }
        if !is_cookie_path(path.as_ref()) {
            return Err(SessionPolicyError::InvalidCookiePath);
        }
        if same_site == SameSite::None && !secure {
            return Err(SessionPolicyError::SameSiteNoneRequiresSecure);
        }
        if cookie_name.starts_with("__Secure-") && !secure {
            return Err(SessionPolicyError::SecurePrefixRequiresSecure);
        }
        if cookie_name.starts_with("__Host-") && (!secure || path != "/") {
            return Err(SessionPolicyError::HostPrefixRequiresSecureRootPath);
        }

        Ok(Self {
            cookie_name,
            same_site,
            secure,
            http_only,
            path,
        })
    }

    /// Returns the session cookie name.
    pub fn cookie_name(&self) -> &str {
        self.cookie_name.as_ref()
    }

    /// Returns the cookie's `SameSite` policy.
    pub fn same_site(&self) -> SameSite {
        self.same_site
    }

    /// Reports whether the cookie is restricted to secure transports.
    pub fn secure(&self) -> bool {
        self.secure
    }

    /// Reports whether browser scripts are denied cookie access.
    pub fn http_only(&self) -> bool {
        self.http_only
    }

    /// Returns the URL path to which the cookie is scoped.
    pub fn path(&self) -> &str {
        self.path.as_ref()
    }
}

/// Failure to construct a valid session-cookie policy.
#[derive(Clone, Copy, Debug, Eq, Error, PartialEq)]
pub enum SessionPolicyError {
    /// The cookie name is empty or contains a forbidden separator/control.
    #[error("session cookie name is invalid")]
    InvalidCookieName,
    /// The cookie path is not an absolute, header-safe path.
    #[error("session cookie path must be absolute and header-safe")]
    InvalidCookiePath,
    /// Browsers require secure transport for `SameSite=None` cookies.
    #[error("SameSite=None requires a secure session cookie")]
    SameSiteNoneRequiresSecure,
    /// The standard `__Secure-` prefix requires secure transport.
    #[error("a __Secure- cookie name requires a secure session cookie")]
    SecurePrefixRequiresSecure,
    /// The standard `__Host-` prefix requires secure transport and root scope.
    #[error("a __Host- cookie name requires a secure session cookie scoped to /")]
    HostPrefixRequiresSecureRootPath,
}

/// Builds the shared Axum session configuration from application-owned inputs.
pub fn build_session_config(policy: SessionPolicy, key: SessionKey) -> SessionConfig {
    let key = Key::try_from(key.0.as_slice())
        .expect("SessionKey guarantees exactly 64 bytes of key material");

    SessionConfig::default()
        .with_session_name(policy.cookie_name)
        .with_cookie_path(policy.path)
        .with_cookie_same_site(policy.same_site)
        .with_secure(policy.secure)
        .with_http_only(policy.http_only)
        .with_mode(SessionMode::OptIn)
        .with_max_age(None)
        // Transport metadata is unstable for clients behind proxies. Cookie
        // integrity is owned by the signing key instead.
        .with_ip_and_user_agent(false)
        .with_key(key)
}

fn is_cookie_name(value: &str) -> bool {
    !value.is_empty()
        && value.bytes().all(|byte| {
            byte.is_ascii()
                && !byte.is_ascii_control()
                && !matches!(
                    byte,
                    b' ' | b'('
                        | b')'
                        | b'<'
                        | b'>'
                        | b'@'
                        | b','
                        | b';'
                        | b':'
                        | b'\\'
                        | b'"'
                        | b'/'
                        | b'['
                        | b']'
                        | b'?'
                        | b'='
                        | b'{'
                        | b'}'
                )
        })
}

fn is_cookie_path(value: &str) -> bool {
    value.starts_with('/')
        && value
            .bytes()
            .all(|byte| byte.is_ascii() && !byte.is_ascii_control() && byte != b';')
}

/// Authenticated Axum session using the application's database handle directly.
pub type AuthSession<User, Database> = AxumAuthSession<User, String, SessionNullPool, Database>;

#[cfg(test)]
mod tests {
    use axum_session::SameSite;
    use base64::Engine;

    use super::{
        SessionKey, SessionKeyEnvironmentError, SessionKeyError, SessionPolicy, SessionPolicyError,
        build_session_config, resolve_session_key,
    };

    #[test]
    fn session_key_accepts_supported_base64_without_exposing_material() {
        let encoded = base64::engine::general_purpose::STANDARD.encode([7_u8; 64]);
        let key = SessionKey::decode(&encoded).expect("64-byte key should decode");

        assert_eq!(format!("{key:?}"), "SessionKey(\"[REDACTED]\")");
        assert!(matches!(
            SessionKey::decode("not-base64"),
            Err(SessionKeyError::InvalidBase64)
        ));
        assert!(matches!(
            SessionKey::decode(
                &base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([9_u8; 32])
            ),
            Err(SessionKeyError::InvalidLength { actual: 32 })
        ));
    }

    #[test]
    fn environment_key_policy_requires_release_material_and_allows_debug_ephemeral_keys() {
        assert!(matches!(
            resolve_session_key(None, false),
            Err(SessionKeyEnvironmentError::Missing)
        ));
        assert!(resolve_session_key(None, true).is_ok());

        let encoded = base64::engine::general_purpose::STANDARD.encode([5_u8; 64]);
        assert!(resolve_session_key(Some(encoded), false).is_ok());
    }

    #[test]
    fn session_policy_validates_cookie_invariants() {
        let policy = SessionPolicy::new("session", SameSite::Lax, false, true, "/")
            .expect("common local policy should be valid");

        assert_eq!(policy.cookie_name(), "session");
        assert_eq!(policy.same_site(), SameSite::Lax);
        assert!(!policy.secure());
        assert!(policy.http_only());
        assert_eq!(policy.path(), "/");
        assert_eq!(
            SessionPolicy::new("bad cookie", SameSite::Lax, false, true, "/"),
            Err(SessionPolicyError::InvalidCookieName)
        );
        assert_eq!(
            SessionPolicy::new("session", SameSite::Lax, false, true, "relative"),
            Err(SessionPolicyError::InvalidCookiePath)
        );
        assert_eq!(
            SessionPolicy::new("session", SameSite::None, false, true, "/"),
            Err(SessionPolicyError::SameSiteNoneRequiresSecure)
        );
        assert_eq!(
            SessionPolicy::new("__Host-session", SameSite::Lax, true, true, "/account"),
            Err(SessionPolicyError::HostPrefixRequiresSecureRootPath)
        );
    }

    #[test]
    fn session_config_is_built_only_from_explicit_inputs() {
        let policy = SessionPolicy::new("session", SameSite::Strict, true, true, "/")
            .expect("test policy should be valid");
        let key = SessionKey::decode(&base64::engine::general_purpose::STANDARD.encode([3_u8; 64]))
            .expect("test key should decode");

        let config = build_session_config(policy, key);
        let debug = format!("{config:?}");

        assert_eq!(config.get_session_name(), "session");
        assert!(debug.contains("cookie_http_only: true"));
        assert!(debug.contains("cookie_path: \"/\""));
        assert!(debug.contains("cookie_same_site: Strict"));
        assert!(debug.contains("cookie_secure: true"));
        assert!(!debug.contains(&base64::engine::general_purpose::STANDARD.encode([3_u8; 64])));
    }
}