Skip to main content

capy_core/
auth_config.rs

1use crate::{AppError, Result};
2use serde::{Deserialize, Serialize};
3
4/// Cookie policy. Cross-site cookies are intentionally outside the built-in path.
5#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
6#[serde(rename_all = "lowercase")]
7pub enum SameSite {
8    /// Send cookies for same-site requests and top-level safe navigation.
9    #[default]
10    Lax,
11    /// Send cookies only in same-site contexts.
12    Strict,
13}
14
15/// Small, typed settings for the optional conventional identity system.
16#[derive(Clone, Debug, Deserialize, Serialize)]
17#[serde(default, deny_unknown_fields)]
18pub struct AuthSettings {
19    /// Per-application password resource limits.
20    pub password: crate::PasswordSettings,
21    /// Absolute authenticated session lifetime, in seconds (default: 30 days).
22    pub session_lifetime_seconds: u64,
23    /// Host-only cookie name. Defaults to `__Host-session` in production.
24    pub cookie_name: Option<String>,
25    /// Defaults to true in production and false locally. Production rejects false.
26    pub secure: Option<bool>,
27    /// Browser cookie policy; Lax by default.
28    pub same_site: SameSite,
29    /// Reset token lifetime, in seconds (default: 30 minutes).
30    pub password_reset_lifetime_seconds: u64,
31}
32
33impl Default for AuthSettings {
34    fn default() -> Self {
35        Self {
36            password: crate::PasswordSettings::default(),
37            session_lifetime_seconds: 30 * 86400,
38            cookie_name: None,
39            secure: None,
40            same_site: SameSite::Lax,
41            password_reset_lifetime_seconds: 1800,
42        }
43    }
44}
45
46impl AuthSettings {
47    /// Resolve the host-only cookie name for an environment.
48    pub fn cookie_name(&self, production: bool) -> &str {
49        self.cookie_name.as_deref().unwrap_or(if production {
50            "__Host-session"
51        } else {
52            "session"
53        })
54    }
55
56    /// Resolve the transport policy without weakening production defaults.
57    pub fn secure(&self, production: bool) -> bool {
58        production || self.secure.unwrap_or(false)
59    }
60
61    /// Validate settings when auth is installed; unrelated apps need no auth config.
62    pub fn validate(&self, production: bool) -> Result<()> {
63        self.password.concurrency()?;
64        let cookie = self.cookie_name(production);
65        if cookie.is_empty()
66            || cookie.len() > 100
67            || !cookie
68                .bytes()
69                .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
70            || (cookie.starts_with("__Host-") || cookie.starts_with("__Secure-"))
71                && !self.secure(production)
72            || production && self.secure == Some(false)
73        {
74            return Err(AppError::Configuration(
75                "Auth requires a valid cookie name and Secure cookies in production.".into(),
76            ));
77        }
78        if !(60..=90 * 86400).contains(&self.session_lifetime_seconds)
79            || !(60..=86400).contains(&self.password_reset_lifetime_seconds)
80        {
81            return Err(AppError::Configuration("Auth session lifetime must be 60..=7776000 seconds; reset lifetime must be 60..=86400 seconds.".into()));
82        }
83        Ok(())
84    }
85}