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#[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 pub fn min_password_length(mut self, n: usize) -> Self {
60 self.min_password_length = n;
61 self
62 }
63
64 pub fn max_password_length(mut self, n: usize) -> Self {
65 self.max_password_length = n;
66 self
67 }
68
69 pub fn require_email_verification(mut self, on: bool) -> Self {
71 self.require_email_verification = on;
72 self
73 }
74
75 pub fn auto_sign_in(mut self, on: bool) -> Self {
77 self.auto_sign_in = on;
78 self
79 }
80
81 pub fn revoke_sessions_on_password_reset(mut self, on: bool) -> Self {
82 self.revoke_sessions_on_password_reset = on;
83 self
84 }
85
86 pub fn reset_password_ttl(mut self, ttl: Duration) -> Self {
87 self.reset_password_ttl = ttl;
88 self
89 }
90
91 pub fn password_policy(
93 mut self,
94 policy: impl Fn(&str) -> bool + Send + Sync + 'static,
95 ) -> Self {
96 self.password_policy = Some(Arc::new(policy));
97 self
98 }
99
100 pub fn hasher(mut self, hasher: impl PasswordHasher) -> Self {
101 self.hasher = Arc::new(hasher);
102 self
103 }
104}
105
106#[derive(Clone, Debug)]
107pub struct EmailVerification {
108 pub(crate) send_on_sign_up: bool,
109 pub(crate) auto_sign_in_after_verification: bool,
110 pub(crate) ttl: Duration,
111}
112
113impl Default for EmailVerification {
114 fn default() -> Self {
115 Self {
116 send_on_sign_up: true,
117 auto_sign_in_after_verification: false,
118 ttl: Duration::hours(1),
119 }
120 }
121}
122
123impl EmailVerification {
124 pub fn send_on_sign_up(mut self, on: bool) -> Self {
125 self.send_on_sign_up = on;
126 self
127 }
128
129 pub fn auto_sign_in_after_verification(mut self, on: bool) -> Self {
130 self.auto_sign_in_after_verification = on;
131 self
132 }
133
134 pub fn ttl(mut self, ttl: Duration) -> Self {
135 self.ttl = ttl;
136 self
137 }
138}
139
140#[derive(Clone, Debug)]
141pub struct SessionConfig {
142 pub(crate) expires_in: Duration,
143 pub(crate) update_age: Duration,
144 pub(crate) fresh_age: Duration,
145 pub(crate) cookie_cache: Option<Duration>,
146}
147
148impl Default for SessionConfig {
149 fn default() -> Self {
150 Self {
151 expires_in: Duration::days(7),
152 update_age: Duration::days(1),
153 fresh_age: Duration::days(1),
154 cookie_cache: None,
155 }
156 }
157}
158
159impl SessionConfig {
160 pub fn expires_in(mut self, d: Duration) -> Self {
161 self.expires_in = d;
162 self
163 }
164
165 pub fn update_age(mut self, d: Duration) -> Self {
167 self.update_age = d;
168 self
169 }
170
171 pub fn fresh_age(mut self, d: Duration) -> Self {
173 self.fresh_age = d;
174 self
175 }
176
177 pub fn cookie_cache(mut self, max_age: Duration) -> Self {
180 self.cookie_cache = Some(max_age);
181 self
182 }
183}
184
185#[derive(Clone, Copy, Debug, PartialEq, Eq)]
186pub enum SameSite {
187 Strict,
188 Lax,
189 None,
190}
191
192#[derive(Clone, Copy, Debug, PartialEq, Eq)]
193pub enum Secure {
194 Auto,
196 Always,
197 Never,
198}
199
200#[derive(Clone, Debug)]
201pub struct CookieConfig {
202 pub(crate) prefix: String,
203 pub(crate) same_site: SameSite,
204 pub(crate) domain: Option<String>,
205 pub(crate) secure: Secure,
206}
207
208impl Default for CookieConfig {
209 fn default() -> Self {
210 Self {
211 prefix: "fastauth".into(),
212 same_site: SameSite::Lax,
213 domain: None,
214 secure: Secure::Auto,
215 }
216 }
217}
218
219impl CookieConfig {
220 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
222 self.prefix = prefix.into();
223 self
224 }
225
226 pub fn same_site(mut self, same_site: SameSite) -> Self {
227 self.same_site = same_site;
228 self
229 }
230
231 pub fn domain(mut self, domain: impl Into<String>) -> Self {
232 self.domain = Some(domain.into());
233 self
234 }
235
236 pub fn secure(mut self, secure: Secure) -> Self {
237 self.secure = secure;
238 self
239 }
240}
241
242#[derive(Clone, Debug, PartialEq, Eq)]
244pub enum ClientIp {
245 Socket,
247 Header(String),
249}
250
251type IdGenerator = Arc<dyn Fn() -> String + Send + Sync>;
252
253#[derive(Clone, Default)]
273pub enum IdStrategy {
274 #[default]
277 Ulid,
278 UuidV7,
280 UuidV4,
282 Custom(IdGenerator),
286}
287
288impl IdStrategy {
289 pub const MAX_LEN: usize = 255;
291
292 pub fn custom(generate: impl Fn() -> String + Send + Sync + 'static) -> Self {
294 IdStrategy::Custom(Arc::new(generate))
295 }
296
297 pub fn generate(&self) -> Result<Id, AuthError> {
300 let id = match self {
301 IdStrategy::Ulid => ulid(OffsetDateTime::now_utc()),
302 IdStrategy::UuidV7 => uuid::Uuid::now_v7().to_string(),
303 IdStrategy::UuidV4 => uuid::Uuid::new_v4().to_string(),
304 IdStrategy::Custom(generate) => {
305 let id = generate();
306 if id.is_empty() {
307 return Err(AuthError::internal(
308 "the custom id generator (IdStrategy::Custom) returned an empty id",
309 ));
310 }
311 if id.len() > Self::MAX_LEN {
312 return Err(AuthError::internal(format_args!(
313 "the custom id generator (IdStrategy::Custom) returned a {}-byte id; ids are at most {} bytes",
314 id.len(),
315 Self::MAX_LEN
316 )));
317 }
318 id
319 }
320 };
321 Ok(Id::from(id))
322 }
323
324 pub fn storage(&self) -> IdStorage {
326 match self {
327 IdStrategy::UuidV7 | IdStrategy::UuidV4 => IdStorage::Uuid,
328 IdStrategy::Ulid | IdStrategy::Custom(_) => IdStorage::Text,
329 }
330 }
331}
332
333impl fmt::Debug for IdStrategy {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 match self {
336 IdStrategy::Ulid => f.write_str("Ulid"),
337 IdStrategy::UuidV7 => f.write_str("UuidV7"),
338 IdStrategy::UuidV4 => f.write_str("UuidV4"),
339 IdStrategy::Custom(_) => f.write_str("Custom(..)"),
340 }
341 }
342}
343
344const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
345
346fn ulid(at: OffsetDateTime) -> String {
348 let millis = (at.unix_timestamp_nanos() / 1_000_000) as u128 & ((1 << 48) - 1);
349 let mut random = [0u8; 16];
350 getrandom::fill(&mut random[6..]).expect("the OS random number generator is available");
351 let value = millis << 80 | u128::from_be_bytes(random);
352 (0..26)
353 .rev()
354 .map(|digit| CROCKFORD[(value >> (digit * 5)) as usize & 31] as char)
355 .collect()
356}
357
358#[derive(Clone, Debug)]
360pub struct CoreConfig {
361 pub app_name: String,
362 pub base_url: Url,
363 pub base_path: String,
364 pub trusted_origins: Vec<String>,
365 pub session: SessionConfig,
366 pub cookies: CookieConfig,
367 pub email_password: Option<EmailPassword>,
368 pub email_verification: EmailVerification,
369 pub rate_limit: RateLimit,
370 pub client_ip: ClientIp,
371 pub ids: IdStrategy,
372 pub(crate) secure_cookies: bool,
373}
374
375impl CoreConfig {
376 pub fn auth_url(&self) -> String {
378 format!(
379 "{}{}",
380 self.base_url.as_str().trim_end_matches('/'),
381 self.base_path
382 )
383 }
384
385 pub fn is_trusted_origin(&self, origin: &str) -> bool {
386 let origin = origin.trim_end_matches('/');
387 origin == self.base_url.origin().ascii_serialization()
388 || self.trusted_origins.iter().any(|o| o == origin)
389 }
390
391 pub fn is_safe_redirect(&self, target: &str) -> bool {
393 if target.starts_with('/') {
394 return !target.starts_with("//") && !target.starts_with("/\\");
395 }
396 Url::parse(target).is_ok_and(|u| self.is_trusted_origin(&u.origin().ascii_serialization()))
397 }
398
399 pub fn is_fresh(&self, session: &Session) -> bool {
402 let fresh_age = self.session.fresh_age;
403 fresh_age.is_zero() || OffsetDateTime::now_utc() - session.created_at <= fresh_age
404 }
405
406 pub fn cookie_name(&self, name: &str) -> String {
407 let secure = if self.secure_cookies { "__Secure-" } else { "" };
408 format!("{secure}{}.{name}", self.cookies.prefix)
409 }
410}
411
412#[cfg(test)]
413mod tests {
414 use super::*;
415
416 fn decode_ulid_millis(id: &str) -> i128 {
417 let value = id.bytes().fold(0u128, |acc, ch| {
418 let digit = CROCKFORD
419 .iter()
420 .position(|&c| c == ch)
421 .expect("crockford digit");
422 acc << 5 | digit as u128
423 });
424 (value >> 80) as i128
425 }
426
427 #[test]
428 fn ulid_is_26_crockford_characters_with_the_current_time() {
429 let before = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
430 let id = IdStrategy::Ulid.generate().unwrap();
431 let after = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
432 let id = id.as_str();
433 assert_eq!(id.len(), 26, "{id}");
434 assert!(id.bytes().all(|b| CROCKFORD.contains(&b)), "{id}");
435 assert!(id.as_bytes()[0] <= b'7', "a ULID fits in 128 bits: {id}");
436 assert!((before..=after).contains(&decode_ulid_millis(id)), "{id}");
437 assert_ne!(id, IdStrategy::Ulid.generate().unwrap().as_str());
438 }
439
440 #[test]
441 fn ulids_sort_by_time() {
442 let base = OffsetDateTime::now_utc();
443 let ids: Vec<String> = (0..50)
444 .map(|ms| ulid(base + Duration::milliseconds(ms)))
445 .collect();
446 let mut sorted = ids.clone();
447 sorted.sort();
448 assert_eq!(ids, sorted);
449
450 let first = IdStrategy::Ulid.generate().unwrap();
451 std::thread::sleep(std::time::Duration::from_millis(2));
452 let second = IdStrategy::Ulid.generate().unwrap();
453 assert!(first < second, "{first:?} < {second:?}");
454 }
455
456 #[test]
457 fn uuid_strategies_have_their_version_nibble() {
458 for (strategy, version) in [(IdStrategy::UuidV7, '7'), (IdStrategy::UuidV4, '4')] {
459 let id = strategy.generate().unwrap();
460 let id = id.as_str();
461 assert_eq!(id.len(), 36, "{id}");
462 assert_eq!(id.as_bytes()[14] as char, version, "{id}");
463 assert!(
464 matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'),
465 "{id}"
466 );
467 assert_eq!(strategy.storage(), IdStorage::Uuid);
468 }
469 }
470
471 #[test]
472 fn custom_ids_are_validated() {
473 let ok = IdStrategy::custom(|| "x".repeat(IdStrategy::MAX_LEN));
474 assert_eq!(ok.generate().unwrap().as_str().len(), 255);
475 assert_eq!(ok.storage(), IdStorage::Text);
476
477 for bad in [String::new(), "x".repeat(IdStrategy::MAX_LEN + 1)] {
478 let strategy = IdStrategy::custom(move || bad.clone());
479 let err = strategy.generate().unwrap_err();
480 assert_eq!(err.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
481 assert_eq!(err.code(), crate::error::codes::INTERNAL);
482 }
483 assert_eq!(format!("{ok:?}"), "Custom(..)");
484 }
485}