fastauth-core 0.8.0

Core of fastauth: the builder, plugin system, sessions, crypto and routing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
use std::fmt;
use std::net::IpAddr;
use std::sync::Arc;

use time::{Duration, OffsetDateTime};
use url::Url;

use crate::auth::ClientAddr;
use crate::crypto::{Argon2id, Hash, PasswordHasher, Secret};
use crate::error::AuthError;
use crate::models::Session;
use crate::query::Where;
use crate::rate_limit::RateLimit;
use crate::schema::IdStorage;
use crate::value::Id;

type PasswordPolicy = Arc<dyn Fn(&str) -> bool + Send + Sync>;

/// Email and password sign-in. Off unless `.email_password(..)` is called.
#[derive(Clone)]
pub struct EmailPassword {
    pub(crate) min_password_length: usize,
    pub(crate) max_password_length: usize,
    pub(crate) require_email_verification: bool,
    pub(crate) auto_sign_in: bool,
    pub(crate) revoke_sessions_on_password_reset: bool,
    pub(crate) reset_password_ttl: Duration,
    pub(crate) password_policy: Option<PasswordPolicy>,
    pub(crate) hasher: Arc<dyn PasswordHasher>,
    pub(crate) max_concurrent_hashes: Option<usize>,
}

impl fmt::Debug for EmailPassword {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EmailPassword")
            .field("min_password_length", &self.min_password_length)
            .field("max_password_length", &self.max_password_length)
            .field(
                "require_email_verification",
                &self.require_email_verification,
            )
            .field("auto_sign_in", &self.auto_sign_in)
            .finish_non_exhaustive()
    }
}

impl Default for EmailPassword {
    fn default() -> Self {
        Self {
            min_password_length: 8,
            max_password_length: 128,
            require_email_verification: false,
            auto_sign_in: true,
            revoke_sessions_on_password_reset: true,
            reset_password_ttl: Duration::hours(1),
            password_policy: None,
            hasher: Arc::new(Argon2id::owasp()),
            max_concurrent_hashes: None,
        }
    }
}

impl EmailPassword {
    /// Whether a password reset signs the user out everywhere, for plugins that reset passwords.
    pub fn revokes_sessions_on_password_reset(&self) -> bool {
        self.revoke_sessions_on_password_reset
    }

    /// Whether sign-in needs a verified email, for plugins that sign in with a password.
    pub fn requires_email_verification(&self) -> bool {
        self.require_email_verification
    }

    /// The longest password accepted, for plugins that check passwords.
    pub fn max_password_len(&self) -> usize {
        self.max_password_length
    }

    pub fn min_password_length(mut self, n: usize) -> Self {
        self.min_password_length = n;
        self
    }

    pub fn max_password_length(mut self, n: usize) -> Self {
        self.max_password_length = n;
        self
    }

    /// Sign-in fails with `EMAIL_NOT_VERIFIED` until the user verifies. Needs a mailer.
    pub fn require_email_verification(mut self, on: bool) -> Self {
        self.require_email_verification = on;
        self
    }

    /// Sign-up returns a session (default true). Ignored when verification is required.
    pub fn auto_sign_in(mut self, on: bool) -> Self {
        self.auto_sign_in = on;
        self
    }

    /// Whether a password reset signs the user out everywhere (default true), so a reset after
    /// a compromise also ends the attacker's sessions. Better Auth defaults to false.
    pub fn revoke_sessions_on_password_reset(mut self, on: bool) -> Self {
        self.revoke_sessions_on_password_reset = on;
        self
    }

    pub fn reset_password_ttl(mut self, ttl: Duration) -> Self {
        self.reset_password_ttl = ttl;
        self
    }

    /// Extra check on new passwords; returning false answers `PASSWORD_TOO_WEAK`.
    pub fn password_policy(
        mut self,
        policy: impl Fn(&str) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.password_policy = Some(Arc::new(policy));
        self
    }

    pub fn hasher(mut self, hasher: impl PasswordHasher) -> Self {
        self.hasher = Arc::new(hasher);
        self
    }

    /// How many password hashes run at once at most (default: the number of CPUs). Each
    /// holds the hasher's memory until it finishes (19 MiB for argon2id, 32 MiB for
    /// `BetterAuthScrypt`), so this bounds what a burst of sign-ins can allocate.
    pub fn max_concurrent_hashes(mut self, n: usize) -> Self {
        self.max_concurrent_hashes = Some(n.max(1));
        self
    }
}

#[derive(Clone, Debug)]
pub struct EmailVerification {
    pub(crate) send_on_sign_up: bool,
    pub(crate) auto_sign_in_after_verification: bool,
    pub(crate) ttl: Duration,
}

impl Default for EmailVerification {
    fn default() -> Self {
        Self {
            send_on_sign_up: true,
            auto_sign_in_after_verification: false,
            ttl: Duration::hours(1),
        }
    }
}

impl EmailVerification {
    /// Whether verifying an email signs the user in, for plugins that verify emails.
    pub fn auto_signs_in_after_verification(&self) -> bool {
        self.auto_sign_in_after_verification
    }

    pub fn send_on_sign_up(mut self, on: bool) -> Self {
        self.send_on_sign_up = on;
        self
    }

    pub fn auto_sign_in_after_verification(mut self, on: bool) -> Self {
        self.auto_sign_in_after_verification = on;
        self
    }

    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = ttl;
        self
    }
}

#[derive(Clone, Debug)]
pub struct SessionConfig {
    pub(crate) expires_in: Duration,
    pub(crate) update_age: Duration,
    pub(crate) fresh_age: Duration,
    pub(crate) cookie_cache: Option<Duration>,
    pub(crate) sliding: SlidingRefresh,
}

impl Default for SessionConfig {
    fn default() -> Self {
        Self {
            expires_in: Duration::days(7),
            update_age: Duration::days(1),
            fresh_age: Duration::days(1),
            cookie_cache: None,
            sliding: SlidingRefresh::UpdatedAt,
        }
    }
}

impl SessionConfig {
    /// How long a session lasts, and the session cookie's `Max-Age`, for plugins that set
    /// session cookies of their own.
    pub fn lifetime(&self) -> Duration {
        self.expires_in
    }

    pub fn expires_in(mut self, d: Duration) -> Self {
        self.expires_in = d;
        self
    }

    /// Extend the expiry at most this often (default one day).
    pub fn update_age(mut self, d: Duration) -> Self {
        self.update_age = d;
        self
    }

    /// `Fresh` endpoints need a session created within this window. Zero disables the check.
    pub fn fresh_age(mut self, d: Duration) -> Self {
        self.fresh_age = d;
        self
    }

    /// A signed cookie caching the session for `max_age`. Saves the DB lookup, at the cost
    /// of revocations taking up to `max_age` to reach other devices.
    pub fn cookie_cache(mut self, max_age: Duration) -> Self {
        self.cookie_cache = Some(max_age);
        self
    }

    /// When a session is due for its sliding extension (default
    /// [`SlidingRefresh::UpdatedAt`]).
    pub fn sliding_refresh(mut self, rule: SlidingRefresh) -> Self {
        self.sliding = rule;
        self
    }
}

/// When the sliding refresh extends a session's expiry to `expires_in` from now.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum SlidingRefresh {
    /// Once `update_age` has passed since the session row's `updated_at` (the default).
    #[default]
    UpdatedAt,
    /// Once `update_age` has passed since the expiry was last set, read from `expires_at`
    /// (`expires_at - expires_in + update_age <= now`): Better Auth's rule. Better Auth moves
    /// `updatedAt` on every change to a session (an active organization, say), so on a
    /// database it shares, `updated_at` doesn't say when the session was last extended.
    /// A session counts as a `rememberMe: false` one, never extended, when it was created to
    /// last one day or less (`expires_at - created_at`), as well as by its marker cookie.
    ExpiresAt,
}

/// How session tokens are kept in the `session` table
/// ([`Builder::session_tokens`](crate::Builder::session_tokens)).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum SessionTokens {
    /// Only each token's SHA-256, in `token_hash` (bytes). The default: whoever reads the
    /// table, from a backup or an injection, holds nothing they can sign in with.
    #[default]
    Hashed,
    /// The token itself, in `token` (text, unique), looked up as is. This is how Better
    /// Auth stores sessions, so both apps resolve each other's sessions when they share a
    /// database. It gives up what hashing protects: anyone who can read the `session`
    /// table can use every live session in it. Use it only while sharing the table, and
    /// switch back once the other app is gone.
    Raw,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SameSite {
    Strict,
    Lax,
    None,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Secure {
    /// Secure (and `__Secure-` prefixed) when `base_url` is https.
    Auto,
    Always,
    Never,
}

#[derive(Clone, Debug)]
pub struct CookieConfig {
    pub(crate) prefix: String,
    pub(crate) same_site: SameSite,
    pub(crate) domain: Option<String>,
    pub(crate) secure: Secure,
    pub(crate) signing: CookieSigning,
}

impl Default for CookieConfig {
    fn default() -> Self {
        Self {
            prefix: "fastauth".into(),
            same_site: SameSite::Lax,
            domain: None,
            secure: Secure::Auto,
            signing: CookieSigning::Fastauth,
        }
    }
}

/// How signed cookies (the session token, the `rememberMe: false` marker and every cookie a
/// plugin signs) are signed and checked.
#[derive(Clone, Debug, Default)]
pub enum CookieSigning {
    /// `value.signature`, an HMAC-SHA256 in base64url keyed with a key derived from the
    /// secrets (`fastauth/v1/cookie`), every configured secret verifying session tokens.
    #[default]
    Fastauth,
    /// Better Auth's format, so a Better Auth app on the same database and fastauth accept each
    /// other's cookies: `encodeURIComponent(value + "." + signature)`, the signature an
    /// HMAC-SHA256 in padded standard base64 keyed with this secret's bytes as they are, with
    /// no key derivation. Cookies are verified in constant time and accepted percent-encoded or
    /// not, as better-call does.
    ///
    /// Only this one secret signs and verifies cookies, as in Better Auth 1.7.8, which signs
    /// cookies with its current secret alone: rotating it signs everyone out of both apps.
    /// `.secrets(..)` still keys everything else. Can't be combined with the cookie cache.
    BetterAuth(Secret),
}

impl CookieSigning {
    /// [`CookieSigning::BetterAuth`] with the Better Auth app's `BETTER_AUTH_SECRET`, as the
    /// app has it (its UTF-8 bytes, not decoded).
    pub fn better_auth(secret: impl Into<Vec<u8>>) -> Self {
        CookieSigning::BetterAuth(Secret::from_bytes(secret))
    }
}

impl CookieConfig {
    /// `"better-auth"` makes cookie names match a Better Auth server.
    pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
        self.prefix = prefix.into();
        self
    }

    pub fn same_site(mut self, same_site: SameSite) -> Self {
        self.same_site = same_site;
        self
    }

    pub fn domain(mut self, domain: impl Into<String>) -> Self {
        self.domain = Some(domain.into());
        self
    }

    pub fn secure(mut self, secure: Secure) -> Self {
        self.secure = secure;
        self
    }

    /// How signed cookies are signed (default [`CookieSigning::Fastauth`]).
    pub fn signing(mut self, signing: CookieSigning) -> Self {
        self.signing = signing;
        self
    }
}

/// Where the client IP comes from. Rate limits are kept per client IP, and sessions record it.
///
/// The first request whose IP can't be read is logged. Such requests are rate-limited per
/// account their JSON body names (`email` or `username`), and otherwise share one bucket.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ClientIp {
    /// The socket address the integration puts in request extensions (default). In axum,
    /// serve with `into_make_service_with_connect_info::<SocketAddr>()`.
    Socket,
    /// A header holding exactly one IP address, set by a proxy you trust that overwrites
    /// whatever the client sent, e.g. `fly-client-ip` or `cf-connecting-ip`. Any other value
    /// counts as no IP. Never `x-forwarded-for`: proxies append to it, so the client writes
    /// its start. Use `TrustedProxies` for that.
    Header(String),
    /// A header that each proxy appends to, like `x-forwarded-for`. `proxies` is how many
    /// proxies you run in front of the app; the client is the `proxies`-th address from the
    /// right, because everything left of it was sent by the client.
    TrustedProxies { header: String, proxies: usize },
}

impl ClientIp {
    /// The client IP for a request, or `None` if the source doesn't hold a valid one.
    pub(crate) fn resolve(&self, parts: &http::request::Parts) -> Option<IpAddr> {
        let ip = match self {
            ClientIp::Socket => parts.extensions.get::<ClientAddr>().map(|a| a.0),
            ClientIp::Header(name) => parts
                .headers
                .get(name.as_str())?
                .to_str()
                .ok()?
                .trim()
                .parse()
                .ok(),
            ClientIp::TrustedProxies { header, proxies } => {
                let mut hops = Vec::new();
                for value in parts.headers.get_all(header.as_str()) {
                    hops.extend(value.to_str().ok()?.split(',').map(str::trim));
                }
                let index = hops.len().checked_sub(*proxies)?;
                hops.get(index)?.parse().ok()
            }
        };
        ip.map(|ip: IpAddr| ip.to_canonical())
    }
}

type IdGenerator = Arc<dyn Fn() -> String + Send + Sync>;

/// How fastauth generates the ids of the rows it creates: users, sessions, accounts,
/// verifications and every row a plugin creates through `ctx.new_id()`.
///
/// Set it with `FastAuth::builder().ids(..)`. The strategy also picks how id columns are
/// stored ([`IdStrategy::storage`]): the UUID strategies use Postgres' native `uuid` type,
/// the others `text`. Switching strategies on an existing database doesn't convert its
/// columns; the migrator warns about the mismatch instead.
///
/// ```
/// use fastauth_core::config::IdStrategy;
///
/// let id = IdStrategy::default().generate().unwrap();
/// assert_eq!(id.as_str().len(), 26);
///
/// let custom = IdStrategy::custom(|| {
///     format!("usr_{}", fastauth_core::crypto::random_string(12, b"0123456789abcdef"))
/// });
/// assert!(custom.generate().unwrap().as_str().starts_with("usr_"));
/// ```
#[derive(Clone, Default)]
pub enum IdStrategy {
    /// A [ULID](https://github.com/ulid/spec): 26 characters of Crockford base32, sortable
    /// by creation time. Stored as `text`. The default.
    #[default]
    Ulid,
    /// A UUIDv7 in hyphenated form, sortable by creation time. Stored as `uuid` on Postgres.
    UuidV7,
    /// A random UUIDv4 in hyphenated form. Stored as `uuid` on Postgres.
    UuidV4,
    /// Ids from your own function, stored as `text`. Every id is checked when it's
    /// generated: an empty one, or one longer than [`IdStrategy::MAX_LEN`] bytes, fails the
    /// request with a 500 and an error log line. Ids must be unique; fastauth doesn't retry.
    Custom(IdGenerator),
}

impl IdStrategy {
    /// The longest id, in bytes, a custom generator may return.
    pub const MAX_LEN: usize = 255;

    /// `IdStrategy::Custom` from a closure.
    pub fn custom(generate: impl Fn() -> String + Send + Sync + 'static) -> Self {
        IdStrategy::Custom(Arc::new(generate))
    }

    /// A new id. Only a custom generator can fail: with a 500 `INTERNAL_SERVER_ERROR`
    /// whose detail is logged, never sent to the client.
    pub fn generate(&self) -> Result<Id, AuthError> {
        let id = match self {
            IdStrategy::Ulid => ulid(OffsetDateTime::now_utc()),
            IdStrategy::UuidV7 => uuid::Uuid::now_v7().to_string(),
            IdStrategy::UuidV4 => uuid::Uuid::new_v4().to_string(),
            IdStrategy::Custom(generate) => {
                let id = generate();
                if id.is_empty() {
                    return Err(AuthError::internal(
                        "the custom id generator (IdStrategy::Custom) returned an empty id",
                    ));
                }
                if id.len() > Self::MAX_LEN {
                    return Err(AuthError::internal(format_args!(
                        "the custom id generator (IdStrategy::Custom) returned a {}-byte id; ids are at most {} bytes",
                        id.len(),
                        Self::MAX_LEN
                    )));
                }
                id
            }
        };
        Ok(Id::from(id))
    }

    /// How id columns are stored for this strategy.
    pub fn storage(&self) -> IdStorage {
        match self {
            IdStrategy::UuidV7 | IdStrategy::UuidV4 => IdStorage::Uuid,
            IdStrategy::Ulid | IdStrategy::Custom(_) => IdStorage::Text,
        }
    }
}

impl fmt::Debug for IdStrategy {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            IdStrategy::Ulid => f.write_str("Ulid"),
            IdStrategy::UuidV7 => f.write_str("UuidV7"),
            IdStrategy::UuidV4 => f.write_str("UuidV4"),
            IdStrategy::Custom(_) => f.write_str("Custom(..)"),
        }
    }
}

const CROCKFORD: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ";

/// A ULID for `at`: 48 bits of Unix milliseconds, then 80 random bits, as 26 base32 digits.
fn ulid(at: OffsetDateTime) -> String {
    let millis = (at.unix_timestamp_nanos() / 1_000_000) as u128 & ((1 << 48) - 1);
    let mut random = [0u8; 16];
    getrandom::fill(&mut random[6..]).expect("the OS random number generator is available");
    let value = millis << 80 | u128::from_be_bytes(random);
    (0..26)
        .rev()
        .map(|digit| CROCKFORD[(value >> (digit * 5)) as usize & 31] as char)
        .collect()
}

/// Everything the builder collected, frozen at `.build()`.
#[derive(Clone, Debug)]
pub struct CoreConfig {
    pub app_name: String,
    pub base_url: Url,
    pub base_path: String,
    pub trusted_origins: Vec<String>,
    pub session: SessionConfig,
    pub cookies: CookieConfig,
    pub email_password: Option<EmailPassword>,
    pub email_verification: EmailVerification,
    pub rate_limit: RateLimit,
    pub client_ip: ClientIp,
    pub ids: IdStrategy,
    pub(crate) secure_cookies: bool,
    pub(crate) session_tokens: SessionTokens,
    pub(crate) plaintext_oauth_tokens: bool,
    pub(crate) owned_accounts: Option<Vec<String>>,
}

impl CoreConfig {
    /// `https://acme.dk/api/auth`
    pub fn auth_url(&self) -> String {
        format!(
            "{}{}",
            self.base_url.as_str().trim_end_matches('/'),
            self.base_path
        )
    }

    pub fn is_trusted_origin(&self, origin: &str) -> bool {
        let origin = origin.trim_end_matches('/');
        origin == self.base_url.origin().ascii_serialization()
            || self.trusted_origins.iter().any(|o| o == origin)
    }

    /// Accepts relative paths (`/dashboard`) and absolute URLs on a trusted origin. See
    /// [`CoreConfig::resolve_redirect`].
    pub fn is_safe_redirect(&self, target: &str) -> bool {
        self.resolve_redirect(target).is_some()
    }

    /// Where a browser lands when redirected to `target`, or `None` when that isn't safe.
    ///
    /// Control characters and backslashes are refused anywhere, because browsers drop or
    /// reinterpret them (`/\t/evil.example` opens `//evil.example`). A relative target must
    /// start with a single `/`, have no encoded `/` or `\` (`%2f`, `%5c`) in its path, and
    /// still be on `base_url`'s origin once resolved against it. An absolute target must be on
    /// a trusted origin.
    pub fn resolve_redirect(&self, target: &str) -> Option<Url> {
        if target.chars().any(char::is_control) || target.contains('\\') {
            return None;
        }
        if !target.starts_with('/') {
            return Url::parse(target)
                .ok()
                .filter(|u| self.is_trusted_origin(&u.origin().ascii_serialization()));
        }
        let path = target
            .split(['?', '#'])
            .next()
            .unwrap_or_default()
            .to_ascii_lowercase();
        if target.starts_with("//") || path.contains("%2f") || path.contains("%5c") {
            return None;
        }
        self.base_url
            .join(target)
            .ok()
            .filter(|u| u.origin() == self.base_url.origin())
    }

    /// Whether `session` was created within `fresh_age`, the rule behind `Fresh` access.
    /// A zero `fresh_age` makes every session fresh.
    pub fn is_fresh(&self, session: &Session) -> bool {
        let fresh_age = self.session.fresh_age;
        fresh_age.is_zero() || OffsetDateTime::now_utc() - session.created_at <= fresh_age
    }

    /// How session tokens are stored ([`SessionTokens`]).
    pub fn session_tokens(&self) -> SessionTokens {
        self.session_tokens
    }

    /// Whether OAuth tokens are stored as plain text
    /// ([`Builder::store_oauth_tokens_in_plaintext`](crate::Builder::store_oauth_tokens_in_plaintext)).
    pub fn oauth_tokens_in_plaintext(&self) -> bool {
        self.plaintext_oauth_tokens
    }

    /// The filter that finds the session row of `token`, under the configured
    /// [`SessionTokens`]: by its SHA-256, or by the token itself.
    pub fn session_token_eq(&self, token: &str) -> Where<Session> {
        match self.session_tokens {
            SessionTokens::Hashed => Session::TOKEN_HASH.eq(Hash::sha256(token)),
            SessionTokens::Raw => Session::TOKEN.eq(token),
        }
    }

    /// Whether fastauth reads, changes and deletes `account` rows of `provider_id`. Every
    /// provider, unless [`Builder::only_owned_accounts`](crate::Builder::only_owned_accounts)
    /// is on: then only `credential` and the providers plugins register (social sign-in),
    /// and rows another app owns, such as its `oidc` accounts, are left alone.
    pub fn owns_account_provider(&self, provider_id: &str) -> bool {
        self.owned_accounts
            .as_ref()
            .is_none_or(|owned| owned.iter().any(|p| p == provider_id))
    }

    /// The account providers fastauth owns, or `None` when it manages every row.
    pub fn owned_account_providers(&self) -> Option<&[String]> {
        self.owned_accounts.as_deref()
    }

    pub fn cookie_name(&self, name: &str) -> String {
        let secure = if self.secure_cookies { "__Secure-" } else { "" };
        format!("{secure}{}.{name}", self.cookies.prefix)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn decode_ulid_millis(id: &str) -> i128 {
        let value = id.bytes().fold(0u128, |acc, ch| {
            let digit = CROCKFORD
                .iter()
                .position(|&c| c == ch)
                .expect("crockford digit");
            acc << 5 | digit as u128
        });
        (value >> 80) as i128
    }

    #[test]
    fn ulid_is_26_crockford_characters_with_the_current_time() {
        let before = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
        let id = IdStrategy::Ulid.generate().unwrap();
        let after = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
        let id = id.as_str();
        assert_eq!(id.len(), 26, "{id}");
        assert!(id.bytes().all(|b| CROCKFORD.contains(&b)), "{id}");
        assert!(id.as_bytes()[0] <= b'7', "a ULID fits in 128 bits: {id}");
        assert!((before..=after).contains(&decode_ulid_millis(id)), "{id}");
        assert_ne!(id, IdStrategy::Ulid.generate().unwrap().as_str());
    }

    #[test]
    fn ulids_sort_by_time() {
        let base = OffsetDateTime::now_utc();
        let ids: Vec<String> = (0..50)
            .map(|ms| ulid(base + Duration::milliseconds(ms)))
            .collect();
        let mut sorted = ids.clone();
        sorted.sort();
        assert_eq!(ids, sorted);

        let first = IdStrategy::Ulid.generate().unwrap();
        std::thread::sleep(std::time::Duration::from_millis(2));
        let second = IdStrategy::Ulid.generate().unwrap();
        assert!(first < second, "{first:?} < {second:?}");
    }

    #[test]
    fn uuid_strategies_have_their_version_nibble() {
        for (strategy, version) in [(IdStrategy::UuidV7, '7'), (IdStrategy::UuidV4, '4')] {
            let id = strategy.generate().unwrap();
            let id = id.as_str();
            assert_eq!(id.len(), 36, "{id}");
            assert_eq!(id.as_bytes()[14] as char, version, "{id}");
            assert!(
                matches!(id.as_bytes()[19], b'8' | b'9' | b'a' | b'b'),
                "{id}"
            );
            assert_eq!(strategy.storage(), IdStorage::Uuid);
        }
    }

    #[test]
    fn custom_ids_are_validated() {
        let ok = IdStrategy::custom(|| "x".repeat(IdStrategy::MAX_LEN));
        assert_eq!(ok.generate().unwrap().as_str().len(), 255);
        assert_eq!(ok.storage(), IdStorage::Text);

        for bad in [String::new(), "x".repeat(IdStrategy::MAX_LEN + 1)] {
            let strategy = IdStrategy::custom(move || bad.clone());
            let err = strategy.generate().unwrap_err();
            assert_eq!(err.status(), http::StatusCode::INTERNAL_SERVER_ERROR);
            assert_eq!(err.code(), crate::error::codes::INTERNAL);
        }
        assert_eq!(format!("{ok:?}"), "Custom(..)");
    }

    fn request(headers: &[(&str, &str)]) -> http::request::Parts {
        let mut builder = http::Request::builder();
        for (name, value) in headers {
            builder = builder.header(*name, *value);
        }
        builder.body(()).unwrap().into_parts().0
    }

    fn ip(source: &ClientIp, headers: &[(&str, &str)]) -> Option<String> {
        source.resolve(&request(headers)).map(|ip| ip.to_string())
    }

    #[test]
    fn client_ip_header_takes_exactly_one_address() {
        let source = ClientIp::Header("fly-client-ip".into());
        assert_eq!(
            ip(&source, &[("fly-client-ip", " 203.0.113.9 ")]).as_deref(),
            Some("203.0.113.9")
        );
        assert_eq!(
            ip(&source, &[("fly-client-ip", "2001:db8::1")]).as_deref(),
            Some("2001:db8::1")
        );
        assert_eq!(
            ip(&source, &[("fly-client-ip", "::ffff:203.0.113.9")]).as_deref(),
            Some("203.0.113.9")
        );
        assert_eq!(
            ip(&source, &[("fly-client-ip", "1.2.3.4, 203.0.113.9")]),
            None
        );
        assert_eq!(ip(&source, &[("fly-client-ip", "anything")]), None);
        assert_eq!(ip(&source, &[]), None);
    }

    #[test]
    fn client_ip_trusted_proxies_counts_from_the_right() {
        let one = ClientIp::TrustedProxies {
            header: "x-forwarded-for".into(),
            proxies: 1,
        };
        let two = ClientIp::TrustedProxies {
            header: "x-forwarded-for".into(),
            proxies: 2,
        };
        let spoofed = [("x-forwarded-for", "6.6.6.6, 203.0.113.9")];
        assert_eq!(ip(&one, &spoofed).as_deref(), Some("203.0.113.9"));
        assert_eq!(ip(&two, &spoofed).as_deref(), Some("6.6.6.6"));
        let chain = [
            ("x-forwarded-for", "6.6.6.6, 203.0.113.9"),
            ("x-forwarded-for", "10.0.0.2"),
        ];
        assert_eq!(ip(&two, &chain).as_deref(), Some("203.0.113.9"));
        assert_eq!(ip(&two, &[("x-forwarded-for", "203.0.113.9")]), None);
        assert_eq!(ip(&one, &[("x-forwarded-for", "1.2.3.4, junk")]), None);
        assert_eq!(ip(&one, &[]), None);
    }
}