capy-core 0.10.0

Typed configuration, application context, and errors for the Capy web framework.
Documentation
use crate::{AppError, Result};
use serde::{Deserialize, Serialize};

/// Cookie policy. Cross-site cookies are intentionally outside the built-in path.
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SameSite {
    /// Send cookies for same-site requests and top-level safe navigation.
    #[default]
    Lax,
    /// Send cookies only in same-site contexts.
    Strict,
}

/// Small, typed settings for the optional conventional identity system.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AuthSettings {
    /// Process-local auth abuse limits (`AUTH_THROTTLE_*`).
    pub throttle: AuthThrottleSettings,
    /// Per-application password resource limits.
    pub password: crate::PasswordSettings,
    /// Absolute authenticated session lifetime, in seconds (default: 30 days).
    pub session_lifetime_seconds: u64,
    /// Host-only cookie name. Defaults to `__Host-session` in production.
    pub cookie_name: Option<String>,
    /// Defaults to true in production and false locally. Production rejects false.
    pub secure: Option<bool>,
    /// Browser cookie policy; Lax by default.
    pub same_site: SameSite,
    /// Reset token lifetime, in seconds (default: 30 minutes).
    pub password_reset_lifetime_seconds: u64,
}

impl Default for AuthSettings {
    fn default() -> Self {
        Self {
            throttle: AuthThrottleSettings::default(),
            password: crate::PasswordSettings::default(),
            session_lifetime_seconds: 30 * 86400,
            cookie_name: None,
            secure: None,
            same_site: SameSite::Lax,
            password_reset_lifetime_seconds: 1800,
        }
    }
}

impl AuthSettings {
    /// Resolve the host-only cookie name for an environment.
    pub fn cookie_name(&self, production: bool) -> &str {
        self.cookie_name.as_deref().unwrap_or(if production {
            "__Host-session"
        } else {
            "session"
        })
    }

    /// Resolve the transport policy without weakening production defaults.
    pub fn secure(&self, production: bool) -> bool {
        production || self.secure.unwrap_or(false)
    }

    /// Validate settings when auth is installed; unrelated apps need no auth config.
    pub fn validate(&self, production: bool) -> Result<()> {
        self.password.concurrency()?;
        self.throttle.validate()?;
        if production && !self.throttle.enabled {
            tracing::warn!(event = "auth.throttle.disabled", "Built-in auth throttling is disabled; enforce equivalent abuse limits at your deployment boundary.");
        }
        let cookie = self.cookie_name(production);
        if cookie.is_empty()
            || cookie.len() > 100
            || !cookie
                .bytes()
                .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
            || (cookie.starts_with("__Host-") || cookie.starts_with("__Secure-"))
                && !self.secure(production)
            || production && self.secure == Some(false)
        {
            return Err(AppError::Configuration(
                "Auth requires a valid cookie name and Secure cookies in production.".into(),
            ));
        }
        if !(60..=90 * 86400).contains(&self.session_lifetime_seconds)
            || !(60..=86400).contains(&self.password_reset_lifetime_seconds)
        {
            return Err(AppError::Configuration("Auth session lifetime must be 60..=7776000 seconds; reset lifetime must be 60..=86400 seconds.".into()));
        }
        Ok(())
    }
}

/// Fixed-window abuse budget. Zero never implicitly disables a limit.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct AuthThrottleLimit {
    /// Allowed attempts per window (1..=1000000).
    pub limit: u32,
    /// Window duration in seconds (1..=86400).
    pub window_seconds: u64,
}
impl AuthThrottleLimit {
    fn validate(&self) -> Result<()> {
        if !(1..=1_000_000).contains(&self.limit) || !(1..=86400).contains(&self.window_seconds) {
            return Err(AppError::Configuration("Invalid auth.throttle budget: limit must be 1..=1000000 and window_seconds 1..=86400. Use enabled=false for an explicit opt-out.".into()));
        }
        Ok(())
    }
}

/// Separate fixed windows for CSRF bootstrap, registration, login, reset request
/// and reset completion. Limits apply per action; account keys span client IPs.
/// Application-owned verification endpoints need their own request-level limiter.
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(default, deny_unknown_fields)]
pub struct AuthThrottleSettings {
    /// Default true. False explicitly disables abuse counters, but never proxy or
    /// client-identity validation, CSRF, password capacity or other auth checks.
    pub enabled: bool,
    /// Per-client-IP budget per action; default 60 attempts per 60 seconds.
    pub ip: AuthThrottleLimit,
    /// Per-normalized-account budget per action; default 10 attempts per 60 seconds.
    /// Reset completion additionally keys this budget by the supplied token digest.
    pub account: AuthThrottleLimit,
}
impl Default for AuthThrottleSettings {
    fn default() -> Self {
        Self {
            enabled: true,
            ip: AuthThrottleLimit {
                limit: 60,
                window_seconds: 60,
            },
            account: AuthThrottleLimit {
                limit: 10,
                window_seconds: 60,
            },
        }
    }
}
impl AuthThrottleSettings {
    /// Validate budgets even while disabled, so reenabling cannot install bad bounds.
    pub fn validate(&self) -> Result<()> {
        self.ip.validate()?;
        self.account.validate()
    }
}