Skip to main content

fastauth_core/
config.rs

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/// Email and password sign-in. Off unless `.email_password(..)` is called.
20#[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    /// Whether a password reset signs the user out everywhere, for plugins that reset passwords.
65    pub fn revokes_sessions_on_password_reset(&self) -> bool {
66        self.revoke_sessions_on_password_reset
67    }
68
69    /// Whether sign-in needs a verified email, for plugins that sign in with a password.
70    pub fn requires_email_verification(&self) -> bool {
71        self.require_email_verification
72    }
73
74    /// The longest password accepted, for plugins that check passwords.
75    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    /// Sign-in fails with `EMAIL_NOT_VERIFIED` until the user verifies. Needs a mailer.
90    pub fn require_email_verification(mut self, on: bool) -> Self {
91        self.require_email_verification = on;
92        self
93    }
94
95    /// Sign-up returns a session (default true). Ignored when verification is required.
96    pub fn auto_sign_in(mut self, on: bool) -> Self {
97        self.auto_sign_in = on;
98        self
99    }
100
101    /// Whether a password reset signs the user out everywhere (default true), so a reset after
102    /// a compromise also ends the attacker's sessions. Better Auth defaults to false.
103    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    /// Extra check on new passwords; returning false answers `PASSWORD_TOO_WEAK`.
114    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    /// How many password hashes run at once at most (default: the number of CPUs). Each
128    /// holds the hasher's memory until it finishes (19 MiB for argon2id, 32 MiB for
129    /// `BetterAuthScrypt`), so this bounds what a burst of sign-ins can allocate.
130    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    /// Whether verifying an email signs the user in, for plugins that verify emails.
155    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    /// How long a session lasts, and the session cookie's `Max-Age`, for plugins that set
198    /// session cookies of their own.
199    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    /// Extend the expiry at most this often (default one day).
209    pub fn update_age(mut self, d: Duration) -> Self {
210        self.update_age = d;
211        self
212    }
213
214    /// `Fresh` endpoints need a session created within this window. Zero disables the check.
215    pub fn fresh_age(mut self, d: Duration) -> Self {
216        self.fresh_age = d;
217        self
218    }
219
220    /// A signed cookie caching the session for `max_age`. Saves the DB lookup, at the cost
221    /// of revocations taking up to `max_age` to reach other devices.
222    pub fn cookie_cache(mut self, max_age: Duration) -> Self {
223        self.cookie_cache = Some(max_age);
224        self
225    }
226
227    /// When a session is due for its sliding extension (default
228    /// [`SlidingRefresh::UpdatedAt`]).
229    pub fn sliding_refresh(mut self, rule: SlidingRefresh) -> Self {
230        self.sliding = rule;
231        self
232    }
233}
234
235/// When the sliding refresh extends a session's expiry to `expires_in` from now.
236#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
237pub enum SlidingRefresh {
238    /// Once `update_age` has passed since the session row's `updated_at` (the default).
239    #[default]
240    UpdatedAt,
241    /// Once `update_age` has passed since the expiry was last set, read from `expires_at`
242    /// (`expires_at - expires_in + update_age <= now`): Better Auth's rule. Better Auth moves
243    /// `updatedAt` on every change to a session (an active organization, say), so on a
244    /// database it shares, `updated_at` doesn't say when the session was last extended.
245    /// A session counts as a `rememberMe: false` one, never extended, when it was created to
246    /// last one day or less (`expires_at - created_at`), as well as by its marker cookie.
247    ExpiresAt,
248}
249
250/// How session tokens are kept in the `session` table
251/// ([`Builder::session_tokens`](crate::Builder::session_tokens)).
252#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
253pub enum SessionTokens {
254    /// Only each token's SHA-256, in `token_hash` (bytes). The default: whoever reads the
255    /// table, from a backup or an injection, holds nothing they can sign in with.
256    #[default]
257    Hashed,
258    /// The token itself, in `token` (text, unique), looked up as is. This is how Better
259    /// Auth stores sessions, so both apps resolve each other's sessions when they share a
260    /// database. It gives up what hashing protects: anyone who can read the `session`
261    /// table can use every live session in it. Use it only while sharing the table, and
262    /// switch back once the other app is gone.
263    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    /// Secure (and `__Secure-` prefixed) when `base_url` is https.
276    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/// How signed cookies (the session token, the `rememberMe: false` marker and every cookie a
303/// plugin signs) are signed and checked.
304#[derive(Clone, Debug, Default)]
305pub enum CookieSigning {
306    /// `value.signature`, an HMAC-SHA256 in base64url keyed with a key derived from the
307    /// secrets (`fastauth/v1/cookie`), every configured secret verifying session tokens.
308    #[default]
309    Fastauth,
310    /// Better Auth's format, so a Better Auth app on the same database and fastauth accept each
311    /// other's cookies: `encodeURIComponent(value + "." + signature)`, the signature an
312    /// HMAC-SHA256 in padded standard base64 keyed with this secret's bytes as they are, with
313    /// no key derivation. Cookies are verified in constant time and accepted percent-encoded or
314    /// not, as better-call does.
315    ///
316    /// Only this one secret signs and verifies cookies, as in Better Auth 1.7.8, which signs
317    /// cookies with its current secret alone: rotating it signs everyone out of both apps.
318    /// `.secrets(..)` still keys everything else. Can't be combined with the cookie cache.
319    BetterAuth(Secret),
320}
321
322impl CookieSigning {
323    /// [`CookieSigning::BetterAuth`] with the Better Auth app's `BETTER_AUTH_SECRET`, as the
324    /// app has it (its UTF-8 bytes, not decoded).
325    pub fn better_auth(secret: impl Into<Vec<u8>>) -> Self {
326        CookieSigning::BetterAuth(Secret::from_bytes(secret))
327    }
328}
329
330impl CookieConfig {
331    /// `"better-auth"` makes cookie names match a Better Auth server.
332    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    /// How signed cookies are signed (default [`CookieSigning::Fastauth`]).
353    pub fn signing(mut self, signing: CookieSigning) -> Self {
354        self.signing = signing;
355        self
356    }
357}
358
359/// Where the client IP comes from. Rate limits are kept per client IP, and sessions record it.
360///
361/// The first request whose IP can't be read is logged. Such requests are rate-limited per
362/// account their JSON body names (`email` or `username`), and otherwise share one bucket.
363#[derive(Clone, Debug, PartialEq, Eq)]
364pub enum ClientIp {
365    /// The socket address the integration puts in request extensions (default). In axum,
366    /// serve with `into_make_service_with_connect_info::<SocketAddr>()`.
367    Socket,
368    /// A header holding exactly one IP address, set by a proxy you trust that overwrites
369    /// whatever the client sent, e.g. `fly-client-ip` or `cf-connecting-ip`. Any other value
370    /// counts as no IP. Never `x-forwarded-for`: proxies append to it, so the client writes
371    /// its start. Use `TrustedProxies` for that.
372    Header(String),
373    /// A header that each proxy appends to, like `x-forwarded-for`. `proxies` is how many
374    /// proxies you run in front of the app; the client is the `proxies`-th address from the
375    /// right, because everything left of it was sent by the client.
376    TrustedProxies { header: String, proxies: usize },
377}
378
379impl ClientIp {
380    /// The client IP for a request, or `None` if the source doesn't hold a valid one.
381    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/// How fastauth generates the ids of the rows it creates: users, sessions, accounts,
408/// verifications and every row a plugin creates through `ctx.new_id()`.
409///
410/// Set it with `FastAuth::builder().ids(..)`. The strategy also picks how id columns are
411/// stored ([`IdStrategy::storage`]): the UUID strategies use Postgres' native `uuid` type,
412/// the others `text`. Switching strategies on an existing database doesn't convert its
413/// columns; the migrator warns about the mismatch instead.
414///
415/// ```
416/// use fastauth_core::config::IdStrategy;
417///
418/// let id = IdStrategy::default().generate().unwrap();
419/// assert_eq!(id.as_str().len(), 26);
420///
421/// let custom = IdStrategy::custom(|| {
422///     format!("usr_{}", fastauth_core::crypto::random_string(12, b"0123456789abcdef"))
423/// });
424/// assert!(custom.generate().unwrap().as_str().starts_with("usr_"));
425/// ```
426#[derive(Clone, Default)]
427pub enum IdStrategy {
428    /// A [ULID](https://github.com/ulid/spec): 26 characters of Crockford base32, sortable
429    /// by creation time. Stored as `text`. The default.
430    #[default]
431    Ulid,
432    /// A UUIDv7 in hyphenated form, sortable by creation time. Stored as `uuid` on Postgres.
433    UuidV7,
434    /// A random UUIDv4 in hyphenated form. Stored as `uuid` on Postgres.
435    UuidV4,
436    /// Ids from your own function, stored as `text`. Every id is checked when it's
437    /// generated: an empty one, or one longer than [`IdStrategy::MAX_LEN`] bytes, fails the
438    /// request with a 500 and an error log line. Ids must be unique; fastauth doesn't retry.
439    Custom(IdGenerator),
440}
441
442impl IdStrategy {
443    /// The longest id, in bytes, a custom generator may return.
444    pub const MAX_LEN: usize = 255;
445
446    /// `IdStrategy::Custom` from a closure.
447    pub fn custom(generate: impl Fn() -> String + Send + Sync + 'static) -> Self {
448        IdStrategy::Custom(Arc::new(generate))
449    }
450
451    /// A new id. Only a custom generator can fail: with a 500 `INTERNAL_SERVER_ERROR`
452    /// whose detail is logged, never sent to the client.
453    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    /// How id columns are stored for this strategy.
479    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
500/// A ULID for `at`: 48 bits of Unix milliseconds, then 80 random bits, as 26 base32 digits.
501fn 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/// Everything the builder collected, frozen at `.build()`.
513#[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    /// `https://acme.dk/api/auth`
534    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    /// Accepts relative paths (`/dashboard`) and absolute URLs on a trusted origin. See
549    /// [`CoreConfig::resolve_redirect`].
550    pub fn is_safe_redirect(&self, target: &str) -> bool {
551        self.resolve_redirect(target).is_some()
552    }
553
554    /// Where a browser lands when redirected to `target`, or `None` when that isn't safe.
555    ///
556    /// Control characters and backslashes are refused anywhere, because browsers drop or
557    /// reinterpret them (`/\t/evil.example` opens `//evil.example`). A relative target must
558    /// start with a single `/`, have no encoded `/` or `\` (`%2f`, `%5c`) in its path, and
559    /// still be on `base_url`'s origin once resolved against it. An absolute target must be on
560    /// a trusted origin.
561    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    /// Whether `session` was created within `fresh_age`, the rule behind `Fresh` access.
585    /// A zero `fresh_age` makes every session fresh.
586    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    /// How session tokens are stored ([`SessionTokens`]).
592    pub fn session_tokens(&self) -> SessionTokens {
593        self.session_tokens
594    }
595
596    /// Whether OAuth tokens are stored as plain text
597    /// ([`Builder::store_oauth_tokens_in_plaintext`](crate::Builder::store_oauth_tokens_in_plaintext)).
598    pub fn oauth_tokens_in_plaintext(&self) -> bool {
599        self.plaintext_oauth_tokens
600    }
601
602    /// The filter that finds the session row of `token`, under the configured
603    /// [`SessionTokens`]: by its SHA-256, or by the token itself.
604    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    /// Whether fastauth reads, changes and deletes `account` rows of `provider_id`. Every
612    /// provider, unless [`Builder::only_owned_accounts`](crate::Builder::only_owned_accounts)
613    /// is on: then only `credential` and the providers plugins register (social sign-in),
614    /// and rows another app owns, such as its `oidc` accounts, are left alone.
615    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    /// The account providers fastauth owns, or `None` when it manages every row.
622    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}