1use std::fmt;
2use std::net::IpAddr;
3use std::sync::Arc;
4
5use time::{Duration, OffsetDateTime};
6use url::Url;
7
8use crate::auth::ClientAddr;
9use crate::crypto::{Argon2id, Hash, PasswordHasher, Secret};
10use crate::error::AuthError;
11use crate::models::Session;
12use crate::query::Where;
13use crate::rate_limit::RateLimit;
14use crate::schema::IdStorage;
15use crate::value::Id;
16
17type PasswordPolicy = Arc<dyn Fn(&str) -> bool + Send + Sync>;
18
19#[derive(Clone)]
21pub struct EmailPassword {
22 pub(crate) min_password_length: usize,
23 pub(crate) max_password_length: usize,
24 pub(crate) require_email_verification: bool,
25 pub(crate) auto_sign_in: bool,
26 pub(crate) revoke_sessions_on_password_reset: bool,
27 pub(crate) reset_password_ttl: Duration,
28 pub(crate) password_policy: Option<PasswordPolicy>,
29 pub(crate) hasher: Arc<dyn PasswordHasher>,
30 pub(crate) max_concurrent_hashes: Option<usize>,
31}
32
33impl fmt::Debug for EmailPassword {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 f.debug_struct("EmailPassword")
36 .field("min_password_length", &self.min_password_length)
37 .field("max_password_length", &self.max_password_length)
38 .field(
39 "require_email_verification",
40 &self.require_email_verification,
41 )
42 .field("auto_sign_in", &self.auto_sign_in)
43 .finish_non_exhaustive()
44 }
45}
46
47impl Default for EmailPassword {
48 fn default() -> Self {
49 Self {
50 min_password_length: 8,
51 max_password_length: 128,
52 require_email_verification: false,
53 auto_sign_in: true,
54 revoke_sessions_on_password_reset: true,
55 reset_password_ttl: Duration::hours(1),
56 password_policy: None,
57 hasher: Arc::new(Argon2id::owasp()),
58 max_concurrent_hashes: None,
59 }
60 }
61}
62
63impl EmailPassword {
64 pub fn revokes_sessions_on_password_reset(&self) -> bool {
66 self.revoke_sessions_on_password_reset
67 }
68
69 pub fn requires_email_verification(&self) -> bool {
71 self.require_email_verification
72 }
73
74 pub fn max_password_len(&self) -> usize {
76 self.max_password_length
77 }
78
79 pub fn min_password_length(mut self, n: usize) -> Self {
80 self.min_password_length = n;
81 self
82 }
83
84 pub fn max_password_length(mut self, n: usize) -> Self {
85 self.max_password_length = n;
86 self
87 }
88
89 pub fn require_email_verification(mut self, on: bool) -> Self {
91 self.require_email_verification = on;
92 self
93 }
94
95 pub fn auto_sign_in(mut self, on: bool) -> Self {
97 self.auto_sign_in = on;
98 self
99 }
100
101 pub fn revoke_sessions_on_password_reset(mut self, on: bool) -> Self {
104 self.revoke_sessions_on_password_reset = on;
105 self
106 }
107
108 pub fn reset_password_ttl(mut self, ttl: Duration) -> Self {
109 self.reset_password_ttl = ttl;
110 self
111 }
112
113 pub fn password_policy(
115 mut self,
116 policy: impl Fn(&str) -> bool + Send + Sync + 'static,
117 ) -> Self {
118 self.password_policy = Some(Arc::new(policy));
119 self
120 }
121
122 pub fn hasher(mut self, hasher: impl PasswordHasher) -> Self {
123 self.hasher = Arc::new(hasher);
124 self
125 }
126
127 pub fn max_concurrent_hashes(mut self, n: usize) -> Self {
131 self.max_concurrent_hashes = Some(n.max(1));
132 self
133 }
134}
135
136#[derive(Clone, Debug)]
137pub struct EmailVerification {
138 pub(crate) send_on_sign_up: bool,
139 pub(crate) auto_sign_in_after_verification: bool,
140 pub(crate) ttl: Duration,
141}
142
143impl Default for EmailVerification {
144 fn default() -> Self {
145 Self {
146 send_on_sign_up: true,
147 auto_sign_in_after_verification: false,
148 ttl: Duration::hours(1),
149 }
150 }
151}
152
153impl EmailVerification {
154 pub fn auto_signs_in_after_verification(&self) -> bool {
156 self.auto_sign_in_after_verification
157 }
158
159 pub fn send_on_sign_up(mut self, on: bool) -> Self {
160 self.send_on_sign_up = on;
161 self
162 }
163
164 pub fn auto_sign_in_after_verification(mut self, on: bool) -> Self {
165 self.auto_sign_in_after_verification = on;
166 self
167 }
168
169 pub fn ttl(mut self, ttl: Duration) -> Self {
170 self.ttl = ttl;
171 self
172 }
173}
174
175#[derive(Clone, Debug)]
176pub struct SessionConfig {
177 pub(crate) expires_in: Duration,
178 pub(crate) update_age: Duration,
179 pub(crate) fresh_age: Duration,
180 pub(crate) cookie_cache: Option<Duration>,
181 pub(crate) sliding: SlidingRefresh,
182}
183
184impl Default for SessionConfig {
185 fn default() -> Self {
186 Self {
187 expires_in: Duration::days(7),
188 update_age: Duration::days(1),
189 fresh_age: Duration::days(1),
190 cookie_cache: None,
191 sliding: SlidingRefresh::UpdatedAt,
192 }
193 }
194}
195
196impl SessionConfig {
197 pub fn lifetime(&self) -> Duration {
200 self.expires_in
201 }
202
203 pub fn expires_in(mut self, d: Duration) -> Self {
204 self.expires_in = d;
205 self
206 }
207
208 pub fn update_age(mut self, d: Duration) -> Self {
210 self.update_age = d;
211 self
212 }
213
214 pub fn fresh_age(mut self, d: Duration) -> Self {
216 self.fresh_age = d;
217 self
218 }
219
220 pub fn cookie_cache(mut self, max_age: Duration) -> Self {
223 self.cookie_cache = Some(max_age);
224 self
225 }
226
227 pub fn sliding_refresh(mut self, rule: SlidingRefresh) -> Self {
230 self.sliding = rule;
231 self
232 }
233}
234
235#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
237pub enum SlidingRefresh {
238 #[default]
240 UpdatedAt,
241 ExpiresAt,
248}
249
250#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
253pub enum SessionTokens {
254 #[default]
257 Hashed,
258 Raw,
264}
265
266#[derive(Clone, Copy, Debug, PartialEq, Eq)]
267pub enum SameSite {
268 Strict,
269 Lax,
270 None,
271}
272
273#[derive(Clone, Copy, Debug, PartialEq, Eq)]
274pub enum Secure {
275 Auto,
277 Always,
278 Never,
279}
280
281#[derive(Clone, Debug)]
282pub struct CookieConfig {
283 pub(crate) prefix: String,
284 pub(crate) same_site: SameSite,
285 pub(crate) domain: Option<String>,
286 pub(crate) secure: Secure,
287 pub(crate) signing: CookieSigning,
288}
289
290impl Default for CookieConfig {
291 fn default() -> Self {
292 Self {
293 prefix: "fastauth".into(),
294 same_site: SameSite::Lax,
295 domain: None,
296 secure: Secure::Auto,
297 signing: CookieSigning::Fastauth,
298 }
299 }
300}
301
302#[derive(Clone, Debug, Default)]
305pub enum CookieSigning {
306 #[default]
309 Fastauth,
310 BetterAuth(Secret),
320}
321
322impl CookieSigning {
323 pub fn better_auth(secret: impl Into<Vec<u8>>) -> Self {
326 CookieSigning::BetterAuth(Secret::from_bytes(secret))
327 }
328}
329
330impl CookieConfig {
331 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
333 self.prefix = prefix.into();
334 self
335 }
336
337 pub fn same_site(mut self, same_site: SameSite) -> Self {
338 self.same_site = same_site;
339 self
340 }
341
342 pub fn domain(mut self, domain: impl Into<String>) -> Self {
343 self.domain = Some(domain.into());
344 self
345 }
346
347 pub fn secure(mut self, secure: Secure) -> Self {
348 self.secure = secure;
349 self
350 }
351
352 pub fn signing(mut self, signing: CookieSigning) -> Self {
354 self.signing = signing;
355 self
356 }
357}
358
359#[derive(Clone, Debug, PartialEq, Eq)]
364pub enum ClientIp {
365 Socket,
368 Header(String),
373 TrustedProxies { header: String, proxies: usize },
377}
378
379impl ClientIp {
380 pub(crate) fn resolve(&self, parts: &http::request::Parts) -> Option<IpAddr> {
382 let ip = match self {
383 ClientIp::Socket => parts.extensions.get::<ClientAddr>().map(|a| a.0),
384 ClientIp::Header(name) => parts
385 .headers
386 .get(name.as_str())?
387 .to_str()
388 .ok()?
389 .trim()
390 .parse()
391 .ok(),
392 ClientIp::TrustedProxies { header, proxies } => {
393 let mut hops = Vec::new();
394 for value in parts.headers.get_all(header.as_str()) {
395 hops.extend(value.to_str().ok()?.split(',').map(str::trim));
396 }
397 let index = hops.len().checked_sub(*proxies)?;
398 hops.get(index)?.parse().ok()
399 }
400 };
401 ip.map(|ip: IpAddr| ip.to_canonical())
402 }
403}
404
405type IdGenerator = Arc<dyn Fn() -> String + Send + Sync>;
406
407#[derive(Clone, Default)]
427pub enum IdStrategy {
428 #[default]
431 Ulid,
432 UuidV7,
434 UuidV4,
436 Custom(IdGenerator),
440}
441
442impl IdStrategy {
443 pub const MAX_LEN: usize = 255;
445
446 pub fn custom(generate: impl Fn() -> String + Send + Sync + 'static) -> Self {
448 IdStrategy::Custom(Arc::new(generate))
449 }
450
451 pub fn generate(&self) -> Result<Id, AuthError> {
454 let id = match self {
455 IdStrategy::Ulid => ulid(OffsetDateTime::now_utc()),
456 IdStrategy::UuidV7 => uuid::Uuid::now_v7().to_string(),
457 IdStrategy::UuidV4 => uuid::Uuid::new_v4().to_string(),
458 IdStrategy::Custom(generate) => {
459 let id = generate();
460 if id.is_empty() {
461 return Err(AuthError::internal(
462 "the custom id generator (IdStrategy::Custom) returned an empty id",
463 ));
464 }
465 if id.len() > Self::MAX_LEN {
466 return Err(AuthError::internal(format_args!(
467 "the custom id generator (IdStrategy::Custom) returned a {}-byte id; ids are at most {} bytes",
468 id.len(),
469 Self::MAX_LEN
470 )));
471 }
472 id
473 }
474 };
475 Ok(Id::from(id))
476 }
477
478 pub fn storage(&self) -> IdStorage {
480 match self {
481 IdStrategy::UuidV7 | IdStrategy::UuidV4 => IdStorage::Uuid,
482 IdStrategy::Ulid | IdStrategy::Custom(_) => IdStorage::Text,
483 }
484 }
485}
486
487impl fmt::Debug for IdStrategy {
488 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
489 match self {
490 IdStrategy::Ulid => f.write_str("Ulid"),
491 IdStrategy::UuidV7 => f.write_str("UuidV7"),
492 IdStrategy::UuidV4 => f.write_str("UuidV4"),
493 IdStrategy::Custom(_) => f.write_str("Custom(..)"),
494 }
495 }
496}
497
498const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
499
500fn ulid(at: OffsetDateTime) -> String {
502 let millis = (at.unix_timestamp_nanos() / 1_000_000) as u128 & ((1 << 48) - 1);
503 let mut random = [0u8; 16];
504 getrandom::fill(&mut random[6..]).expect("the OS random number generator is available");
505 let value = millis << 80 | u128::from_be_bytes(random);
506 (0..26)
507 .rev()
508 .map(|digit| CROCKFORD[(value >> (digit * 5)) as usize & 31] as char)
509 .collect()
510}
511
512#[derive(Clone, Debug)]
514pub struct CoreConfig {
515 pub app_name: String,
516 pub base_url: Url,
517 pub base_path: String,
518 pub trusted_origins: Vec<String>,
519 pub session: SessionConfig,
520 pub cookies: CookieConfig,
521 pub email_password: Option<EmailPassword>,
522 pub email_verification: EmailVerification,
523 pub rate_limit: RateLimit,
524 pub client_ip: ClientIp,
525 pub ids: IdStrategy,
526 pub(crate) secure_cookies: bool,
527 pub(crate) session_tokens: SessionTokens,
528 pub(crate) plaintext_oauth_tokens: bool,
529 pub(crate) owned_accounts: Option<Vec<String>>,
530}
531
532impl CoreConfig {
533 pub fn auth_url(&self) -> String {
535 format!(
536 "{}{}",
537 self.base_url.as_str().trim_end_matches('/'),
538 self.base_path
539 )
540 }
541
542 pub fn is_trusted_origin(&self, origin: &str) -> bool {
543 let origin = origin.trim_end_matches('/');
544 origin == self.base_url.origin().ascii_serialization()
545 || self.trusted_origins.iter().any(|o| o == origin)
546 }
547
548 pub fn is_safe_redirect(&self, target: &str) -> bool {
551 self.resolve_redirect(target).is_some()
552 }
553
554 pub fn resolve_redirect(&self, target: &str) -> Option<Url> {
562 if target.chars().any(char::is_control) || target.contains('\\') {
563 return None;
564 }
565 if !target.starts_with('/') {
566 return Url::parse(target)
567 .ok()
568 .filter(|u| self.is_trusted_origin(&u.origin().ascii_serialization()));
569 }
570 let path = target
571 .split(['?', '#'])
572 .next()
573 .unwrap_or_default()
574 .to_ascii_lowercase();
575 if target.starts_with("//") || path.contains("%2f") || path.contains("%5c") {
576 return None;
577 }
578 self.base_url
579 .join(target)
580 .ok()
581 .filter(|u| u.origin() == self.base_url.origin())
582 }
583
584 pub fn is_fresh(&self, session: &Session) -> bool {
587 let fresh_age = self.session.fresh_age;
588 fresh_age.is_zero() || OffsetDateTime::now_utc() - session.created_at <= fresh_age
589 }
590
591 pub fn session_tokens(&self) -> SessionTokens {
593 self.session_tokens
594 }
595
596 pub fn oauth_tokens_in_plaintext(&self) -> bool {
599 self.plaintext_oauth_tokens
600 }
601
602 pub fn session_token_eq(&self, token: &str) -> Where<Session> {
605 match self.session_tokens {
606 SessionTokens::Hashed => Session::TOKEN_HASH.eq(Hash::sha256(token)),
607 SessionTokens::Raw => Session::TOKEN.eq(token),
608 }
609 }
610
611 pub fn owns_account_provider(&self, provider_id: &str) -> bool {
616 self.owned_accounts
617 .as_ref()
618 .is_none_or(|owned| owned.iter().any(|p| p == provider_id))
619 }
620
621 pub fn owned_account_providers(&self) -> Option<&[String]> {
623 self.owned_accounts.as_deref()
624 }
625
626 pub fn cookie_name(&self, name: &str) -> String {
627 let secure = if self.secure_cookies { "__Secure-" } else { "" };
628 format!("{secure}{}.{name}", self.cookies.prefix)
629 }
630}
631
632#[cfg(test)]
633mod tests {
634 use super::*;
635
636 fn decode_ulid_millis(id: &str) -> i128 {
637 let value = id.bytes().fold(0u128, |acc, ch| {
638 let digit = CROCKFORD
639 .iter()
640 .position(|&c| c == ch)
641 .expect("crockford digit");
642 acc << 5 | digit as u128
643 });
644 (value >> 80) as i128
645 }
646
647 #[test]
648 fn ulid_is_26_crockford_characters_with_the_current_time() {
649 let before = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
650 let id = IdStrategy::Ulid.generate().unwrap();
651 let after = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
652 let id = id.as_str();
653 assert_eq!(id.len(), 26, "{id}");
654 assert!(id.bytes().all(|b| CROCKFORD.contains(&b)), "{id}");
655 assert!(id.as_bytes()[0] <= b'7', "a ULID fits in 128 bits: {id}");
656 assert!((before..=after).contains(&decode_ulid_millis(id)), "{id}");
657 assert_ne!(id, IdStrategy::Ulid.generate().unwrap().as_str());
658 }
659
660 #[test]
661 fn ulids_sort_by_time() {
662 let base = OffsetDateTime::now_utc();
663 let ids: Vec<String> = (0..50)
664 .map(|ms| ulid(base + Duration::milliseconds(ms)))
665 .collect();
666 let mut sorted = ids.clone();
667 sorted.sort();
668 assert_eq!(ids, sorted);
669
670 let first = IdStrategy::Ulid.generate().unwrap();
671 std::thread::sleep(std::time::Duration::from_millis(2));
672 let second = IdStrategy::Ulid.generate().unwrap();
673 assert!(first < second, "{first:?} < {second:?}");
674 }
675
676 #[test]
677 fn uuid_strategies_have_their_version_nibble() {
678 for (strategy, version) in [(IdStrategy::UuidV7, '7'), (IdStrategy::UuidV4, '4')] {
679 let id = strategy.generate().unwrap();
680 let id = id.as_str();
681 assert_eq!(id.len(), 36, "{id}");
682 assert_eq!(id.as_bytes()[14] as char, version, "{id}");
683 assert!(
684 matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'),
685 "{id}"
686 );
687 assert_eq!(strategy.storage(), IdStorage::Uuid);
688 }
689 }
690
691 #[test]
692 fn custom_ids_are_validated() {
693 let ok = IdStrategy::custom(|| "x".repeat(IdStrategy::MAX_LEN));
694 assert_eq!(ok.generate().unwrap().as_str().len(), 255);
695 assert_eq!(ok.storage(), IdStorage::Text);
696
697 for bad in [String::new(), "x".repeat(IdStrategy::MAX_LEN + 1)] {
698 let strategy = IdStrategy::custom(move || bad.clone());
699 let err = strategy.generate().unwrap_err();
700 assert_eq!(err.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
701 assert_eq!(err.code(), crate::error::codes::INTERNAL);
702 }
703 assert_eq!(format!("{ok:?}"), "Custom(..)");
704 }
705
706 fn request(headers: &[(&str, &str)]) -> http::request::Parts {
707 let mut builder = http::Request::builder();
708 for (name, value) in headers {
709 builder = builder.header(*name, *value);
710 }
711 builder.body(()).unwrap().into_parts().0
712 }
713
714 fn ip(source: &ClientIp, headers: &[(&str, &str)]) -> Option<String> {
715 source.resolve(&request(headers)).map(|ip| ip.to_string())
716 }
717
718 #[test]
719 fn client_ip_header_takes_exactly_one_address() {
720 let source = ClientIp::Header("fly-client-ip".into());
721 assert_eq!(
722 ip(&source, &[("fly-client-ip", " 203.0.113.9 ")]).as_deref(),
723 Some("203.0.113.9")
724 );
725 assert_eq!(
726 ip(&source, &[("fly-client-ip", "2001:db8::1")]).as_deref(),
727 Some("2001:db8::1")
728 );
729 assert_eq!(
730 ip(&source, &[("fly-client-ip", "::ffff:203.0.113.9")]).as_deref(),
731 Some("203.0.113.9")
732 );
733 assert_eq!(
734 ip(&source, &[("fly-client-ip", "1.2.3.4, 203.0.113.9")]),
735 None
736 );
737 assert_eq!(ip(&source, &[("fly-client-ip", "anything")]), None);
738 assert_eq!(ip(&source, &[]), None);
739 }
740
741 #[test]
742 fn client_ip_trusted_proxies_counts_from_the_right() {
743 let one = ClientIp::TrustedProxies {
744 header: "x-forwarded-for".into(),
745 proxies: 1,
746 };
747 let two = ClientIp::TrustedProxies {
748 header: "x-forwarded-for".into(),
749 proxies: 2,
750 };
751 let spoofed = [("x-forwarded-for", "6.6.6.6, 203.0.113.9")];
752 assert_eq!(ip(&one, &spoofed).as_deref(), Some("203.0.113.9"));
753 assert_eq!(ip(&two, &spoofed).as_deref(), Some("6.6.6.6"));
754 let chain = [
755 ("x-forwarded-for", "6.6.6.6, 203.0.113.9"),
756 ("x-forwarded-for", "10.0.0.2"),
757 ];
758 assert_eq!(ip(&two, &chain).as_deref(), Some("203.0.113.9"));
759 assert_eq!(ip(&two, &[("x-forwarded-for", "203.0.113.9")]), None);
760 assert_eq!(ip(&one, &[("x-forwarded-for", "1.2.3.4, junk")]), None);
761 assert_eq!(ip(&one, &[]), None);
762 }
763}