rustango 0.62.0

Batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
//! Bare-admin SSO login wiring, behind the `admin-sso` feature.
//!
//! The reusable SSO core (types, `build_provider`, `verified_email`,
//! `SSO_FLOW_COOKIE`) lives in [`crate::sso`]. This module only wires
//! it to the bare admin: it builds a
//! [`ResolvedSso`](crate::sso::ResolvedSso) from an
//! [`SsoProvider`](crate::sso::SsoProvider) row, runs the handshake,
//! signs in the [`AdminUser`] linked to the IdP subject, and mints the
//! admin session cookie.
//!
//! SSO never creates an admin account or links one by email: an admin
//! adds the [`SsoLink`](crate::sso::SsoLink) row. The refusal log names the subject.
//!
//! The re-export below keeps the older `crate::admin::sso::…` paths
//! working for callers such as [`crate::tenancy::sso`].

pub use crate::sso::*;

use axum::{
    extract::{Path, Query, State},
    http::{header, HeaderMap, HeaderValue},
    response::{IntoResponse, Redirect, Response},
    routing::get,
    Router,
};

use super::session::{self, AdminSession, SESSION_COOKIE};
use super::urls::AppState;
use super::user::AdminUser;
use crate::signals::auth::{
    meta_from_parts, send_user_logged_in, AuthFailureReason, AuthRequestMeta, UserLoggedInContext,
};
use crate::sso::link::{signal_refused, Account, AccountLookup, EmailLookup};

/// The auth-signal `source` for a bare-admin SSO sign-in.
const SIGNAL_SOURCE: &str = "admin_sso";

/// Query params on the IdP callback (`?code=…&state=…` or `?error=…`).
#[derive(serde::Deserialize)]
struct CallbackParams {
    code: Option<String>,
    state: Option<String>,
    error: Option<String>,
}

/// Routes for the bare-admin SSO flow, mounted next to `/login`.
/// `GET /login/sso/{slug}` starts the handshake for one configured
/// [`SsoProvider`](super::sso_provider::SsoProvider), and
/// `.../callback` completes it.
pub(crate) fn sso_router(state: AppState) -> Router {
    let router = Router::new()
        .route("/login/sso/{slug}", get(sso_begin))
        .route("/login/sso/{slug}/callback", get(sso_callback));
    // Outside `/login/sso/`, so no provider slug is shadowed.
    #[cfg(feature = "totp")]
    let router = router.route(
        "/login/sso-totp",
        axum::routing::post(second_factor::submit),
    );
    router.with_state(state)
}

fn login_path(state: &AppState) -> String {
    let p = &state.config.admin_prefix;
    if p.is_empty() {
        "/login".to_owned()
    } else {
        format!("{p}/login")
    }
}

/// Per-provider callback URL built from the request host:
/// `{scheme}://{host}{login_path}/sso/{slug}/callback`. The scheme
/// comes from `X-Forwarded-Proto` sent by a trusted proxy, else `https`.
/// `None` for a host the admin's allowed hosts do not list.
fn derive_bare_redirect(
    headers: &HeaderMap,
    extensions: &axum::http::Extensions,
    state: &AppState,
    slug: &str,
) -> Option<String> {
    redirect_for(
        headers,
        extensions,
        &login_path(state),
        state.config.allowed_hosts.as_ref(),
        slug,
    )
}

fn redirect_for(
    headers: &HeaderMap,
    extensions: &axum::http::Extensions,
    login_path: &str,
    allowed: Option<&crate::host_validation::AllowedHostsLayer>,
    slug: &str,
) -> Option<String> {
    let host = crate::urls::HostAuthority::parse(headers.get(header::HOST)?.to_str().ok()?)?;
    if allowed.is_some_and(|a| !a.permits(&host.to_string())) {
        tracing::warn!(target: "rustango::admin::sso", %host, "SSO refused: the Host is not an allowed host");
        return None;
    }
    let scheme = crate::real_ip::trusted_forwarded(headers, extensions, "x-forwarded-proto")
        .unwrap_or("https");
    Some(format!("{scheme}://{host}{login_path}/sso/{slug}/callback"))
}

/// Redirect back to the login page with a generic `?sso_error=` marker.
/// Details are logged, never shown to the user.
fn login_error(state: &AppState, code: &str) -> Response {
    Redirect::to(&format!("{}?sso_error={code}", login_path(state))).into_response()
}

fn cookie_attrs(secure: bool) -> &'static str {
    if secure {
        "; Secure"
    } else {
        ""
    }
}

// GET /login/sso/{slug}: start the handshake for one provider.
async fn sso_begin(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    headers: HeaderMap,
    extensions: axum::http::Extensions,
) -> Response {
    let Some(secret) = state.config.session_secret.as_ref() else {
        return login_error(&state, "disabled");
    };
    let scope = crate::sso::policy::throttle_scope(state.config.tenant.as_deref());
    if let Err(refused) = crate::sso::policy::throttle_check(&scope, &extensions, &headers).await {
        return refused;
    }
    let Some(redirect_uri) = derive_bare_redirect(&headers, &extensions, &state, &slug) else {
        return login_error(&state, "config");
    };
    let cfg = match super::sso_provider::resolve_by_slug(&state.pool, &slug, redirect_uri).await {
        Ok(Some(c)) => c,
        Ok(None) => return login_error(&state, "disabled"),
        Err(e) => {
            tracing::error!(target: "rustango::admin::sso", "begin resolve: {e}");
            return login_error(&state, "config");
        }
    };
    let provider = match build_provider(&cfg.sso).await {
        Ok(p) => p,
        Err(e) => {
            tracing::error!(target: "rustango::admin::sso", "begin: {e}");
            return login_error(&state, "config");
        }
    };
    let (url, flow) = provider.begin();
    let sealed = seal_flow(
        &flow,
        FlowScope::new(FlowPurpose::Admin, "", &slug),
        secret.key(),
    );
    let cookie = flow_cookie(&state).set(&sealed, 600);
    let mut resp = Redirect::to(&url).into_response();
    if let Ok(v) = HeaderValue::from_str(&cookie) {
        resp.headers_mut().insert(header::SET_COOKIE, v);
    }
    resp
}

// GET /login/sso/{slug}/callback: finish the handshake, link the
// account, mint the session.
async fn sso_callback(
    State(state): State<AppState>,
    Path(slug): Path<String>,
    headers: HeaderMap,
    extensions: axum::http::Extensions,
    Query(params): Query<CallbackParams>,
) -> Response {
    let Some(secret) = state.config.session_secret.as_ref() else {
        return login_error(&state, "disabled");
    };
    if params.error.is_some() {
        return login_error(&state, "denied");
    }
    let (Some(code), Some(cb_state)) = (params.code, params.state) else {
        return login_error(&state, "callback");
    };
    // Recover + verify the sealed flow from its cookie.
    let Some(sealed) = flow_cookie(&state).read(&headers) else {
        return login_error(&state, "expired");
    };
    let flow = match open_flow(
        sealed,
        FlowScope::new(FlowPurpose::Admin, "", &slug),
        secret.key(),
    ) {
        Ok(f) => f,
        Err(_) => return login_error(&state, "expired"),
    };
    let scope = crate::sso::policy::throttle_scope(state.config.tenant.as_deref());
    let attempt = match crate::sso::policy::throttle_begin(&scope, &extensions, &headers).await {
        Ok(a) => a,
        Err(refused) => return refused,
    };
    // Claimed only past the throttle, so a throttled callback can be retried.
    if !crate::sso::claim_flow(&flow) {
        return login_error(&state, "expired");
    }
    let Some(redirect_uri) = derive_bare_redirect(&headers, &extensions, &state, &slug) else {
        return login_error(&state, "config");
    };
    let cfg = match super::sso_provider::resolve_by_slug(&state.pool, &slug, redirect_uri).await {
        Ok(Some(c)) => c,
        Ok(None) => return login_error(&state, "disabled"),
        Err(e) => {
            tracing::error!(target: "rustango::admin::sso", "callback resolve: {e}");
            return login_error(&state, "config");
        }
    };
    let provider = match build_provider(&cfg.sso).await {
        Ok(p) => p,
        Err(e) => {
            tracing::error!(target: "rustango::admin::sso", "callback build: {e}");
            return login_error(&state, "config");
        }
    };
    let identity = match provider.complete(&flow, &code, &cb_state).await {
        Ok((u, tokens)) => {
            crate::sso::policy::Identity::from_handshake(&provider, u, &tokens, &flow).await
        }
        Err(e) => {
            tracing::warn!(target: "rustango::admin::sso", "handshake: {e}");
            attempt.failed().await;
            return login_error(&state, "handshake");
        }
    };
    let normalized = &identity.profile;
    // Sign in by (provider, sub) link only: every admin account is staff,
    // so a verified email never creates a link here.
    let key = cfg.key(LinkSource::Admin);
    let accounts = AdminAccounts(&state.pool);
    let path = format!("/login/sso/{slug}");
    let meta = || meta_from_parts(&extensions, &headers, Some(&path));
    let policy = crate::sso::policy::EffectivePolicy::new(cfg.policy.clone(), false)
        .with_lifecycle(cfg.lifecycle.clone());
    let request = crate::sso::policy::AdmitRequest::new(
        &state.pool,
        crate::sso::policy::Surface::BareAdmin,
        &key,
        &policy,
        &identity,
    )
    .provider(&slug);
    let uid = match crate::sso::policy::admit(request, &accounts).await {
        Ok(a) => a.user_id,
        Err(crate::sso::policy::Denied::Refused(r)) => {
            let ctx = crate::sso::policy::RefusalContext {
                pool: &state.pool,
                surface: crate::sso::policy::Surface::BareAdmin,
                signal_source: SIGNAL_SOURCE,
                provider: &slug,
                key: &key,
                identity: &identity,
                tenant: state.config.tenant.clone(),
                extensions: &extensions,
                headers: &headers,
                path: &path,
            };
            crate::sso::policy::refuse(&ctx, &r).await;
            attempt.failed().await;
            return login_error(&state, "nouser");
        }
        Err(e) => {
            tracing::error!(target: "rustango::admin::sso", slug, "sso sign-in failed: {e}");
            return login_error(&state, "nouser");
        }
    };
    let Ok(Some(user)) = accounts.user(uid).await else {
        return login_error(&state, "nouser");
    };
    if !user.active {
        signal_refused(
            SIGNAL_SOURCE,
            normalized,
            AuthFailureReason::Inactive,
            meta(),
            state.config.tenant.clone(),
        )
        .await;
        return login_error(&state, "nouser");
    }
    attempt.succeeded().await;
    let ttl = policy.session_ttl(session::DEFAULT_TTL_SECS, user.is_superuser);
    // A confirmed device owes its code first, as on the password login (#2249).
    #[cfg(feature = "totp")]
    match super::totp_store::confirmed_secret_checked(&state.pool, uid).await {
        Ok(None) => {}
        Ok(Some(_)) => {
            return second_factor::prompt(&state, &extensions, &headers, secret, &user, ttl).await
        }
        Err(e) => {
            // Fail closed: an unreadable device is not "no second factor" (#1644).
            tracing::error!(target: "rustango::admin::sso", user_id = uid, error = %e, "cannot read the TOTP device");
            return login_error(&state, "config");
        }
    }
    mint_session(&state, secret, &user, meta(), ttl).await
}

/// Mint the normal admin session, bound to the user's stored password
/// hash, exactly as a successful password login does.
async fn mint_session(
    state: &AppState,
    secret: &session::AdminSessionSecret,
    user: &AdminUser,
    request: AuthRequestMeta,
    ttl_secs: i64,
) -> Response {
    let uid = user.id.get().copied().unwrap_or_default();
    let auth_hash = crate::session::PasswordFingerprint::of(secret, &user.password_hash);
    let cookie_value = session::encode_for(
        secret,
        AdminSession::new(uid, user.username.clone(), user.is_superuser),
        &auth_hash,
        user.sessions_revoked_at,
        ttl_secs,
    );
    let session_cookie = format!(
        "{SESSION_COOKIE}={cookie_value}; Path=/; HttpOnly; SameSite=Lax{s}",
        s = cookie_attrs(state.config.secure_cookies),
    );
    let redirect_to = if state.config.admin_prefix.is_empty() {
        "/".to_owned()
    } else {
        state.config.admin_prefix.clone()
    };
    let mut resp = Redirect::to(&redirect_to).into_response();
    if let Ok(v) = HeaderValue::from_str(&session_cookie) {
        resp.headers_mut().append(header::SET_COOKIE, v);
    }
    clear_flow(&mut resp, state);
    send_user_logged_in(UserLoggedInContext {
        source: SIGNAL_SOURCE,
        user_id: uid,
        username: user.username.clone(),
        is_superuser: user.is_superuser,
        request,
        tenant: state.config.tenant.clone(),
    })
    .await;
    resp
}

/// The bare admin's flow cookie: at `/`, so `__Host-` over HTTPS.
fn flow_cookie(state: &AppState) -> crate::sso::FlowCookie<'static> {
    crate::sso::FlowCookie::new(SSO_FLOW_COOKIE, "/", state.config.secure_cookies)
}

/// Expire the flow cookie.
fn clear_flow(resp: &mut Response, state: &AppState) {
    for c in flow_cookie(state).clear() {
        if let Ok(v) = HeaderValue::from_str(&c) {
            resp.headers_mut().append(header::SET_COOKIE, v);
        }
    }
}

/// Expire the transient cookie `name`.
#[cfg(feature = "totp")]
fn clear_cookie(resp: &mut Response, name: &str) {
    if let Ok(v) = HeaderValue::from_str(&format!("{name}=; Path=/; HttpOnly; Max-Age=0")) {
        resp.headers_mut().append(header::SET_COOKIE, v);
    }
}

/// The TOTP step after an SSO sign-in (#2249). The IdP proved who the
/// user is; a signed, short-lived cookie carries that to the code form.
#[cfg(feature = "totp")]
mod second_factor {
    use super::*;
    use crate::session::PendingSecondFactor as Pending;

    const PENDING_COOKIE: &str = "rustango_admin_sso_totp";
    /// Domain tag: a pending cookie is never a valid MAC of a session.
    const TAG: &[u8] = b"rustango-admin-sso-totp-v1";
    const TTL_SECS: i64 = Pending::TTL_SECS;

    fn seal(secret: &session::AdminSessionSecret, p: &Pending) -> String {
        p.seal(secret, TAG)
    }

    fn open(secret: &session::AdminSessionSecret, value: &str) -> Option<Pending> {
        Pending::open(secret, TAG, value)
    }

    /// Ask for the code: the TOTP-only login form plus the pending cookie.
    pub(super) async fn prompt(
        state: &AppState,
        extensions: &axum::http::Extensions,
        headers: &HeaderMap,
        secret: &session::AdminSessionSecret,
        user: &AdminUser,
        session_ttl: i64,
    ) -> Response {
        let mut pending = Pending::new(
            secret,
            user.id.get().copied().unwrap_or_default(),
            &user.password_hash,
        );
        // Signed with the rest, so the code step keeps the provider's lifetime.
        pending.session_ttl = Some(session_ttl);
        let cookie = format!(
            "{PENDING_COOKIE}={}; Path=/; HttpOnly; SameSite=Lax; Max-Age={TTL_SECS}{s}",
            seal(secret, &pending),
            s = cookie_attrs(state.config.secure_cookies),
        );
        let mut resp =
            crate::admin::login_view::sso_totp_response(state, extensions, headers, None).await;
        if let Ok(v) = HeaderValue::from_str(&cookie) {
            resp.headers_mut().append(header::SET_COOKIE, v);
        }
        clear_flow(&mut resp, state);
        resp
    }

    #[derive(serde::Deserialize)]
    pub(super) struct CodeInput {
        #[serde(rename = "_csrf", default)]
        csrf_token: Option<String>,
        #[serde(default)]
        totp_code: Option<String>,
    }

    // POST /login/sso-totp: redeem the code, then mint the session.
    pub(super) async fn submit(
        State(state): State<AppState>,
        ip: crate::login_throttle::ClientIp,
        extensions: axum::http::Extensions,
        headers: HeaderMap,
        axum::Form(form): axum::Form<CodeInput>,
    ) -> Response {
        use crate::login_throttle::LoginScope;
        let Some(secret) = state.config.session_secret.as_ref() else {
            return login_error(&state, "disabled");
        };
        if !crate::forms::csrf::verify_form_token(&headers, form.csrf_token.as_deref()) {
            return crate::admin::login_view::sso_totp_response(
                &state,
                &extensions,
                &headers,
                Some("Your session expired or the form was invalid. Please try again."),
            )
            .await;
        }
        let Some(pending) = crate::cookies::cookie_from_headers(&headers, PENDING_COOKIE)
            .and_then(|v| open(secret, v))
        else {
            return login_error(&state, "expired");
        };
        let Ok(Some(user)) = AdminAccounts(&state.pool).user(pending.uid).await else {
            return login_error(&state, "nouser");
        };
        if !user.active || !pending.pwf.matches(secret, &user.password_hash) {
            return login_error(&state, "expired");
        }
        // Same lock and limits as the password login's code check.
        let attempt = match crate::login_throttle::shared()
            .begin(&LoginScope::Admin, &ip, &user.username)
            .await
        {
            Ok(a) => a,
            Err(refused) => return refused.into_response(),
        };
        let device = match super::super::totp_store::confirmed_secret_checked(
            &state.pool,
            pending.uid,
        )
        .await
        {
            Ok(Some(device)) => device,
            Ok(None) | Err(_) => {
                attempt.prompted().await;
                return login_error(&state, "expired");
            }
        };
        let code = form.totp_code.as_deref().unwrap_or("").trim();
        let accepted = !code.is_empty()
            && super::super::totp_store::redeem_code(&state.pool, pending.uid, &device, code)
                .await
                .unwrap_or(false);
        if !accepted {
            if code.is_empty() {
                attempt.prompted().await;
            } else {
                attempt.failed().await;
            }
            use crate::signals::auth::{send_user_login_failed, AuthFailureReason};
            send_user_login_failed(crate::signals::auth::UserLoginFailedContext {
                source: SIGNAL_SOURCE,
                attempted_username: Some(user.username.clone()),
                reason: AuthFailureReason::InvalidCredentials,
                request: crate::signals::auth::meta_from_parts(
                    &extensions,
                    &headers,
                    Some("/login/sso-totp"),
                ),
                tenant: state.config.tenant.clone(),
            })
            .await;
            return crate::admin::login_view::sso_totp_response(
                &state,
                &extensions,
                &headers,
                Some("Enter the 6-digit code from your authenticator app."),
            )
            .await;
        }
        attempt.succeeded().await;
        let meta = meta_from_parts(&extensions, &headers, Some("/login/sso-totp"));
        let ttl = pending.session_ttl.map_or(session::DEFAULT_TTL_SECS, |t| {
            t.min(session::DEFAULT_TTL_SECS)
        });
        let mut resp = mint_session(&state, secret, &user, meta, ttl).await;
        clear_cookie(&mut resp, PENDING_COOKIE);
        resp
    }
}

/// The bare admin's accounts. Every one is staff, so none links by email.
struct AdminAccounts<'a>(&'a crate::sql::Pool);

impl AdminAccounts<'_> {
    /// The admin user with this id; a driver error is an error, not "missing".
    async fn user(&self, id: i64) -> Result<Option<AdminUser>, String> {
        use crate::sql::FetcherPool as _;
        Ok(AdminUser::objects()
            .filter("id", id)
            .fetch(self.0)
            .await
            .map_err(|e| e.to_string())?
            .into_iter()
            .next())
    }
}

fn admin_account(u: &AdminUser) -> Option<Account> {
    Some(
        Account::new(u.id.get().copied()?, true, u.active)
            .with_superuser(u.is_superuser)
            .with_created_at(u.created_at),
    )
}

impl AccountLookup for AdminAccounts<'_> {
    async fn by_id(&self, id: i64) -> Result<Option<Account>, String> {
        Ok(self.user(id).await?.as_ref().and_then(admin_account))
    }

    async fn by_email(&self, email: &str) -> Result<EmailLookup, String> {
        use crate::sql::FetcherPool as _;
        let rows = AdminUser::objects()
            .filter("email__iexact", email.to_owned())
            .fetch(self.0)
            .await
            .map_err(|e| e.to_string())?;
        Ok(
            match EmailLookup::pick(&rows, email, |u| u.email.as_deref()) {
                Ok(Some(u)) => admin_account(u).map_or(EmailLookup::Missing, EmailLookup::Found),
                Ok(None) => EmailLookup::Missing,
                Err(()) => EmailLookup::Collides,
            },
        )
    }
}

#[cfg(test)]
mod redirect_tests {
    /// The redirect URI uses only a Host the allowed hosts list.
    #[test]
    fn the_redirect_uri_needs_an_allowed_host() {
        let headers = |host: &str| {
            let mut h = axum::http::HeaderMap::new();
            h.insert(axum::http::header::HOST, host.parse().unwrap());
            h
        };
        let ext = axum::http::Extensions::new();
        let allowed = crate::host_validation::AllowedHostsLayer::new(["admin.example.com"]);
        let go = |host: &str, a| super::redirect_for(&headers(host), &ext, "/login", a, "g");
        assert_eq!(
            go("admin.example.com:8443", Some(&allowed)).as_deref(),
            Some("https://admin.example.com:8443/login/sso/g/callback")
        );
        assert_eq!(go("evil.example", Some(&allowed)), None);
        // No list: any plain host, as before.
        assert!(go("evil.example", None).is_some());
    }
}

#[cfg(all(test, feature = "testkit"))]
mod tests {
    use super::AdminUser;

    /// The admin account carries its creation time, so stale links are noticed.
    #[test]
    fn admin_account_carries_created_at() {
        let at = chrono::Utc::now() - chrono::TimeDelta::days(3);
        let u = AdminUser {
            id: crate::sql::Auto::Set(7),
            created_at: at,
            ..crate::testkit::admin_user()
        };
        assert_eq!(super::admin_account(&u).unwrap().created_at, Some(at));
    }
}