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    /// Process-local auth abuse limits (`AUTH_THROTTLE_*`).
20    pub throttle: AuthThrottleSettings,
21    /// Per-application password resource limits.
22    pub password: crate::PasswordSettings,
23    /// Absolute authenticated session lifetime, in seconds (default: 30 days).
24    pub session_lifetime_seconds: u64,
25    /// Host-only cookie name. Defaults to `__Host-session` in production.
26    pub cookie_name: Option<String>,
27    /// Defaults to true in production and false locally. Production rejects false.
28    pub secure: Option<bool>,
29    /// Browser cookie policy; Lax by default.
30    pub same_site: SameSite,
31    /// Reset token lifetime, in seconds (default: 30 minutes).
32    pub password_reset_lifetime_seconds: u64,
33}
34
35impl Default for AuthSettings {
36    fn default() -> Self {
37        Self {
38            throttle: AuthThrottleSettings::default(),
39            password: crate::PasswordSettings::default(),
40            session_lifetime_seconds: 30 * 86400,
41            cookie_name: None,
42            secure: None,
43            same_site: SameSite::Lax,
44            password_reset_lifetime_seconds: 1800,
45        }
46    }
47}
48
49impl AuthSettings {
50    /// Resolve the host-only cookie name for an environment.
51    pub fn cookie_name(&self, production: bool) -> &str {
52        self.cookie_name.as_deref().unwrap_or(if production {
53            "__Host-session"
54        } else {
55            "session"
56        })
57    }
58
59    /// Resolve the transport policy without weakening production defaults.
60    pub fn secure(&self, production: bool) -> bool {
61        production || self.secure.unwrap_or(false)
62    }
63
64    /// Validate settings when auth is installed; unrelated apps need no auth config.
65    pub fn validate(&self, production: bool) -> Result<()> {
66        self.password.concurrency()?;
67        self.throttle.validate()?;
68        if production && !self.throttle.enabled {
69            tracing::warn!(event = "auth.throttle.disabled", "Built-in auth throttling is disabled; enforce equivalent abuse limits at your deployment boundary.");
70        }
71        let cookie = self.cookie_name(production);
72        if cookie.is_empty()
73            || cookie.len() > 100
74            || !cookie
75                .bytes()
76                .all(|c| c.is_ascii_alphanumeric() || b"_-".contains(&c))
77            || (cookie.starts_with("__Host-") || cookie.starts_with("__Secure-"))
78                && !self.secure(production)
79            || production && self.secure == Some(false)
80        {
81            return Err(AppError::Configuration(
82                "Auth requires a valid cookie name and Secure cookies in production.".into(),
83            ));
84        }
85        if !(60..=90 * 86400).contains(&self.session_lifetime_seconds)
86            || !(60..=86400).contains(&self.password_reset_lifetime_seconds)
87        {
88            return Err(AppError::Configuration("Auth session lifetime must be 60..=7776000 seconds; reset lifetime must be 60..=86400 seconds.".into()));
89        }
90        Ok(())
91    }
92}
93
94/// Fixed-window abuse budget. Zero never implicitly disables a limit.
95#[derive(Clone, Debug, Deserialize, Serialize)]
96#[serde(deny_unknown_fields)]
97pub struct AuthThrottleLimit {
98    /// Allowed attempts per window (1..=1000000).
99    pub limit: u32,
100    /// Window duration in seconds (1..=86400).
101    pub window_seconds: u64,
102}
103impl AuthThrottleLimit {
104    fn validate(&self) -> Result<()> {
105        if !(1..=1_000_000).contains(&self.limit) || !(1..=86400).contains(&self.window_seconds) {
106            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()));
107        }
108        Ok(())
109    }
110}
111
112/// Separate fixed windows for CSRF bootstrap, registration, login, reset request
113/// and reset completion. Limits apply per action; account keys span client IPs.
114/// Application-owned verification endpoints need their own request-level limiter.
115#[derive(Clone, Debug, Deserialize, Serialize)]
116#[serde(default, deny_unknown_fields)]
117pub struct AuthThrottleSettings {
118    /// Default true. False explicitly disables abuse counters, but never proxy or
119    /// client-identity validation, CSRF, password capacity or other auth checks.
120    pub enabled: bool,
121    /// Per-client-IP budget per action; default 60 attempts per 60 seconds.
122    pub ip: AuthThrottleLimit,
123    /// Per-normalized-account budget per action; default 10 attempts per 60 seconds.
124    /// Reset completion additionally keys this budget by the supplied token digest.
125    pub account: AuthThrottleLimit,
126}
127impl Default for AuthThrottleSettings {
128    fn default() -> Self {
129        Self {
130            enabled: true,
131            ip: AuthThrottleLimit {
132                limit: 60,
133                window_seconds: 60,
134            },
135            account: AuthThrottleLimit {
136                limit: 10,
137                window_seconds: 60,
138            },
139        }
140    }
141}
142impl AuthThrottleSettings {
143    /// Validate budgets even while disabled, so reenabling cannot install bad bounds.
144    pub fn validate(&self) -> Result<()> {
145        self.ip.validate()?;
146        self.account.validate()
147    }
148}