Skip to main content

fastauth_core/
config.rs

1use std::fmt;
2use std::sync::Arc;
3
4use time::{Duration, OffsetDateTime};
5use url::Url;
6
7use crate::crypto::{Argon2id, PasswordHasher};
8use crate::models::Session;
9use crate::rate_limit::RateLimit;
10
11type PasswordPolicy = Arc<dyn Fn(&str) -> bool + Send + Sync>;
12
13/// Email and password sign-in. Off unless `.email_password(..)` is called.
14#[derive(Clone)]
15pub struct EmailPassword {
16    pub(crate) min_password_length: usize,
17    pub(crate) max_password_length: usize,
18    pub(crate) require_email_verification: bool,
19    pub(crate) auto_sign_in: bool,
20    pub(crate) revoke_sessions_on_password_reset: bool,
21    pub(crate) reset_password_ttl: Duration,
22    pub(crate) password_policy: Option<PasswordPolicy>,
23    pub(crate) hasher: Arc<dyn PasswordHasher>,
24}
25
26impl fmt::Debug for EmailPassword {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.debug_struct("EmailPassword")
29            .field("min_password_length", &self.min_password_length)
30            .field("max_password_length", &self.max_password_length)
31            .field(
32                "require_email_verification",
33                &self.require_email_verification,
34            )
35            .field("auto_sign_in", &self.auto_sign_in)
36            .finish_non_exhaustive()
37    }
38}
39
40impl Default for EmailPassword {
41    fn default() -> Self {
42        Self {
43            min_password_length: 8,
44            max_password_length: 128,
45            require_email_verification: false,
46            auto_sign_in: true,
47            revoke_sessions_on_password_reset: false,
48            reset_password_ttl: Duration::hours(1),
49            password_policy: None,
50            hasher: Arc::new(Argon2id::owasp()),
51        }
52    }
53}
54
55impl EmailPassword {
56    pub fn min_password_length(mut self, n: usize) -> Self {
57        self.min_password_length = n;
58        self
59    }
60
61    pub fn max_password_length(mut self, n: usize) -> Self {
62        self.max_password_length = n;
63        self
64    }
65
66    /// Sign-in fails with `EMAIL_NOT_VERIFIED` until the user verifies. Needs a mailer.
67    pub fn require_email_verification(mut self, on: bool) -> Self {
68        self.require_email_verification = on;
69        self
70    }
71
72    /// Sign-up returns a session (default true). Ignored when verification is required.
73    pub fn auto_sign_in(mut self, on: bool) -> Self {
74        self.auto_sign_in = on;
75        self
76    }
77
78    pub fn revoke_sessions_on_password_reset(mut self, on: bool) -> Self {
79        self.revoke_sessions_on_password_reset = on;
80        self
81    }
82
83    pub fn reset_password_ttl(mut self, ttl: Duration) -> Self {
84        self.reset_password_ttl = ttl;
85        self
86    }
87
88    /// Extra check on new passwords; returning false answers `PASSWORD_TOO_WEAK`.
89    pub fn password_policy(
90        mut self,
91        policy: impl Fn(&str) -> bool + Send + Sync + 'static,
92    ) -> Self {
93        self.password_policy = Some(Arc::new(policy));
94        self
95    }
96
97    pub fn hasher(mut self, hasher: impl PasswordHasher) -> Self {
98        self.hasher = Arc::new(hasher);
99        self
100    }
101}
102
103#[derive(Clone, Debug)]
104pub struct EmailVerification {
105    pub(crate) send_on_sign_up: bool,
106    pub(crate) auto_sign_in_after_verification: bool,
107    pub(crate) ttl: Duration,
108}
109
110impl Default for EmailVerification {
111    fn default() -> Self {
112        Self {
113            send_on_sign_up: true,
114            auto_sign_in_after_verification: false,
115            ttl: Duration::hours(1),
116        }
117    }
118}
119
120impl EmailVerification {
121    pub fn send_on_sign_up(mut self, on: bool) -> Self {
122        self.send_on_sign_up = on;
123        self
124    }
125
126    pub fn auto_sign_in_after_verification(mut self, on: bool) -> Self {
127        self.auto_sign_in_after_verification = on;
128        self
129    }
130
131    pub fn ttl(mut self, ttl: Duration) -> Self {
132        self.ttl = ttl;
133        self
134    }
135}
136
137#[derive(Clone, Debug)]
138pub struct SessionConfig {
139    pub(crate) expires_in: Duration,
140    pub(crate) update_age: Duration,
141    pub(crate) fresh_age: Duration,
142    pub(crate) cookie_cache: Option<Duration>,
143}
144
145impl Default for SessionConfig {
146    fn default() -> Self {
147        Self {
148            expires_in: Duration::days(7),
149            update_age: Duration::days(1),
150            fresh_age: Duration::days(1),
151            cookie_cache: None,
152        }
153    }
154}
155
156impl SessionConfig {
157    pub fn expires_in(mut self, d: Duration) -> Self {
158        self.expires_in = d;
159        self
160    }
161
162    /// Extend the expiry at most this often (default one day).
163    pub fn update_age(mut self, d: Duration) -> Self {
164        self.update_age = d;
165        self
166    }
167
168    /// `Fresh` endpoints need a session created within this window. Zero disables the check.
169    pub fn fresh_age(mut self, d: Duration) -> Self {
170        self.fresh_age = d;
171        self
172    }
173
174    /// A signed cookie caching the session for `max_age`. Saves the DB lookup, at the cost
175    /// of revocations taking up to `max_age` to reach other devices.
176    pub fn cookie_cache(mut self, max_age: Duration) -> Self {
177        self.cookie_cache = Some(max_age);
178        self
179    }
180}
181
182#[derive(Clone, Copy, Debug, PartialEq, Eq)]
183pub enum SameSite {
184    Strict,
185    Lax,
186    None,
187}
188
189#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190pub enum Secure {
191    /// Secure (and `__Secure-` prefixed) when `base_url` is https.
192    Auto,
193    Always,
194    Never,
195}
196
197#[derive(Clone, Debug)]
198pub struct CookieConfig {
199    pub(crate) prefix: String,
200    pub(crate) same_site: SameSite,
201    pub(crate) domain: Option<String>,
202    pub(crate) secure: Secure,
203}
204
205impl Default for CookieConfig {
206    fn default() -> Self {
207        Self {
208            prefix: "fastauth".into(),
209            same_site: SameSite::Lax,
210            domain: None,
211            secure: Secure::Auto,
212        }
213    }
214}
215
216impl CookieConfig {
217    /// `"better-auth"` makes cookie names match a Better Auth server.
218    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
219        self.prefix = prefix.into();
220        self
221    }
222
223    pub fn same_site(mut self, same_site: SameSite) -> Self {
224        self.same_site = same_site;
225        self
226    }
227
228    pub fn domain(mut self, domain: impl Into<String>) -> Self {
229        self.domain = Some(domain.into());
230        self
231    }
232
233    pub fn secure(mut self, secure: Secure) -> Self {
234        self.secure = secure;
235        self
236    }
237}
238
239/// Where the client IP comes from.
240#[derive(Clone, Debug, PartialEq, Eq)]
241pub enum ClientIp {
242    /// The socket address the integration puts in request extensions (default).
243    Socket,
244    /// A header set by a proxy you trust, e.g. `fly-client-ip`. Take the first value.
245    Header(String),
246}
247
248/// Everything the builder collected, frozen at `.build()`.
249#[derive(Clone, Debug)]
250pub struct CoreConfig {
251    pub app_name: String,
252    pub base_url: Url,
253    pub base_path: String,
254    pub trusted_origins: Vec<String>,
255    pub session: SessionConfig,
256    pub cookies: CookieConfig,
257    pub email_password: Option<EmailPassword>,
258    pub email_verification: EmailVerification,
259    pub rate_limit: RateLimit,
260    pub client_ip: ClientIp,
261    pub(crate) secure_cookies: bool,
262}
263
264impl CoreConfig {
265    /// `https://acme.dk/api/auth`
266    pub fn auth_url(&self) -> String {
267        format!(
268            "{}{}",
269            self.base_url.as_str().trim_end_matches('/'),
270            self.base_path
271        )
272    }
273
274    pub fn is_trusted_origin(&self, origin: &str) -> bool {
275        let origin = origin.trim_end_matches('/');
276        origin == self.base_url.origin().ascii_serialization()
277            || self.trusted_origins.iter().any(|o| o == origin)
278    }
279
280    /// Accepts relative paths (`/dashboard`) and absolute URLs on a trusted origin.
281    pub fn is_safe_redirect(&self, target: &str) -> bool {
282        if target.starts_with('/') {
283            return !target.starts_with("//") && !target.starts_with("/\\");
284        }
285        Url::parse(target).is_ok_and(|u| self.is_trusted_origin(&u.origin().ascii_serialization()))
286    }
287
288    /// Whether `session` was created within `fresh_age`, the rule behind `Fresh` access.
289    /// A zero `fresh_age` makes every session fresh.
290    pub fn is_fresh(&self, session: &Session) -> bool {
291        let fresh_age = self.session.fresh_age;
292        fresh_age.is_zero() || OffsetDateTime::now_utc() - session.created_at <= fresh_age
293    }
294
295    pub fn cookie_name(&self, name: &str) -> String {
296        let secure = if self.secure_cookies { "__Secure-" } else { "" };
297        format!("{secure}{}.{name}", self.cookies.prefix)
298    }
299}