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, PasswordHasher};
10use crate::error::AuthError;
11use crate::models::Session;
12use crate::rate_limit::RateLimit;
13use crate::schema::IdStorage;
14use crate::value::Id;
15
16type PasswordPolicy = Arc<dyn Fn(&str) -> bool + Send + Sync>;
17
18#[derive(Clone)]
20pub struct EmailPassword {
21 pub(crate) min_password_length: usize,
22 pub(crate) max_password_length: usize,
23 pub(crate) require_email_verification: bool,
24 pub(crate) auto_sign_in: bool,
25 pub(crate) revoke_sessions_on_password_reset: bool,
26 pub(crate) reset_password_ttl: Duration,
27 pub(crate) password_policy: Option<PasswordPolicy>,
28 pub(crate) hasher: Arc<dyn PasswordHasher>,
29}
30
31impl fmt::Debug for EmailPassword {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 f.debug_struct("EmailPassword")
34 .field("min_password_length", &self.min_password_length)
35 .field("max_password_length", &self.max_password_length)
36 .field(
37 "require_email_verification",
38 &self.require_email_verification,
39 )
40 .field("auto_sign_in", &self.auto_sign_in)
41 .finish_non_exhaustive()
42 }
43}
44
45impl Default for EmailPassword {
46 fn default() -> Self {
47 Self {
48 min_password_length: 8,
49 max_password_length: 128,
50 require_email_verification: false,
51 auto_sign_in: true,
52 revoke_sessions_on_password_reset: true,
53 reset_password_ttl: Duration::hours(1),
54 password_policy: None,
55 hasher: Arc::new(Argon2id::owasp()),
56 }
57 }
58}
59
60impl EmailPassword {
61 pub fn revokes_sessions_on_password_reset(&self) -> bool {
63 self.revoke_sessions_on_password_reset
64 }
65
66 pub fn requires_email_verification(&self) -> bool {
68 self.require_email_verification
69 }
70
71 pub fn max_password_len(&self) -> usize {
73 self.max_password_length
74 }
75
76 pub fn min_password_length(mut self, n: usize) -> Self {
77 self.min_password_length = n;
78 self
79 }
80
81 pub fn max_password_length(mut self, n: usize) -> Self {
82 self.max_password_length = n;
83 self
84 }
85
86 pub fn require_email_verification(mut self, on: bool) -> Self {
88 self.require_email_verification = on;
89 self
90 }
91
92 pub fn auto_sign_in(mut self, on: bool) -> Self {
94 self.auto_sign_in = on;
95 self
96 }
97
98 pub fn revoke_sessions_on_password_reset(mut self, on: bool) -> Self {
101 self.revoke_sessions_on_password_reset = on;
102 self
103 }
104
105 pub fn reset_password_ttl(mut self, ttl: Duration) -> Self {
106 self.reset_password_ttl = ttl;
107 self
108 }
109
110 pub fn password_policy(
112 mut self,
113 policy: impl Fn(&str) -> bool + Send + Sync + 'static,
114 ) -> Self {
115 self.password_policy = Some(Arc::new(policy));
116 self
117 }
118
119 pub fn hasher(mut self, hasher: impl PasswordHasher) -> Self {
120 self.hasher = Arc::new(hasher);
121 self
122 }
123}
124
125#[derive(Clone, Debug)]
126pub struct EmailVerification {
127 pub(crate) send_on_sign_up: bool,
128 pub(crate) auto_sign_in_after_verification: bool,
129 pub(crate) ttl: Duration,
130}
131
132impl Default for EmailVerification {
133 fn default() -> Self {
134 Self {
135 send_on_sign_up: true,
136 auto_sign_in_after_verification: false,
137 ttl: Duration::hours(1),
138 }
139 }
140}
141
142impl EmailVerification {
143 pub fn auto_signs_in_after_verification(&self) -> bool {
145 self.auto_sign_in_after_verification
146 }
147
148 pub fn send_on_sign_up(mut self, on: bool) -> Self {
149 self.send_on_sign_up = on;
150 self
151 }
152
153 pub fn auto_sign_in_after_verification(mut self, on: bool) -> Self {
154 self.auto_sign_in_after_verification = on;
155 self
156 }
157
158 pub fn ttl(mut self, ttl: Duration) -> Self {
159 self.ttl = ttl;
160 self
161 }
162}
163
164#[derive(Clone, Debug)]
165pub struct SessionConfig {
166 pub(crate) expires_in: Duration,
167 pub(crate) update_age: Duration,
168 pub(crate) fresh_age: Duration,
169 pub(crate) cookie_cache: Option<Duration>,
170}
171
172impl Default for SessionConfig {
173 fn default() -> Self {
174 Self {
175 expires_in: Duration::days(7),
176 update_age: Duration::days(1),
177 fresh_age: Duration::days(1),
178 cookie_cache: None,
179 }
180 }
181}
182
183impl SessionConfig {
184 pub fn lifetime(&self) -> Duration {
187 self.expires_in
188 }
189
190 pub fn expires_in(mut self, d: Duration) -> Self {
191 self.expires_in = d;
192 self
193 }
194
195 pub fn update_age(mut self, d: Duration) -> Self {
197 self.update_age = d;
198 self
199 }
200
201 pub fn fresh_age(mut self, d: Duration) -> Self {
203 self.fresh_age = d;
204 self
205 }
206
207 pub fn cookie_cache(mut self, max_age: Duration) -> Self {
210 self.cookie_cache = Some(max_age);
211 self
212 }
213}
214
215#[derive(Clone, Copy, Debug, PartialEq, Eq)]
216pub enum SameSite {
217 Strict,
218 Lax,
219 None,
220}
221
222#[derive(Clone, Copy, Debug, PartialEq, Eq)]
223pub enum Secure {
224 Auto,
226 Always,
227 Never,
228}
229
230#[derive(Clone, Debug)]
231pub struct CookieConfig {
232 pub(crate) prefix: String,
233 pub(crate) same_site: SameSite,
234 pub(crate) domain: Option<String>,
235 pub(crate) secure: Secure,
236}
237
238impl Default for CookieConfig {
239 fn default() -> Self {
240 Self {
241 prefix: "fastauth".into(),
242 same_site: SameSite::Lax,
243 domain: None,
244 secure: Secure::Auto,
245 }
246 }
247}
248
249impl CookieConfig {
250 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
252 self.prefix = prefix.into();
253 self
254 }
255
256 pub fn same_site(mut self, same_site: SameSite) -> Self {
257 self.same_site = same_site;
258 self
259 }
260
261 pub fn domain(mut self, domain: impl Into<String>) -> Self {
262 self.domain = Some(domain.into());
263 self
264 }
265
266 pub fn secure(mut self, secure: Secure) -> Self {
267 self.secure = secure;
268 self
269 }
270}
271
272#[derive(Clone, Debug, PartialEq, Eq)]
277pub enum ClientIp {
278 Socket,
281 Header(String),
286 TrustedProxies { header: String, proxies: usize },
290}
291
292impl ClientIp {
293 pub(crate) fn resolve(&self, parts: &http::request::Parts) -> Option<IpAddr> {
295 let ip = match self {
296 ClientIp::Socket => parts.extensions.get::<ClientAddr>().map(|a| a.0),
297 ClientIp::Header(name) => parts
298 .headers
299 .get(name.as_str())?
300 .to_str()
301 .ok()?
302 .trim()
303 .parse()
304 .ok(),
305 ClientIp::TrustedProxies { header, proxies } => {
306 let mut hops = Vec::new();
307 for value in parts.headers.get_all(header.as_str()) {
308 hops.extend(value.to_str().ok()?.split(',').map(str::trim));
309 }
310 let index = hops.len().checked_sub(*proxies)?;
311 hops.get(index)?.parse().ok()
312 }
313 };
314 ip.map(|ip: IpAddr| ip.to_canonical())
315 }
316}
317
318type IdGenerator = Arc<dyn Fn() -> String + Send + Sync>;
319
320#[derive(Clone, Default)]
340pub enum IdStrategy {
341 #[default]
344 Ulid,
345 UuidV7,
347 UuidV4,
349 Custom(IdGenerator),
353}
354
355impl IdStrategy {
356 pub const MAX_LEN: usize = 255;
358
359 pub fn custom(generate: impl Fn() -> String + Send + Sync + 'static) -> Self {
361 IdStrategy::Custom(Arc::new(generate))
362 }
363
364 pub fn generate(&self) -> Result<Id, AuthError> {
367 let id = match self {
368 IdStrategy::Ulid => ulid(OffsetDateTime::now_utc()),
369 IdStrategy::UuidV7 => uuid::Uuid::now_v7().to_string(),
370 IdStrategy::UuidV4 => uuid::Uuid::new_v4().to_string(),
371 IdStrategy::Custom(generate) => {
372 let id = generate();
373 if id.is_empty() {
374 return Err(AuthError::internal(
375 "the custom id generator (IdStrategy::Custom) returned an empty id",
376 ));
377 }
378 if id.len() > Self::MAX_LEN {
379 return Err(AuthError::internal(format_args!(
380 "the custom id generator (IdStrategy::Custom) returned a {}-byte id; ids are at most {} bytes",
381 id.len(),
382 Self::MAX_LEN
383 )));
384 }
385 id
386 }
387 };
388 Ok(Id::from(id))
389 }
390
391 pub fn storage(&self) -> IdStorage {
393 match self {
394 IdStrategy::UuidV7 | IdStrategy::UuidV4 => IdStorage::Uuid,
395 IdStrategy::Ulid | IdStrategy::Custom(_) => IdStorage::Text,
396 }
397 }
398}
399
400impl fmt::Debug for IdStrategy {
401 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
402 match self {
403 IdStrategy::Ulid => f.write_str("Ulid"),
404 IdStrategy::UuidV7 => f.write_str("UuidV7"),
405 IdStrategy::UuidV4 => f.write_str("UuidV4"),
406 IdStrategy::Custom(_) => f.write_str("Custom(..)"),
407 }
408 }
409}
410
411const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";
412
413fn ulid(at: OffsetDateTime) -> String {
415 let millis = (at.unix_timestamp_nanos() / 1_000_000) as u128 & ((1 << 48) - 1);
416 let mut random = [0u8; 16];
417 getrandom::fill(&mut random[6..]).expect("the OS random number generator is available");
418 let value = millis << 80 | u128::from_be_bytes(random);
419 (0..26)
420 .rev()
421 .map(|digit| CROCKFORD[(value >> (digit * 5)) as usize & 31] as char)
422 .collect()
423}
424
425#[derive(Clone, Debug)]
427pub struct CoreConfig {
428 pub app_name: String,
429 pub base_url: Url,
430 pub base_path: String,
431 pub trusted_origins: Vec<String>,
432 pub session: SessionConfig,
433 pub cookies: CookieConfig,
434 pub email_password: Option<EmailPassword>,
435 pub email_verification: EmailVerification,
436 pub rate_limit: RateLimit,
437 pub client_ip: ClientIp,
438 pub ids: IdStrategy,
439 pub(crate) secure_cookies: bool,
440}
441
442impl CoreConfig {
443 pub fn auth_url(&self) -> String {
445 format!(
446 "{}{}",
447 self.base_url.as_str().trim_end_matches('/'),
448 self.base_path
449 )
450 }
451
452 pub fn is_trusted_origin(&self, origin: &str) -> bool {
453 let origin = origin.trim_end_matches('/');
454 origin == self.base_url.origin().ascii_serialization()
455 || self.trusted_origins.iter().any(|o| o == origin)
456 }
457
458 pub fn is_safe_redirect(&self, target: &str) -> bool {
461 self.resolve_redirect(target).is_some()
462 }
463
464 pub fn resolve_redirect(&self, target: &str) -> Option<Url> {
472 if target.chars().any(char::is_control) || target.contains('\\') {
473 return None;
474 }
475 if !target.starts_with('/') {
476 return Url::parse(target)
477 .ok()
478 .filter(|u| self.is_trusted_origin(&u.origin().ascii_serialization()));
479 }
480 let path = target
481 .split(['?', '#'])
482 .next()
483 .unwrap_or_default()
484 .to_ascii_lowercase();
485 if target.starts_with("//") || path.contains("%2f") || path.contains("%5c") {
486 return None;
487 }
488 self.base_url
489 .join(target)
490 .ok()
491 .filter(|u| u.origin() == self.base_url.origin())
492 }
493
494 pub fn is_fresh(&self, session: &Session) -> bool {
497 let fresh_age = self.session.fresh_age;
498 fresh_age.is_zero() || OffsetDateTime::now_utc() - session.created_at <= fresh_age
499 }
500
501 pub fn cookie_name(&self, name: &str) -> String {
502 let secure = if self.secure_cookies { "__Secure-" } else { "" };
503 format!("{secure}{}.{name}", self.cookies.prefix)
504 }
505}
506
507#[cfg(test)]
508mod tests {
509 use super::*;
510
511 fn decode_ulid_millis(id: &str) -> i128 {
512 let value = id.bytes().fold(0u128, |acc, ch| {
513 let digit = CROCKFORD
514 .iter()
515 .position(|&c| c == ch)
516 .expect("crockford digit");
517 acc << 5 | digit as u128
518 });
519 (value >> 80) as i128
520 }
521
522 #[test]
523 fn ulid_is_26_crockford_characters_with_the_current_time() {
524 let before = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
525 let id = IdStrategy::Ulid.generate().unwrap();
526 let after = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
527 let id = id.as_str();
528 assert_eq!(id.len(), 26, "{id}");
529 assert!(id.bytes().all(|b| CROCKFORD.contains(&b)), "{id}");
530 assert!(id.as_bytes()[0] <= b'7', "a ULID fits in 128 bits: {id}");
531 assert!((before..=after).contains(&decode_ulid_millis(id)), "{id}");
532 assert_ne!(id, IdStrategy::Ulid.generate().unwrap().as_str());
533 }
534
535 #[test]
536 fn ulids_sort_by_time() {
537 let base = OffsetDateTime::now_utc();
538 let ids: Vec<String> = (0..50)
539 .map(|ms| ulid(base + Duration::milliseconds(ms)))
540 .collect();
541 let mut sorted = ids.clone();
542 sorted.sort();
543 assert_eq!(ids, sorted);
544
545 let first = IdStrategy::Ulid.generate().unwrap();
546 std::thread::sleep(std::time::Duration::from_millis(2));
547 let second = IdStrategy::Ulid.generate().unwrap();
548 assert!(first < second, "{first:?} < {second:?}");
549 }
550
551 #[test]
552 fn uuid_strategies_have_their_version_nibble() {
553 for (strategy, version) in [(IdStrategy::UuidV7, '7'), (IdStrategy::UuidV4, '4')] {
554 let id = strategy.generate().unwrap();
555 let id = id.as_str();
556 assert_eq!(id.len(), 36, "{id}");
557 assert_eq!(id.as_bytes()[14] as char, version, "{id}");
558 assert!(
559 matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'),
560 "{id}"
561 );
562 assert_eq!(strategy.storage(), IdStorage::Uuid);
563 }
564 }
565
566 #[test]
567 fn custom_ids_are_validated() {
568 let ok = IdStrategy::custom(|| "x".repeat(IdStrategy::MAX_LEN));
569 assert_eq!(ok.generate().unwrap().as_str().len(), 255);
570 assert_eq!(ok.storage(), IdStorage::Text);
571
572 for bad in [String::new(), "x".repeat(IdStrategy::MAX_LEN + 1)] {
573 let strategy = IdStrategy::custom(move || bad.clone());
574 let err = strategy.generate().unwrap_err();
575 assert_eq!(err.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
576 assert_eq!(err.code(), crate::error::codes::INTERNAL);
577 }
578 assert_eq!(format!("{ok:?}"), "Custom(..)");
579 }
580
581 fn request(headers: &[(&str, &str)]) -> http::request::Parts {
582 let mut builder = http::Request::builder();
583 for (name, value) in headers {
584 builder = builder.header(*name, *value);
585 }
586 builder.body(()).unwrap().into_parts().0
587 }
588
589 fn ip(source: &ClientIp, headers: &[(&str, &str)]) -> Option<String> {
590 source.resolve(&request(headers)).map(|ip| ip.to_string())
591 }
592
593 #[test]
594 fn client_ip_header_takes_exactly_one_address() {
595 let source = ClientIp::Header("fly-client-ip".into());
596 assert_eq!(
597 ip(&source, &[("fly-client-ip", " 203.0.113.9 ")]).as_deref(),
598 Some("203.0.113.9")
599 );
600 assert_eq!(
601 ip(&source, &[("fly-client-ip", "2001:db8::1")]).as_deref(),
602 Some("2001:db8::1")
603 );
604 assert_eq!(
605 ip(&source, &[("fly-client-ip", "::ffff:203.0.113.9")]).as_deref(),
606 Some("203.0.113.9")
607 );
608 assert_eq!(
609 ip(&source, &[("fly-client-ip", "1.2.3.4, 203.0.113.9")]),
610 None
611 );
612 assert_eq!(ip(&source, &[("fly-client-ip", "anything")]), None);
613 assert_eq!(ip(&source, &[]), None);
614 }
615
616 #[test]
617 fn client_ip_trusted_proxies_counts_from_the_right() {
618 let one = ClientIp::TrustedProxies {
619 header: "x-forwarded-for".into(),
620 proxies: 1,
621 };
622 let two = ClientIp::TrustedProxies {
623 header: "x-forwarded-for".into(),
624 proxies: 2,
625 };
626 let spoofed = [("x-forwarded-for", "6.6.6.6, 203.0.113.9")];
627 assert_eq!(ip(&one, &spoofed).as_deref(), Some("203.0.113.9"));
628 assert_eq!(ip(&two, &spoofed).as_deref(), Some("6.6.6.6"));
629 let chain = [
630 ("x-forwarded-for", "6.6.6.6, 203.0.113.9"),
631 ("x-forwarded-for", "10.0.0.2"),
632 ];
633 assert_eq!(ip(&two, &chain).as_deref(), Some("203.0.113.9"));
634 assert_eq!(ip(&two, &[("x-forwarded-for", "203.0.113.9")]), None);
635 assert_eq!(ip(&one, &[("x-forwarded-for", "1.2.3.4, junk")]), None);
636 assert_eq!(ip(&one, &[]), None);
637 }
638}