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    /// Absolute authenticated session lifetime, in seconds (default: 30 days).
20    pub session_lifetime_seconds: u64,
21    /// Host-only cookie name. Defaults to `__Host-session` in production.
22    pub cookie_name: Option<String>,
23    /// Defaults to true in production and false locally. Production rejects false.
24    pub secure: Option<bool>,
25    /// Browser cookie policy; Lax by default.
26    pub same_site: SameSite,
27    /// Reset token lifetime, in seconds (default: 30 minutes).
28    pub password_reset_lifetime_seconds: u64,
29}
30
31impl Default for AuthSettings {
32    fn default() -> Self {
33        Self {
34            session_lifetime_seconds: 30 * 86400,
35            cookie_name: None,
36            secure: None,
37            same_site: SameSite::Lax,
38            password_reset_lifetime_seconds: 1800,
39        }
40    }
41}
42
43impl AuthSettings {
44    /// Resolve the host-only cookie name for an environment.
45    pub fn cookie_name(&self, production: bool) -> &str {
46        self.cookie_name.as_deref().unwrap_or(if production {
47            "__Host-session"
48        } else {
49            "session"
50        })
51    }
52
53    /// Resolve the transport policy without weakening production defaults.
54    pub fn secure(&self, production: bool) -> bool {
55        production || self.secure.unwrap_or(false)
56    }
57
58    /// Validate settings when auth is installed; unrelated apps need no auth config.
59    pub fn validate(&self, production: bool) -> Result<()> {
60        let cookie = self.cookie_name(production);
61        if cookie.is_empty()
62            || cookie.len() > 100
63            || !cookie
64                .bytes()
65                .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
66            || (cookie.starts_with("__Host-") || cookie.starts_with("__Secure-"))
67                && !self.secure(production)
68            || production && self.secure == Some(false)
69        {
70            return Err(AppError::Configuration(
71                "Auth requires a valid cookie name and Secure cookies in production.".into(),
72            ));
73        }
74        if !(60..=90 * 86400).contains(&self.session_lifetime_seconds)
75            || !(60..=86400).contains(&self.password_reset_lifetime_seconds)
76        {
77            return Err(AppError::Configuration("Auth session lifetime must be 60..=7776000 seconds; reset lifetime must be 60..=86400 seconds.".into()));
78        }
79        Ok(())
80    }
81}