allowthem-core 0.0.4

Core types, database, and auth logic for allowthem
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
use std::sync::Arc;

use chrono::Duration;
use sqlx::SqlitePool;

use crate::db::Db;
use crate::error::AuthError;
use crate::sessions::{self, SessionConfig};
use crate::types::{SessionToken, User};

/// Outcome of a successful login or session creation.
pub struct LoginOutcome {
    pub user: User,
    pub token: SessionToken,
    /// Value for the `Set-Cookie` response header.
    pub set_cookie: String,
}

/// Error type for builder construction and validation failures.
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
    /// Database connection or migration failure.
    #[error("database error: {0}")]
    Database(#[from] AuthError),

    /// Invalid builder configuration.
    /// Reserved for future validation; not currently produced.
    #[error("invalid configuration: {0}")]
    InvalidConfig(&'static str),
}

enum PoolSource {
    Url(String),
    Pool(SqlitePool),
}

/// Builder for constructing a configured [`AllowThem`] handle.
pub struct AllowThemBuilder {
    pool_source: PoolSource,
    session_ttl: Option<Duration>,
    cookie_name: Option<&'static str>,
    cookie_secure: Option<bool>,
    cookie_domain: String,
    mfa_key: Option<[u8; 32]>,
    signing_key: Option<[u8; 32]>,
    csrf_key: Option<[u8; 32]>,
    base_url: Option<String>,
}

impl AllowThemBuilder {
    /// Start building from a database URL.
    ///
    /// At build time, calls `Db::connect(url)` which creates the pool,
    /// sets pragmas (foreign_keys, WAL, busy_timeout), and runs migrations.
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            pool_source: PoolSource::Url(url.into()),
            session_ttl: None,
            cookie_name: None,
            cookie_secure: None,
            cookie_domain: String::new(),
            mfa_key: None,
            signing_key: None,
            csrf_key: None,
            base_url: None,
        }
    }

    /// Start building from an existing pool.
    ///
    /// At build time, calls `Db::new(pool)` which runs migrations.
    /// The caller is responsible for pragma configuration on their pool.
    pub fn with_pool(pool: SqlitePool) -> Self {
        Self {
            pool_source: PoolSource::Pool(pool),
            session_ttl: None,
            cookie_name: None,
            cookie_secure: None,
            cookie_domain: String::new(),
            mfa_key: None,
            signing_key: None,
            csrf_key: None,
            base_url: None,
        }
    }

    /// Override session TTL. Default: 24 hours.
    pub fn session_ttl(mut self, ttl: Duration) -> Self {
        self.session_ttl = Some(ttl);
        self
    }

    /// Override session cookie name. Default: `"allowthem_session"`.
    pub fn cookie_name(mut self, name: &'static str) -> Self {
        self.cookie_name = Some(name);
        self
    }

    /// Set the Secure attribute on session cookies.
    ///
    /// Default: `true`. Set to `false` for local development over HTTP.
    pub fn cookie_secure(mut self, secure: bool) -> Self {
        self.cookie_secure = Some(secure);
        self
    }

    /// Set the Domain attribute on session cookies.
    ///
    /// Default: empty (omitted). When set, the cookie is sent to the domain
    /// and all its subdomains.
    pub fn cookie_domain(mut self, domain: impl Into<String>) -> Self {
        self.cookie_domain = domain.into();
        self
    }

    /// Set the AES-256-GCM encryption key for MFA secrets.
    ///
    /// When not set, all MFA operations return `AuthError::MfaNotConfigured`.
    /// This keeps MFA opt-in for embedded integrators who don't need it.
    pub fn mfa_key(mut self, key: [u8; 32]) -> Self {
        self.mfa_key = Some(key);
        self
    }

    /// Set the AES-256-GCM encryption key for RS256 signing key storage.
    ///
    /// Required for OIDC/standalone mode. When not set, all signing key
    /// operations return `AuthError::SigningKeyNotConfigured`.
    pub fn signing_key(mut self, key: [u8; 32]) -> Self {
        self.signing_key = Some(key);
        self
    }

    /// Set the base URL (issuer) for the OIDC provider.
    ///
    /// Required for standalone mode. Used as the `iss` claim in tokens
    /// and for issuer validation on incoming access tokens.
    /// When not set, OIDC operations return `AuthError::BaseUrlNotConfigured`.
    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = Some(url.into());
        self
    }

    /// Set the HMAC key for session-bound CSRF token derivation.
    ///
    /// Required for `csrf_middleware` in `crates/server`. If not set,
    /// `csrf_middleware` returns 500. Use 32 random bytes distinct from
    /// `mfa_key` and `signing_key`.
    pub fn csrf_key(mut self, key: [u8; 32]) -> Self {
        self.csrf_key = Some(key);
        self
    }

    /// Construct the [`AllowThem`] handle.
    ///
    /// Connects to (or wraps) the database, runs migrations, and assembles
    /// the session configuration from overrides plus defaults.
    pub async fn build(self) -> Result<AllowThem, BuildError> {
        let db = match self.pool_source {
            PoolSource::Url(url) => Db::connect(&url).await?,
            PoolSource::Pool(pool) => Db::new(pool).await?,
        };

        let defaults = SessionConfig::default();
        let session_config = SessionConfig {
            ttl: self.session_ttl.unwrap_or(defaults.ttl),
            cookie_name: self.cookie_name.unwrap_or(defaults.cookie_name),
            secure: self.cookie_secure.unwrap_or(defaults.secure),
        };

        Ok(AllowThem {
            inner: Arc::new(Inner {
                db,
                session_config,
                cookie_domain: self.cookie_domain,
                mfa_key: self.mfa_key,
                signing_key: self.signing_key,
                csrf_key: self.csrf_key,
                base_url: self.base_url,
            }),
        })
    }
}

struct Inner {
    db: Db,
    session_config: SessionConfig,
    cookie_domain: String,
    mfa_key: Option<[u8; 32]>,
    signing_key: Option<[u8; 32]>,
    csrf_key: Option<[u8; 32]>,
    base_url: Option<String>,
}

/// Configured allowthem handle.
///
/// Bundles a `Db`, `SessionConfig`, and cookie domain into a single value
/// that is cheaply cloneable and safe to share across Axum handlers via
/// `State<AllowThem>` or `Extension<AllowThem>`.
#[derive(Clone)]
pub struct AllowThem {
    inner: Arc<Inner>,
}

impl AllowThem {
    /// Access the underlying database handle.
    ///
    /// Escape hatch for callers who need direct `Db` access for operations
    /// not yet wrapped by `AllowThem` methods (e.g., user CRUD, role management).
    pub fn db(&self) -> &Db {
        &self.inner.db
    }

    /// Access the session configuration.
    pub fn session_config(&self) -> &SessionConfig {
        &self.inner.session_config
    }

    /// Build a `Set-Cookie` header value for the given session token.
    ///
    /// Uses the stored `SessionConfig` and cookie domain. Delegates to
    /// `sessions::session_cookie()`.
    pub fn session_cookie(&self, token: &SessionToken) -> String {
        sessions::session_cookie(token, &self.inner.session_config, &self.inner.cookie_domain)
    }

    /// Returns the MFA encryption key, or `Err(MfaNotConfigured)` if not set.
    pub(crate) fn mfa_key(&self) -> Result<&[u8; 32], AuthError> {
        self.inner
            .mfa_key
            .as_ref()
            .ok_or(AuthError::MfaNotConfigured)
    }

    /// Returns the signing key encryption key, or `Err(SigningKeyNotConfigured)` if not set.
    pub(crate) fn signing_key(&self) -> Result<&[u8; 32], AuthError> {
        self.inner
            .signing_key
            .as_ref()
            .ok_or(AuthError::SigningKeyNotConfigured)
    }

    /// Returns the base URL (issuer), or `Err(BaseUrlNotConfigured)` if not set.
    pub fn base_url(&self) -> Result<&str, AuthError> {
        self.inner
            .base_url
            .as_deref()
            .ok_or(AuthError::BaseUrlNotConfigured)
    }

    pub fn csrf_key(&self) -> Result<&[u8; 32], AuthError> {
        self.inner
            .csrf_key
            .as_ref()
            .ok_or(AuthError::CsrfKeyNotConfigured)
    }

    /// Fetch the active signing key and decrypt its private key PEM.
    ///
    /// Combines the encryption key, active key lookup, and decryption into
    /// a single call. Keeps the raw encryption key private to the core crate.
    pub async fn get_decrypted_signing_key(
        &self,
    ) -> Result<(crate::signing_keys::SigningKey, String), AuthError> {
        let enc_key = self.signing_key()?;
        let key = self.db().get_active_signing_key().await?;
        let pem = crate::signing_keys::decrypt_private_key(&key, enc_key)?;
        Ok((key, pem))
    }

    /// Build a `Set-Cookie` header value that expires the session cookie.
    ///
    /// Returns `Max-Age=0` with the same cookie name, path, domain, and flags
    /// used by `session_cookie()`. Pass this as the `Set-Cookie` header on a
    /// logout response to clear the browser's stored session cookie.
    pub fn clear_session_cookie(&self) -> String {
        sessions::clear_session_cookie(&self.inner.session_config, &self.inner.cookie_domain)
    }

    /// Extract the session token from a `Cookie` header value.
    ///
    /// Uses the stored cookie name. Delegates to `sessions::parse_session_cookie()`.
    pub fn parse_session_cookie(&self, cookie_header: &str) -> Option<SessionToken> {
        sessions::parse_session_cookie(cookie_header, self.inner.session_config.cookie_name)
    }

    /// Authenticate with credentials and create a session.
    ///
    /// Returns `Err(AuthError::InvalidCredentials)` for any credential failure —
    /// unknown identifier, wrong password, no local password hash (SSO-only
    /// account), or inactive user — to prevent account enumeration.
    ///
    /// Records an `AuditEvent::Login` on success. IP and user-agent are not
    /// available at this layer; callers who need them in the audit log should
    /// use the low-level `Db` methods directly.
    pub async fn login(&self, identifier: &str, password: &str) -> Result<LoginOutcome, AuthError> {
        use chrono::Utc;

        use crate::audit::AuditEvent;
        use crate::password::verify_password;

        let user = self
            .db()
            .find_for_login(identifier)
            .await
            .map_err(|e| match e {
                AuthError::NotFound => AuthError::InvalidCredentials,
                other => other,
            })?;

        if !user.is_active {
            return Err(AuthError::InvalidCredentials);
        }

        let hash = user
            .password_hash
            .as_ref()
            .ok_or(AuthError::InvalidCredentials)?;

        if !verify_password(password, hash)? {
            return Err(AuthError::InvalidCredentials);
        }

        let token = sessions::generate_token();
        let token_hash = sessions::hash_token(&token);
        let expires_at = Utc::now() + self.inner.session_config.ttl;
        self.db()
            .create_session(user.id, token_hash, None, None, expires_at)
            .await?;

        let _ = self
            .db()
            .log_audit(AuditEvent::Login, Some(&user.id), None, None, None, None)
            .await;

        let set_cookie = self.session_cookie(&token);
        Ok(LoginOutcome {
            user,
            token,
            set_cookie,
        })
    }

    /// Create a session for an already-authenticated user.
    ///
    /// Does not verify credentials. Intended for use after OAuth, TOTP, or
    /// other non-password authentication flows. The calling flow is responsible
    /// for audit logging.
    pub async fn create_session_cookie(
        &self,
        user_id: crate::types::UserId,
    ) -> Result<LoginOutcome, AuthError> {
        use chrono::Utc;

        let user = self.db().get_user(user_id).await?;
        let token = sessions::generate_token();
        let token_hash = sessions::hash_token(&token);
        let expires_at = Utc::now() + self.inner.session_config.ttl;
        self.db()
            .create_session(user_id, token_hash, None, None, expires_at)
            .await?;

        let set_cookie = self.session_cookie(&token);
        Ok(LoginOutcome {
            user,
            token,
            set_cookie,
        })
    }
}

#[cfg(test)]
mod tests {
    use sqlx::sqlite::SqliteConnectOptions;
    use std::str::FromStr;

    use super::*;
    use crate::sessions::generate_token;
    use crate::types::Email;

    #[tokio::test]
    async fn build_with_url_defaults() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let config = ath.session_config();
        assert_eq!(config.ttl, Duration::hours(24));
        assert_eq!(config.cookie_name, "allowthem_session");
        assert!(config.secure);

        let token = generate_token();
        let cookie = ath.session_cookie(&token);
        assert!(!cookie.contains("; Domain="));
    }

    #[tokio::test]
    async fn build_with_pool() {
        let opts = SqliteConnectOptions::from_str("sqlite::memory:")
            .unwrap()
            .pragma("foreign_keys", "ON");
        let pool = sqlx::SqlitePool::connect_with(opts).await.unwrap();

        let ath = AllowThemBuilder::with_pool(pool).build().await.unwrap();

        let email = Email::new("test@example.com".into()).unwrap();
        let user = ath.db().create_user(email, "password123", None, None).await;
        assert!(user.is_ok());
    }

    #[tokio::test]
    async fn build_with_overrides() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .session_ttl(Duration::hours(48))
            .cookie_name("my_session")
            .cookie_secure(false)
            .cookie_domain("example.com")
            .build()
            .await
            .unwrap();

        let config = ath.session_config();
        assert_eq!(config.ttl, Duration::hours(48));
        assert_eq!(config.cookie_name, "my_session");
        assert!(!config.secure);
    }

    #[tokio::test]
    async fn session_cookie_uses_config() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("custom")
            .cookie_secure(false)
            .cookie_domain("example.com")
            .build()
            .await
            .unwrap();

        let token = generate_token();
        let cookie = ath.session_cookie(&token);

        assert!(cookie.contains("custom="));
        assert!(cookie.contains("; Domain=example.com"));
        assert!(!cookie.contains("; Secure"));
    }

    #[tokio::test]
    async fn clear_session_cookie_defaults() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let cookie = ath.clear_session_cookie();
        assert!(cookie.starts_with("allowthem_session=;"));
        assert!(cookie.contains("; Max-Age=0"));
        assert!(!cookie.contains("; Domain="));
        assert!(cookie.contains("; Secure"));
    }

    #[tokio::test]
    async fn clear_session_cookie_name_matches_session_cookie() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("app_session")
            .build()
            .await
            .unwrap();

        let token = generate_token();
        let set = ath.session_cookie(&token);
        let clear = ath.clear_session_cookie();

        // Both must share the same cookie name prefix so the browser matches them.
        assert!(set.starts_with("app_session="));
        assert!(clear.starts_with("app_session=;"));
        assert!(clear.contains("; Path=/"));
        assert!(clear.contains("; Max-Age=0"));
    }

    #[tokio::test]
    async fn clear_session_cookie_with_domain_and_no_secure() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("my_session")
            .cookie_secure(false)
            .cookie_domain("example.com")
            .build()
            .await
            .unwrap();

        let cookie = ath.clear_session_cookie();
        assert!(cookie.starts_with("my_session=;"));
        assert!(cookie.contains("; Max-Age=0"));
        assert!(cookie.contains("; Domain=example.com"));
        assert!(!cookie.contains("; Secure"));
    }

    #[tokio::test]
    async fn parse_session_cookie_uses_config() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_name("custom")
            .build()
            .await
            .unwrap();

        let header = "custom=abc123; other=xyz";
        let result = ath.parse_session_cookie(header);

        assert!(result.is_some());
        assert_eq!(result.unwrap().as_str(), "abc123");
    }

    #[tokio::test]
    async fn build_with_bad_url_fails() {
        let result = AllowThemBuilder::new("not-a-url").build().await;

        assert!(result.is_err());
        assert!(matches!(result.err().unwrap(), BuildError::Database(_)));
    }

    #[tokio::test]
    async fn clone_shares_state() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();
        let ath2 = ath.clone();

        let email = Email::new("shared@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "password123", None, None)
            .await
            .unwrap();

        let found = ath2.db().get_user(user.id).await;
        assert!(found.is_ok());
        assert_eq!(found.unwrap().id, user.id);
    }

    #[tokio::test]
    async fn signing_key_not_configured_returns_error() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();
        let result = ath.signing_key();
        assert!(matches!(
            result,
            Err(crate::error::AuthError::SigningKeyNotConfigured)
        ));
    }

    #[tokio::test]
    async fn base_url_not_configured_returns_error() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();
        let result = ath.base_url();
        assert!(matches!(
            result,
            Err(crate::error::AuthError::BaseUrlNotConfigured)
        ));
    }

    #[tokio::test]
    async fn base_url_configured_returns_value() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .base_url("https://auth.example.com")
            .build()
            .await
            .unwrap();
        let result = ath.base_url();
        assert!(matches!(result, Ok("https://auth.example.com")));
    }

    #[tokio::test]
    async fn login_success() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .build()
            .await
            .unwrap();

        let email = Email::new("login@example.com".into()).unwrap();
        ath.db()
            .create_user(email, "secret", None, None)
            .await
            .unwrap();

        let outcome = ath.login("login@example.com", "secret").await.unwrap();
        assert_eq!(outcome.user.email.as_str(), "login@example.com");
        assert!(!outcome.token.as_str().is_empty());
        assert!(outcome.set_cookie.contains("allowthem_session="));
    }

    #[tokio::test]
    async fn login_wrong_password() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let email = Email::new("wp@example.com".into()).unwrap();
        ath.db()
            .create_user(email, "correct", None, None)
            .await
            .unwrap();

        let result = ath.login("wp@example.com", "wrong").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn login_unknown_identifier() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let result = ath.login("nobody@example.com", "any").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn login_inactive_user() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let email = Email::new("inactive@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "secret", None, None)
            .await
            .unwrap();
        ath.db().update_user_active(user.id, false).await.unwrap();

        let result = ath.login("inactive@example.com", "secret").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn login_no_password_hash() {
        use crate::types::UserId;

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        // Insert a user directly with password_hash = NULL (SSO-only account).
        // UserId uses UUID v7; bind it properly so SQLx can round-trip it.
        let id = UserId::new();
        let now = chrono::Utc::now()
            .format("%Y-%m-%dT%H:%M:%S%.3fZ")
            .to_string();
        sqlx::query(
            "INSERT INTO allowthem_users \
             (id, email, username, password_hash, email_verified, is_active, created_at, updated_at) \
             VALUES (?, 'sso@example.com', NULL, NULL, 1, 1, ?, ?)",
        )
        .bind(id)
        .bind(&now)
        .bind(&now)
        .execute(ath.db().pool())
        .await
        .unwrap();

        let result = ath.login("sso@example.com", "any").await;
        assert!(matches!(result, Err(AuthError::InvalidCredentials)));
    }

    #[tokio::test]
    async fn create_session_cookie_success() {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .build()
            .await
            .unwrap();

        let email = Email::new("sess@example.com".into()).unwrap();
        let user = ath
            .db()
            .create_user(email, "secret", None, None)
            .await
            .unwrap();

        let outcome = ath.create_session_cookie(user.id).await.unwrap();
        assert_eq!(outcome.user.id, user.id);
        assert!(!outcome.token.as_str().is_empty());
        assert!(outcome.set_cookie.contains("allowthem_session="));

        // Session must exist in DB
        let session = ath.db().lookup_session(&outcome.token).await.unwrap();
        assert!(session.is_some());
    }

    #[tokio::test]
    async fn create_session_cookie_unknown_user() {
        use crate::types::UserId;

        let ath = AllowThemBuilder::new("sqlite::memory:")
            .build()
            .await
            .unwrap();

        let result = ath.create_session_cookie(UserId::new()).await;
        assert!(matches!(result, Err(AuthError::NotFound)));
    }
}