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::error::AuthError;
9use crate::models::Session;
10use crate::rate_limit::RateLimit;
11use crate::schema::IdStorage;
12use crate::value::Id;
13
14type PasswordPolicy = Arc<dyn Fn(&str) -> bool + Send + Sync>;
15
16/// Email and password sign-in. Off unless `.email_password(..)` is called.
17#[derive(Clone)]
18pub struct EmailPassword {
19    pub(crate) min_password_length: usize,
20    pub(crate) max_password_length: usize,
21    pub(crate) require_email_verification: bool,
22    pub(crate) auto_sign_in: bool,
23    pub(crate) revoke_sessions_on_password_reset: bool,
24    pub(crate) reset_password_ttl: Duration,
25    pub(crate) password_policy: Option<PasswordPolicy>,
26    pub(crate) hasher: Arc<dyn PasswordHasher>,
27}
28
29impl fmt::Debug for EmailPassword {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        f.debug_struct("EmailPassword")
32            .field("min_password_length", &self.min_password_length)
33            .field("max_password_length", &self.max_password_length)
34            .field(
35                "require_email_verification",
36                &self.require_email_verification,
37            )
38            .field("auto_sign_in", &self.auto_sign_in)
39            .finish_non_exhaustive()
40    }
41}
42
43impl Default for EmailPassword {
44    fn default() -> Self {
45        Self {
46            min_password_length: 8,
47            max_password_length: 128,
48            require_email_verification: false,
49            auto_sign_in: true,
50            revoke_sessions_on_password_reset: false,
51            reset_password_ttl: Duration::hours(1),
52            password_policy: None,
53            hasher: Arc::new(Argon2id::owasp()),
54        }
55    }
56}
57
58impl EmailPassword {
59    /// Whether a password reset signs the user out everywhere, for plugins that reset passwords.
60    pub fn revokes_sessions_on_password_reset(&self) -> bool {
61        self.revoke_sessions_on_password_reset
62    }
63
64    pub fn min_password_length(mut self, n: usize) -> Self {
65        self.min_password_length = n;
66        self
67    }
68
69    pub fn max_password_length(mut self, n: usize) -> Self {
70        self.max_password_length = n;
71        self
72    }
73
74    /// Sign-in fails with `EMAIL_NOT_VERIFIED` until the user verifies. Needs a mailer.
75    pub fn require_email_verification(mut self, on: bool) -> Self {
76        self.require_email_verification = on;
77        self
78    }
79
80    /// Sign-up returns a session (default true). Ignored when verification is required.
81    pub fn auto_sign_in(mut self, on: bool) -> Self {
82        self.auto_sign_in = on;
83        self
84    }
85
86    pub fn revoke_sessions_on_password_reset(mut self, on: bool) -> Self {
87        self.revoke_sessions_on_password_reset = on;
88        self
89    }
90
91    pub fn reset_password_ttl(mut self, ttl: Duration) -> Self {
92        self.reset_password_ttl = ttl;
93        self
94    }
95
96    /// Extra check on new passwords; returning false answers `PASSWORD_TOO_WEAK`.
97    pub fn password_policy(
98        mut self,
99        policy: impl Fn(&str) -> bool + Send + Sync + 'static,
100    ) -> Self {
101        self.password_policy = Some(Arc::new(policy));
102        self
103    }
104
105    pub fn hasher(mut self, hasher: impl PasswordHasher) -> Self {
106        self.hasher = Arc::new(hasher);
107        self
108    }
109}
110
111#[derive(Clone, Debug)]
112pub struct EmailVerification {
113    pub(crate) send_on_sign_up: bool,
114    pub(crate) auto_sign_in_after_verification: bool,
115    pub(crate) ttl: Duration,
116}
117
118impl Default for EmailVerification {
119    fn default() -> Self {
120        Self {
121            send_on_sign_up: true,
122            auto_sign_in_after_verification: false,
123            ttl: Duration::hours(1),
124        }
125    }
126}
127
128impl EmailVerification {
129    /// Whether verifying an email signs the user in, for plugins that verify emails.
130    pub fn auto_signs_in_after_verification(&self) -> bool {
131        self.auto_sign_in_after_verification
132    }
133
134    pub fn send_on_sign_up(mut self, on: bool) -> Self {
135        self.send_on_sign_up = on;
136        self
137    }
138
139    pub fn auto_sign_in_after_verification(mut self, on: bool) -> Self {
140        self.auto_sign_in_after_verification = on;
141        self
142    }
143
144    pub fn ttl(mut self, ttl: Duration) -> Self {
145        self.ttl = ttl;
146        self
147    }
148}
149
150#[derive(Clone, Debug)]
151pub struct SessionConfig {
152    pub(crate) expires_in: Duration,
153    pub(crate) update_age: Duration,
154    pub(crate) fresh_age: Duration,
155    pub(crate) cookie_cache: Option<Duration>,
156}
157
158impl Default for SessionConfig {
159    fn default() -> Self {
160        Self {
161            expires_in: Duration::days(7),
162            update_age: Duration::days(1),
163            fresh_age: Duration::days(1),
164            cookie_cache: None,
165        }
166    }
167}
168
169impl SessionConfig {
170    pub fn expires_in(mut self, d: Duration) -> Self {
171        self.expires_in = d;
172        self
173    }
174
175    /// Extend the expiry at most this often (default one day).
176    pub fn update_age(mut self, d: Duration) -> Self {
177        self.update_age = d;
178        self
179    }
180
181    /// `Fresh` endpoints need a session created within this window. Zero disables the check.
182    pub fn fresh_age(mut self, d: Duration) -> Self {
183        self.fresh_age = d;
184        self
185    }
186
187    /// A signed cookie caching the session for `max_age`. Saves the DB lookup, at the cost
188    /// of revocations taking up to `max_age` to reach other devices.
189    pub fn cookie_cache(mut self, max_age: Duration) -> Self {
190        self.cookie_cache = Some(max_age);
191        self
192    }
193}
194
195#[derive(Clone, Copy, Debug, PartialEq, Eq)]
196pub enum SameSite {
197    Strict,
198    Lax,
199    None,
200}
201
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub enum Secure {
204    /// Secure (and `__Secure-` prefixed) when `base_url` is https.
205    Auto,
206    Always,
207    Never,
208}
209
210#[derive(Clone, Debug)]
211pub struct CookieConfig {
212    pub(crate) prefix: String,
213    pub(crate) same_site: SameSite,
214    pub(crate) domain: Option<String>,
215    pub(crate) secure: Secure,
216}
217
218impl Default for CookieConfig {
219    fn default() -> Self {
220        Self {
221            prefix: "fastauth".into(),
222            same_site: SameSite::Lax,
223            domain: None,
224            secure: Secure::Auto,
225        }
226    }
227}
228
229impl CookieConfig {
230    /// `"better-auth"` makes cookie names match a Better Auth server.
231    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
232        self.prefix = prefix.into();
233        self
234    }
235
236    pub fn same_site(mut self, same_site: SameSite) -> Self {
237        self.same_site = same_site;
238        self
239    }
240
241    pub fn domain(mut self, domain: impl Into<String>) -> Self {
242        self.domain = Some(domain.into());
243        self
244    }
245
246    pub fn secure(mut self, secure: Secure) -> Self {
247        self.secure = secure;
248        self
249    }
250}
251
252/// Where the client IP comes from.
253#[derive(Clone, Debug, PartialEq, Eq)]
254pub enum ClientIp {
255    /// The socket address the integration puts in request extensions (default).
256    Socket,
257    /// A header set by a proxy you trust, e.g. `fly-client-ip`. Take the first value.
258    Header(String),
259}
260
261type IdGenerator = Arc<dyn Fn() -> String + Send + Sync>;
262
263/// How fastauth generates the ids of the rows it creates: users, sessions, accounts,
264/// verifications and every row a plugin creates through `ctx.new_id()`.
265///
266/// Set it with `FastAuth::builder().ids(..)`. The strategy also picks how id columns are
267/// stored ([`IdStrategy::storage`]): the UUID strategies use Postgres' native `uuid` type,
268/// the others `text`. Switching strategies on an existing database doesn't convert its
269/// columns; the migrator warns about the mismatch instead.
270///
271/// ```
272/// use fastauth_core::config::IdStrategy;
273///
274/// let id = IdStrategy::default().generate().unwrap();
275/// assert_eq!(id.as_str().len(), 26);
276///
277/// let custom = IdStrategy::custom(|| {
278///     format!("usr_{}", fastauth_core::crypto::random_string(12, b"0123456789abcdef"))
279/// });
280/// assert!(custom.generate().unwrap().as_str().starts_with("usr_"));
281/// ```
282#[derive(Clone, Default)]
283pub enum IdStrategy {
284    /// A [ULID](https://github.com/ulid/spec): 26 characters of Crockford base32, sortable
285    /// by creation time. Stored as `text`. The default.
286    #[default]
287    Ulid,
288    /// A UUIDv7 in hyphenated form, sortable by creation time. Stored as `uuid` on Postgres.
289    UuidV7,
290    /// A random UUIDv4 in hyphenated form. Stored as `uuid` on Postgres.
291    UuidV4,
292    /// Ids from your own function, stored as `text`. Every id is checked when it's
293    /// generated: an empty one, or one longer than [`IdStrategy::MAX_LEN`] bytes, fails the
294    /// request with a 500 and an error log line. Ids must be unique; fastauth doesn't retry.
295    Custom(IdGenerator),
296}
297
298impl IdStrategy {
299    /// The longest id, in bytes, a custom generator may return.
300    pub const MAX_LEN: usize = 255;
301
302    /// `IdStrategy::Custom` from a closure.
303    pub fn custom(generate: impl Fn() -> String + Send + Sync + 'static) -> Self {
304        IdStrategy::Custom(Arc::new(generate))
305    }
306
307    /// A new id. Only a custom generator can fail: with a 500 `INTERNAL_SERVER_ERROR`
308    /// whose detail is logged, never sent to the client.
309    pub fn generate(&self) -> Result<Id, AuthError> {
310        let id = match self {
311            IdStrategy::Ulid => ulid(OffsetDateTime::now_utc()),
312            IdStrategy::UuidV7 => uuid::Uuid::now_v7().to_string(),
313            IdStrategy::UuidV4 => uuid::Uuid::new_v4().to_string(),
314            IdStrategy::Custom(generate) => {
315                let id = generate();
316                if id.is_empty() {
317                    return Err(AuthError::internal(
318                        "the custom id generator (IdStrategy::Custom) returned an empty id",
319                    ));
320                }
321                if id.len() > Self::MAX_LEN {
322                    return Err(AuthError::internal(format_args!(
323                        "the custom id generator (IdStrategy::Custom) returned a {}-byte id; ids are at most {} bytes",
324                        id.len(),
325                        Self::MAX_LEN
326                    )));
327                }
328                id
329            }
330        };
331        Ok(Id::from(id))
332    }
333
334    /// How id columns are stored for this strategy.
335    pub fn storage(&self) -> IdStorage {
336        match self {
337            IdStrategy::UuidV7 | IdStrategy::UuidV4 => IdStorage::Uuid,
338            IdStrategy::Ulid | IdStrategy::Custom(_) => IdStorage::Text,
339        }
340    }
341}
342
343impl fmt::Debug for IdStrategy {
344    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
345        match self {
346            IdStrategy::Ulid => f.write_str("Ulid"),
347            IdStrategy::UuidV7 => f.write_str("UuidV7"),
348            IdStrategy::UuidV4 => f.write_str("UuidV4"),
349            IdStrategy::Custom(_) => f.write_str("Custom(..)"),
350        }
351    }
352}
353
354const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
355
356/// A ULID for `at`: 48 bits of Unix milliseconds, then 80 random bits, as 26 base32 digits.
357fn ulid(at: OffsetDateTime) -> String {
358    let millis = (at.unix_timestamp_nanos() / 1_000_000) as u128 & ((1 << 48) - 1);
359    let mut random = [0u8; 16];
360    getrandom::fill(&mut random[6..]).expect("the OS random number generator is available");
361    let value = millis << 80 | u128::from_be_bytes(random);
362    (0..26)
363        .rev()
364        .map(|digit| CROCKFORD[(value >> (digit * 5)) as usize & 31] as char)
365        .collect()
366}
367
368/// Everything the builder collected, frozen at `.build()`.
369#[derive(Clone, Debug)]
370pub struct CoreConfig {
371    pub app_name: String,
372    pub base_url: Url,
373    pub base_path: String,
374    pub trusted_origins: Vec<String>,
375    pub session: SessionConfig,
376    pub cookies: CookieConfig,
377    pub email_password: Option<EmailPassword>,
378    pub email_verification: EmailVerification,
379    pub rate_limit: RateLimit,
380    pub client_ip: ClientIp,
381    pub ids: IdStrategy,
382    pub(crate) secure_cookies: bool,
383}
384
385impl CoreConfig {
386    /// `https://acme.dk/api/auth`
387    pub fn auth_url(&self) -> String {
388        format!(
389            "{}{}",
390            self.base_url.as_str().trim_end_matches('/'),
391            self.base_path
392        )
393    }
394
395    pub fn is_trusted_origin(&self, origin: &str) -> bool {
396        let origin = origin.trim_end_matches('/');
397        origin == self.base_url.origin().ascii_serialization()
398            || self.trusted_origins.iter().any(|o| o == origin)
399    }
400
401    /// Accepts relative paths (`/dashboard`) and absolute URLs on a trusted origin.
402    pub fn is_safe_redirect(&self, target: &str) -> bool {
403        if target.starts_with('/') {
404            return !target.starts_with("//") && !target.starts_with("/\\");
405        }
406        Url::parse(target).is_ok_and(|u| self.is_trusted_origin(&u.origin().ascii_serialization()))
407    }
408
409    /// Whether `session` was created within `fresh_age`, the rule behind `Fresh` access.
410    /// A zero `fresh_age` makes every session fresh.
411    pub fn is_fresh(&self, session: &Session) -> bool {
412        let fresh_age = self.session.fresh_age;
413        fresh_age.is_zero() || OffsetDateTime::now_utc() - session.created_at <= fresh_age
414    }
415
416    pub fn cookie_name(&self, name: &str) -> String {
417        let secure = if self.secure_cookies { "__Secure-" } else { "" };
418        format!("{secure}{}.{name}", self.cookies.prefix)
419    }
420}
421
422#[cfg(test)]
423mod tests {
424    use super::*;
425
426    fn decode_ulid_millis(id: &str) -> i128 {
427        let value = id.bytes().fold(0u128, |acc, ch| {
428            let digit = CROCKFORD
429                .iter()
430                .position(|&c| c == ch)
431                .expect("crockford digit");
432            acc << 5 | digit as u128
433        });
434        (value >> 80) as i128
435    }
436
437    #[test]
438    fn ulid_is_26_crockford_characters_with_the_current_time() {
439        let before = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
440        let id = IdStrategy::Ulid.generate().unwrap();
441        let after = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
442        let id = id.as_str();
443        assert_eq!(id.len(), 26, "{id}");
444        assert!(id.bytes().all(|b| CROCKFORD.contains(&b)), "{id}");
445        assert!(id.as_bytes()[0] <= b'7', "a ULID fits in 128 bits: {id}");
446        assert!((before..=after).contains(&decode_ulid_millis(id)), "{id}");
447        assert_ne!(id, IdStrategy::Ulid.generate().unwrap().as_str());
448    }
449
450    #[test]
451    fn ulids_sort_by_time() {
452        let base = OffsetDateTime::now_utc();
453        let ids: Vec<String> = (0..50)
454            .map(|ms| ulid(base + Duration::milliseconds(ms)))
455            .collect();
456        let mut sorted = ids.clone();
457        sorted.sort();
458        assert_eq!(ids, sorted);
459
460        let first = IdStrategy::Ulid.generate().unwrap();
461        std::thread::sleep(std::time::Duration::from_millis(2));
462        let second = IdStrategy::Ulid.generate().unwrap();
463        assert!(first < second, "{first:?} < {second:?}");
464    }
465
466    #[test]
467    fn uuid_strategies_have_their_version_nibble() {
468        for (strategy, version) in [(IdStrategy::UuidV7, '7'), (IdStrategy::UuidV4, '4')] {
469            let id = strategy.generate().unwrap();
470            let id = id.as_str();
471            assert_eq!(id.len(), 36, "{id}");
472            assert_eq!(id.as_bytes()[14] as char, version, "{id}");
473            assert!(
474                matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'),
475                "{id}"
476            );
477            assert_eq!(strategy.storage(), IdStorage::Uuid);
478        }
479    }
480
481    #[test]
482    fn custom_ids_are_validated() {
483        let ok = IdStrategy::custom(|| "x".repeat(IdStrategy::MAX_LEN));
484        assert_eq!(ok.generate().unwrap().as_str().len(), 255);
485        assert_eq!(ok.storage(), IdStorage::Text);
486
487        for bad in [String::new(), "x".repeat(IdStrategy::MAX_LEN + 1)] {
488            let strategy = IdStrategy::custom(move || bad.clone());
489            let err = strategy.generate().unwrap_err();
490            assert_eq!(err.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
491            assert_eq!(err.code(), crate::error::codes::INTERNAL);
492        }
493        assert_eq!(format!("{ok:?}"), "Custom(..)");
494    }
495}