tablo-core 0.2.0

The core toolkit types for Tablo, a server-rendered admin toolkit on Topcoat and Toasty.
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
764
765
766
767
768
769
use std::sync::Arc;

use jiff::Timestamp;
use toasty::Db;
use topcoat::{
    context::Cx,
    router::{Body, response::IntoResponse},
};

use super::{
    login::GENERIC_ERROR,
    session::{SESSION_SWEEP_BATCH, sweep_expired_sessions, token_key},
    *,
};
use crate::{
    Panel,
    panel::{state::PanelState, test_support::mount},
};

#[test]
fn safe_next_only_accepts_same_origin_relative_paths() {
    assert_eq!(safe_next("/admin/users"), Some("/admin/users"));
    assert_eq!(
        safe_next("/admin/posts?status=draft"),
        Some("/admin/posts?status=draft")
    );
    assert_eq!(safe_next("  /admin  "), Some("/admin"));
    for target in [
        "",
        "admin",
        "//evil.example/login",
        "https://evil.example/steal",
        "/\\evil.example",
        "/admin\r\nLocation: https://evil.example",
    ] {
        assert_eq!(safe_next(target), None, "must reject {target:?}");
    }
}

#[test]
fn password_hashes_verify_round_trip() {
    let phc = hash_password("correct horse battery staple").expect("hash");
    assert!(phc.starts_with("$argon2id$"), "{phc}");
    assert!(verify_password("correct horse battery staple", Some(&phc)));
    assert!(!verify_password("wrong", Some(&phc)));
    assert!(!verify_password("anything", Some("not-a-phc")));
    // An unknown account pays a verification and never passes.
    assert!(!verify_password("anything", None));
}

#[test]
fn token_keys_are_hex_encoded_sha256() {
    let token = topcoat::session::Token::random();
    let key = token_key(&token.hash());
    assert_eq!(key.len(), 64);
    assert!(key.chars().all(|c| c.is_ascii_hexdigit()));
}

/// Declares the shipped auth models without pushing their schema, so the first
/// statement fails at the driver.
async fn schema_less_db() -> Db {
    Db::builder()
        .models(toasty::models!(AdminUser, AuthSession))
        .connect("sqlite::memory:")
        .await
        .expect("connect to in-memory sqlite")
}

/// Maps a driver failure to the opaque sign-in copy, never the driver's text or
/// the credential rejection.
#[test]
fn infrastructure_failure_maps_driver_errors_to_the_opaque_sign_in_copy() {
    let err = super::infrastructure_failure(toasty::Error::from_args(format_args!(
        "secret driver gunk: no such table"
    )));
    let rendered = err.to_string();
    assert!(
        rendered.contains(UNAVAILABLE_ERROR),
        "the opaque message must survive, got {rendered}"
    );
    assert!(
        !rendered.contains("gunk"),
        "driver text must not leak, got {rendered}"
    );
    assert!(
        !rendered.contains(GENERIC_ERROR),
        "an outage must not read as a rejected password, got {rendered}"
    );
}

/// A custom `Authenticator`'s own failure keeps its mapping.
#[test]
fn infrastructure_failure_keeps_an_app_error_intact() {
    let guard: topcoat::Error = topcoat::router::error::not_found().into();
    assert!(
        super::infrastructure_failure(guard).is::<topcoat::router::error::NotFoundError>(),
        "an app-authored error must keep its own mapping"
    );
}

/// Builds the `Cx` for a login POST over the password authenticator.
fn login_cx(db: Db, token: &str) -> Cx {
    use topcoat::{context::CxTestBuilder, cookie::CookieJarCell};

    let parts = http::Request::builder()
        .method(http::Method::POST)
        .uri("/admin/login")
        .header(
            http::header::CONTENT_TYPE,
            "application/x-www-form-urlencoded",
        )
        .header(
            http::header::COOKIE,
            format!("{}={token}", crate::csrf::COOKIE_NAME),
        )
        .body(())
        .unwrap()
        .into_parts()
        .0;
    CxTestBuilder::new()
        .app_context(db)
        .request_context(crate::panel::test_support::current_panel(
            crate::panel::test_support::panel_state("/admin", Auth::password()),
        ))
        .request_context(parts)
        .request_context(CookieJarCell::new())
        .build()
}

/// Runs the login handler and renders the status and body a browser receives.
async fn post_login(cx: &Cx, form: String) -> (http::StatusCode, String) {
    let response = login_post(cx, Body::from(form))
        .await
        .expect("a failed sign-in is answered by the login page");
    let status = response.status();
    let body = String::from_utf8_lossy(
        &http_body_util::BodyExt::collect(response.into_body())
            .await
            .unwrap()
            .to_bytes(),
    )
    .to_string();
    (status, body)
}

/// A driver failure during verification answers the outage copy with no driver
/// text and no credential copy.
#[tokio::test]
async fn a_driver_login_failure_does_not_echo_driver_text() {
    // The credential query fails at the driver without a pushed schema.
    let db = schema_less_db().await;

    // The same query outside the handler carries driver text.
    let mut raw = db.clone();
    let driver = AdminUser::filter(
        AdminUser::fields()
            .email()
            .eq("ada@example.com".to_string()),
    )
    .first()
    .exec(&mut raw)
    .await
    .expect_err("the table is missing")
    .to_string();
    drop(raw);
    assert!(
        driver.contains("no such table"),
        "the control must be a driver failure, got {driver:?}"
    );

    let token = Uuid::new_v4().to_string();
    let cx = login_cx(db, &token);
    let (status, rendered) = post_login(
        &cx,
        format!("email=ada@example.com&password=opensesame&csrf_token={token}"),
    )
    .await;

    assert_eq!(
        status,
        http::StatusCode::SERVICE_UNAVAILABLE,
        "an outage is not a credential rejection"
    );
    assert!(
        rendered.contains(UNAVAILABLE_ERROR),
        "the opaque outage copy must reach the page, got {rendered:?}"
    );
    assert!(
        !rendered.contains(&driver) && !rendered.contains("no such table"),
        "driver text must not reach the response: the driver said {driver:?}, the response said {rendered:?}"
    );
    assert!(
        !rendered.contains(GENERIC_ERROR),
        "an outage must not read as a rejected password, got {rendered:?}"
    );
}

/// A wrong password keeps the generic 403, never the outage copy.
#[tokio::test]
async fn a_rejected_password_still_renders_the_generic_error() {
    let mut db = schema_less_db().await;
    db.push_schema().await.expect("push schema");
    toasty::create!(AdminUser {
        email: "ada@example.com".to_string(),
        password_hash: hash_password("opensesame").expect("hash"),
        display_name: "Ada".to_string(),
        active: true,
        created_at: Timestamp::now(),
    })
    .exec(&mut db)
    .await
    .expect("seed admin");

    let token = Uuid::new_v4().to_string();
    let cx = login_cx(db, &token);
    let (status, rendered) = post_login(
        &cx,
        format!("email=ada@example.com&password=wrong&csrf_token={token}"),
    )
    .await;

    assert_eq!(
        status,
        http::StatusCode::FORBIDDEN,
        "a rejection is not an outage"
    );
    assert!(
        rendered.contains(GENERIC_ERROR),
        "the credential copy must survive, got {rendered:?}"
    );
    assert!(
        !rendered.contains(UNAVAILABLE_ERROR),
        "a rejected password must not read as an outage, got {rendered:?}"
    );
}

/// Builds a router for a password-auth panel over `db`.
fn auth_router(db: Db) -> topcoat::router::Router {
    mount(db, Panel::new("admin").auth(Auth::password())).expect("panel builds")
}

/// Builds a login POST carrying the CSRF cookie the double-submit check reads.
fn login_request(body: String, csrf: &str) -> http::Request<Body> {
    http::Request::builder()
        .method(http::Method::POST)
        .uri("/admin/login")
        .header(
            http::header::CONTENT_TYPE,
            "application/x-www-form-urlencoded",
        )
        .header(
            http::header::COOKIE,
            format!("{}={csrf}", crate::csrf::COOKIE_NAME),
        )
        .body(Body::from(body))
        .unwrap()
}

/// Reads the session token's `Set-Cookie` header, when the response set one.
fn session_cookie(response: &http::Response<Body>) -> Option<String> {
    response
        .headers()
        .get_all(http::header::SET_COOKIE)
        .iter()
        .filter_map(|value| value.to_str().ok())
        .find(|value| value.starts_with("__Host-session="))
        .map(str::to_string)
}

/// Builds a `Db` with pushed schema and one active admin.
async fn db_with_admin(email: &str) -> Db {
    let mut db = Db::builder()
        .models(toasty::models!(AdminUser, AuthSession))
        .connect("sqlite::memory:")
        .await
        .expect("connect to in-memory sqlite");
    db.push_schema().await.expect("push schema");
    toasty::create!(AdminUser {
        email: email.to_string(),
        password_hash: hash_password("opensesame").expect("hash"),
        display_name: "Ada".to_string(),
        active: true,
        created_at: Timestamp::now(),
    })
    .exec(&mut db)
    .await
    .expect("seed admin");
    db
}

/// A login body over the credential cap answers 413 and starts no session.
#[tokio::test]
async fn an_oversized_login_post_is_refused() {
    let db = db_with_admin("ada@example.com").await;
    let router = auth_router(db);

    let token = Uuid::new_v4().to_string();
    let oversized = format!(
        "email={}&password=opensesame&csrf_token={token}",
        "a".repeat(MAX_LOGIN_BYTES)
    );
    let resp = router.handle(login_request(oversized, &token)).await;
    assert_eq!(
        resp.status(),
        http::StatusCode::PAYLOAD_TOO_LARGE,
        "a login body over the credential cap must be refused, got {}",
        resp.status()
    );
    assert!(
        session_cookie(&resp).is_none(),
        "a refused login must not start a session"
    );

    // A normal credential POST still signs in.
    let token = Uuid::new_v4().to_string();
    let resp = router
        .handle(login_request(
            format!("email=ada@example.com&password=opensesame&csrf_token={token}"),
            &token,
        ))
        .await;
    assert_eq!(
        resp.status(),
        http::StatusCode::SEE_OTHER,
        "a normal credential POST must sign in, got {}",
        resp.status()
    );
    assert!(
        session_cookie(&resp).is_some(),
        "a successful login starts a session"
    );
}

/// Login sweeps every expired session row, whoever owns it.
#[tokio::test]
async fn login_sweeps_every_expired_session() {
    let mut db = db_with_admin("ada@example.com").await;
    let other = toasty::create!(AdminUser {
        email: "grace@example.com".to_string(),
        password_hash: hash_password("opensesame").expect("hash"),
        display_name: "Grace".to_string(),
        active: true,
        created_at: Timestamp::now(),
    })
    .exec(&mut db)
    .await
    .expect("seed the other admin");
    let ada = AdminUser::filter(
        AdminUser::fields()
            .email()
            .eq("ada@example.com".to_string()),
    )
    .first()
    .exec(&mut db)
    .await
    .expect("look up ada")
    .expect("ada exists");
    let expired = "2000-01-01T00:00:00Z"
        .parse::<Timestamp>()
        .expect("a past timestamp");
    let live = "2100-01-01T00:00:00Z"
        .parse::<Timestamp>()
        .expect("a future timestamp");
    for (token_hash, user_id, expires_at) in [
        ("expired-mine", ada.id.to_string(), expired),
        ("live-mine", ada.id.to_string(), live),
        ("expired-other", other.id.to_string(), expired),
    ] {
        toasty::create!(AuthSession {
            token_hash: token_hash.to_string(),
            user_id,
            panel: "/admin".to_string(),
            expires_at,
            created_at: Timestamp::now(),
        })
        .exec(&mut db)
        .await
        .expect("seed a session row");
    }

    let router = auth_router(db.clone());
    let token = Uuid::new_v4().to_string();
    let resp = router
        .handle(login_request(
            format!("email=ada@example.com&password=opensesame&csrf_token={token}"),
            &token,
        ))
        .await;
    assert_eq!(
        resp.status(),
        http::StatusCode::SEE_OTHER,
        "the login must succeed"
    );

    let mut check = db.clone();
    assert!(
        AuthSession::filter(
            AuthSession::fields()
                .token_hash()
                .eq("expired-mine".to_string())
        )
        .first()
        .exec(&mut check)
        .await
        .expect("query")
        .is_none(),
        "the signing-in user's expired session must be purged"
    );
    let mut check = db.clone();
    assert!(
        AuthSession::filter(
            AuthSession::fields()
                .token_hash()
                .eq("live-mine".to_string())
        )
        .first()
        .exec(&mut check)
        .await
        .expect("query")
        .is_some(),
        "a live session of the same user survives the purge"
    );
    let mut check = db.clone();
    assert!(
        AuthSession::filter(
            AuthSession::fields()
                .token_hash()
                .eq("expired-other".to_string())
        )
        .first()
        .exec(&mut check)
        .await
        .expect("query")
        .is_none(),
        "the sweep does not wait for the expired row's owner to sign in"
    );
}

/// One login sweeps at most [`SESSION_SWEEP_BATCH`] rows.
#[tokio::test]
async fn login_sweeps_at_most_a_batch() {
    let mut db = db_with_admin("ada@example.com").await;
    let ada = AdminUser::filter(
        AdminUser::fields()
            .email()
            .eq("ada@example.com".to_string()),
    )
    .first()
    .exec(&mut db)
    .await
    .expect("look up ada")
    .expect("ada exists");
    let expired = "2000-01-01T00:00:00Z"
        .parse::<Timestamp>()
        .expect("a past timestamp");
    let mut seed = AuthSession::create_many();
    for index in 0..=SESSION_SWEEP_BATCH {
        seed = seed.item(
            AuthSession::create()
                .token_hash(format!("expired-{index}"))
                .user_id(ada.id.to_string())
                .panel("/admin")
                .expires_at(expired)
                .created_at(Timestamp::now()),
        );
    }
    seed.exec(&mut db).await.expect("seed the expired rows");

    let router = auth_router(db.clone());
    let token = Uuid::new_v4().to_string();
    let resp = router
        .handle(login_request(
            format!("email=ada@example.com&password=opensesame&csrf_token={token}"),
            &token,
        ))
        .await;
    assert_eq!(
        resp.status(),
        http::StatusCode::SEE_OTHER,
        "the login must succeed"
    );

    let mut check = db.clone();
    let remaining = AuthSession::all()
        .exec(&mut check)
        .await
        .expect("query")
        .len();
    assert_eq!(
        remaining, 2,
        "one expired row past the batch, plus the session this login created"
    );
}

/// A sweep failure answers the opaque sign-in copy with no driver text.
#[tokio::test]
async fn a_sweep_failure_maps_to_the_opaque_sign_in_copy() {
    let cx = login_cx(schema_less_db().await, "token");
    let error = sweep_expired_sessions(&cx)
        .await
        .expect_err("a schema-less database fails the sweep");
    let rendered = error.to_string();
    assert!(
        rendered.contains(UNAVAILABLE_ERROR),
        "the opaque message must survive, got {rendered}"
    );
    assert!(
        !rendered.contains("no such table"),
        "driver text must not leak, got {rendered}"
    );
}

/// A failed session delete answers the opaque copy with no driver text.
#[tokio::test]
async fn a_driver_session_delete_failure_does_not_echo_driver_text() {
    use topcoat::context::CxTestBuilder;

    let db = schema_less_db().await;

    // The same delete outside the handler carries driver text.
    let mut raw = db.clone();
    let driver = AuthSession::filter(AuthSession::fields().user_id().eq("ada".to_string()))
        .delete()
        .exec(&mut raw)
        .await
        .expect_err("the table is missing")
        .to_string();
    drop(raw);
    assert!(
        driver.contains("no such table"),
        "the control must be a driver failure, got {driver:?}"
    );

    let cx = CxTestBuilder::new().app_context(db).build();
    let error = revoke_sessions_for_user(&cx, "ada")
        .await
        .expect_err("the delete must fail");

    let rendered = error.to_string();
    assert!(
        rendered.contains(UNAVAILABLE_ERROR),
        "the opaque message must survive, got {rendered:?}"
    );
    assert!(
        !rendered.contains(&driver) && !rendered.contains("no such table"),
        "driver text must not reach the response: the driver said {driver:?}, the response said {rendered:?}"
    );
}

/// An app route at the login path under a method the login routes do not serve.
#[topcoat::router::route(PUT "/admin/login")]
async fn app_put_at_the_login_path() -> topcoat::Result<&'static str> {
    Ok("app route ran")
}

/// Admits only the login methods at the login path: a logged-out PUT stops at
/// the gate.
#[tokio::test]
async fn the_login_bypass_is_scoped_to_the_login_methods() {
    let db = db_with_admin("ada@example.com").await;
    let router = auth_router(db);

    let put = router
        .handle(
            http::Request::builder()
                .method(http::Method::PUT)
                .uri("/admin/login")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(
        put.status(),
        http::StatusCode::UNAUTHORIZED,
        "a logged-out PUT at the login path must stop at the gate"
    );

    let get = router
        .handle(
            http::Request::builder()
                .uri("/admin/login")
                .body(Body::empty())
                .unwrap(),
        )
        .await;
    assert_eq!(
        get.status(),
        http::StatusCode::OK,
        "the login page must still answer while logged out"
    );
}

/// A user type other than the panel's.
struct Visitor;

impl PanelUser for Visitor {
    fn user_id(&self) -> String {
        "visitor".to_string()
    }

    fn display_name(&self) -> &str {
        "Visitor"
    }
}

fn ada() -> AdminUser {
    AdminUser {
        id: Uuid::nil(),
        email: "ada@example.com".to_string(),
        password_hash: String::new(),
        display_name: "Ada".to_string(),
        active: true,
        created_at: Timestamp::UNIX_EPOCH,
    }
}

/// A request on `/admin` with `user` signed in to `panel`, served by `serving`.
fn signed_cx(user: impl PanelUser, panel: &Arc<PanelState>, serving: &Arc<PanelState>) -> Cx {
    let (parts, ()) = http::Request::builder()
        .uri("/admin/users")
        .body(())
        .unwrap()
        .into_parts();
    topcoat::context::CxTestBuilder::new()
        .request_context(parts)
        .request_context(crate::panel::state::CurrentPanel(Arc::clone(serving)))
        .request_context(SignedIn {
            user: Arc::new(user),
            panel: Arc::clone(panel),
            tenant: None,
        })
        .build()
}

#[test]
fn the_user_reads_back_as_the_apps_own_type_only() {
    let panel = Arc::new(crate::panel::test_support::panel_state(
        "/admin",
        Auth::password(),
    ));
    let cx = signed_cx(ada(), &panel, &panel);
    assert_eq!(
        user::<AdminUser>(&cx).map(|u| u.email.as_str()),
        Some("ada@example.com")
    );
    assert!(signed_in(&cx));
    assert!(
        user::<Visitor>(&cx).is_none(),
        "another type reads as nobody"
    );
    let refused = require_user::<Visitor>(&cx)
        .err()
        .expect("wrong type refused");
    assert_eq!(refused.into_response(&cx).unwrap().status(), 403);
}

#[test]
fn a_user_is_nobody_on_another_panel() {
    let admin = Arc::new(crate::panel::test_support::panel_state(
        "/admin",
        Auth::password(),
    ));
    let staff = Arc::new(crate::panel::test_support::panel_state(
        "/staff",
        Auth::password(),
    ));
    let cx = signed_cx(ada(), &admin, &staff);
    assert!(user::<AdminUser>(&cx).is_none());
    assert!(!signed_in(&cx));
}

#[test]
fn an_inactive_user_is_not_signed_in() {
    let panel = Arc::new(crate::panel::test_support::panel_state(
        "/admin",
        Auth::password(),
    ));
    let cx = signed_cx(
        AdminUser {
            active: false,
            ..ada()
        },
        &panel,
        &panel,
    );
    assert!(user::<AdminUser>(&cx).is_none());
    assert!(
        resolved(&cx).is_some(),
        "the logout route still reads the user"
    );
}

/// A user holding the memberships it carries.
struct Member(Vec<Membership>);

impl PanelUser for Member {
    fn user_id(&self) -> String {
        "member".to_string()
    }

    fn display_name(&self) -> &str {
        "Member"
    }

    fn tenants(&self) -> &[Membership] {
        &self.0
    }
}

/// A request on `/admin` signed in as a member of `tenants`, whose session
/// selected `selected`, with an optional `Tenant` override on the `Cx`.
fn member_cx(
    tenants: &[uuid::Uuid],
    selected: Option<uuid::Uuid>,
    overridden: Option<uuid::Uuid>,
) -> Cx {
    let panel = std::sync::Arc::new(crate::panel::test_support::panel_state(
        "/admin",
        crate::Auth::password(),
    ));
    let memberships = tenants
        .iter()
        .enumerate()
        .map(|(index, tenant)| Membership::new(*tenant, format!("Tenant {index}")))
        .collect();
    let mut builder = topcoat::context::CxTestBuilder::new()
        .request_context(crate::panel::state::CurrentPanel(std::sync::Arc::clone(
            &panel,
        )))
        .request_context(SignedIn {
            user: std::sync::Arc::new(Member(memberships)),
            panel,
            tenant: selected,
        })
        .app_context(crate::tenancy::TenantSource(session_tenant));
    if let Some(tenant) = overridden {
        builder = builder.request_context(crate::Tenant(tenant));
    }
    builder.build()
}

#[test]
fn the_request_acts_for_the_selected_membership_else_the_first() {
    let (a, b, stranger) = (
        uuid::Uuid::from_u128(1),
        uuid::Uuid::from_u128(2),
        uuid::Uuid::from_u128(3),
    );
    assert_eq!(crate::tenant_id(&member_cx(&[a, b], None, None)), Some(a));
    assert_eq!(
        crate::tenant_id(&member_cx(&[a, b], Some(b), None)),
        Some(b)
    );
    let cx = member_cx(&[a, b], Some(b), None);
    assert_eq!(membership(&cx).map(|m| m.name.as_str()), Some("Tenant 1"));
    // A selection the user is no longer a member of falls back to the first.
    assert_eq!(
        crate::tenant_id(&member_cx(&[a, b], Some(stranger), None)),
        Some(a)
    );
    // No membership, no tenant.
    assert_eq!(crate::tenant_id(&member_cx(&[], Some(a), None)), None);
    // An override wins, and names no membership unless the user holds it.
    let cx = member_cx(&[a, b], None, Some(stranger));
    assert_eq!(crate::tenant_id(&cx), Some(stranger));
    assert_eq!(membership(&cx), None);
    let cx = member_cx(&[a, b], None, Some(b));
    assert_eq!(membership(&cx).map(|m| m.tenant), Some(b));
}