rustango 0.43.1

Django-shaped 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
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
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
//! `GET /login` + `POST /login` + `POST /logout` + auth middleware
//! for the bare admin's session auth (#253 slice A).
//!
//! Mounted by [`crate::admin::Builder::with_session_auth`]. Layered
//! as middleware so every non-login route requires a valid session
//! cookie; the gate redirects to `/login` (relative to
//! `state.config.admin_prefix`) on missing / expired cookies.
//!
//! ## Reuse with `tenancy::admin`
//!
//! The HMAC signing primitive comes from `crate::session` (shared
//! with `tenancy::session`). The password-verify call goes through
//! `crate::passwords::verify` — the same primitive the tenancy
//! `auth::authenticate_user` flow uses. Only the user model
//! (`AdminUser` vs `tenancy::User`) and the cookie shape differ;
//! all the crypto + password machinery lives in one place.

use std::sync::Arc;

use axum::body::Body;
use axum::extract::{Form, State};
use axum::http::{header, HeaderValue, Request, StatusCode};
use axum::middleware::Next;
use axum::response::{Html, IntoResponse, Redirect, Response};
use axum::routing::{get, post};
use axum::Router;

use super::session::{self, AdminSession, AdminSessionSecret, SESSION_COOKIE};
use super::templates::render_template;
use super::urls::AppState;
use super::user::AdminUser;
use crate::core::{Filter, Model, Op, SelectQuery, SqlValue, WhereExpr};

/// Public (unauthenticated) routes — `/login` + `/logout`. Merged
/// into the admin router BEFORE the auth middleware is applied so
/// the login form itself stays publicly reachable.
pub(crate) fn public_router(state: AppState) -> Router {
    Router::new()
        .route("/login", get(login_form).post(login_submit))
        .route("/logout", post(logout_submit))
        .with_state(state)
}

/// Authenticated routes that ride on top of the session middleware.
/// `/account/password` lives here so an unauthenticated visitor
/// can't reach the password-change form. Mounted from
/// [`crate::admin::Builder::build`] when `with_session_auth` is set.
pub(crate) fn protected_router(state: AppState) -> Router {
    let router = Router::new().route(
        "/account/password",
        get(change_password_form).post(change_password_submit),
    );
    // Issue #367 — TOTP two-factor enrollment (self-service, behind the
    // session gate). Only mounted when the `totp` feature is on.
    #[cfg(feature = "totp")]
    let router = router.route(
        "/account/totp",
        get(totp_enroll_form).post(totp_enroll_submit),
    );
    router.with_state(state)
}

// ============================================================ Login form (GET)

async fn login_form(State(state): State<AppState>, headers: axum::http::HeaderMap) -> Response {
    login_response(&state, &headers, None)
}

/// Build the login-page response, seeding a double-submit CSRF token
/// (audit M3): the cookie is set on the GET (if not already present) and
/// the matching token is embedded as a hidden form field, so the POST
/// can be validated in [`login_submit`] without relying on outer
/// middleware placement.
fn login_response(
    state: &AppState,
    headers: &axum::http::HeaderMap,
    error: Option<&str>,
) -> Response {
    use crate::forms::csrf;
    let (token, set_cookie) = csrf::ensure_token(headers, csrf::CSRF_COOKIE);
    let html = render_login_form(state, error, &csrf::csrf_input_html(&token));
    let mut resp = Html(html).into_response();
    if let Some(cookie) = set_cookie {
        if let Ok(v) = HeaderValue::from_str(&cookie) {
            resp.headers_mut().append(header::SET_COOKIE, v);
        }
    }
    resp
}

fn render_login_form(state: &AppState, error: Option<&str>, csrf_input: &str) -> String {
    let admin_prefix = &state.config.admin_prefix;
    let ctx = serde_json::json!({
        "title": "Sign in",
        "action": format!("{admin_prefix}/login"),
        "error": error,
        "csrf_input": csrf_input,
        "admin_title": state
            .config
            .title
            .as_deref()
            .unwrap_or("Rustango Admin"),
        "admin_prefix": admin_prefix,
        "static_url": &state.config.static_url,
        // Issue #367 — show the optional authenticator-code field when
        // the `totp` feature is compiled in. The field is harmless for
        // non-enrolled users (left blank), so a build-time flag is
        // enough; no per-request DB lookup on the login GET.
        "totp_enabled": cfg!(feature = "totp"),
    });
    render_template("login.html", &ctx)
}

// ============================================================ Login form (POST)

#[derive(serde::Deserialize)]
struct LoginInput {
    username: String,
    password: String,
    /// Double-submit CSRF token (audit M3). Optional so a missing field
    /// is handled as a failed check (re-render) rather than a 422 form
    /// rejection.
    #[serde(rename = "_csrf", default)]
    csrf_token: Option<String>,
    /// Authenticator (TOTP) code — issue #367. Optional: only enrolled
    /// users need it, and the field is always present on the form so a
    /// 2FA user submits username + password + code in one step (no
    /// hidden-password second round). Ignored when the `totp` feature is
    /// off or the user has no confirmed device.
    // Read only when the `totp` feature compiles the 2FA challenge; the
    // field stays on the form unconditionally so enabling the feature
    // doesn't change the wire format.
    #[cfg_attr(not(feature = "totp"), allow(dead_code))]
    #[serde(default)]
    totp_code: Option<String>,
}

async fn login_submit(
    State(state): State<AppState>,
    headers: axum::http::HeaderMap,
    Form(form): Form<LoginInput>,
) -> Response {
    use crate::signals::auth::{
        meta_from_headers, send_user_logged_in, send_user_login_failed, AuthFailureReason,
        UserLoggedInContext, UserLoginFailedContext,
    };
    let meta = meta_from_headers(&headers, Some("/login"));

    let Some(secret) = state.config.session_secret.clone() else {
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            "session auth not configured",
        )
            .into_response();
    };

    // Audit M3 — validate the double-submit CSRF token before touching
    // the database or verifying credentials. A cross-site forged POST
    // can't read the SameSite=Lax CSRF cookie to echo it back, so it
    // fails here. The token is seeded + embedded by `login_response`.
    if !crate::forms::csrf::verify_form_token(&headers, form.csrf_token.as_deref()) {
        return login_response(
            &state,
            &headers,
            Some("Your session expired or the form was invalid. Please try again."),
        );
    }

    // Schema-driven lookup so we don't depend on tenancy's
    // typed query helpers — the bare admin compiles without `tenancy`.
    let fields: Vec<&'static crate::core::FieldSchema> = AdminUser::SCHEMA.fields.iter().collect();
    // #562 — by_pk constructor for the single-column-lookup shape.
    let select = SelectQuery::by_pk(
        AdminUser::SCHEMA,
        "username",
        SqlValue::String(form.username.clone()),
    );
    let row = crate::sql::select_one_row_as_json(&state.pool, &select, &fields)
        .await
        .ok()
        .flatten();

    let Some(row) = row else {
        // H1: spend a verify's worth of work on the unknown-user path
        // so timing doesn't reveal whether the username exists.
        crate::passwords::verify_dummy(&form.password);
        send_user_login_failed(UserLoginFailedContext {
            source: "admin",
            attempted_username: Some(form.username.clone()),
            reason: AuthFailureReason::InvalidCredentials,
            request: meta.clone(),
        })
        .await;
        return login_response(&state, &headers, Some("Invalid credentials."));
    };
    let id = row.get("id").and_then(|v| v.as_i64()).unwrap_or_default();
    let stored_hash = row
        .get("password_hash")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    let is_active = row.get("active").and_then(|v| v.as_bool()).unwrap_or(true);
    let is_superuser = row
        .get("is_superuser")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    // Audit M1 — per-account brute-force lockout, on by default. The key
    // is scoped (`admin:<id>`) so it can't collide with operator/tenant
    // ids, and uses the resolved id (not the raw username) so an attacker
    // can't lock arbitrary accounts. A locked account short-circuits
    // before the password verify.
    #[cfg(feature = "cache")]
    if crate::account_lockout::shared()
        .is_locked(&format!("admin:{id}"))
        .await
    {
        send_user_login_failed(UserLoginFailedContext {
            source: "admin",
            attempted_username: Some(form.username.clone()),
            reason: AuthFailureReason::InvalidCredentials,
            request: meta.clone(),
        })
        .await;
        return login_response(
            &state,
            &headers,
            Some("Too many failed attempts. Please try again later."),
        );
    }

    // Verify before the active check so active vs inactive accounts take
    // the same time (audit H1).
    let password_ok = crate::passwords::verify(&form.password, stored_hash).unwrap_or(false);

    if !is_active {
        send_user_login_failed(UserLoginFailedContext {
            source: "admin",
            attempted_username: Some(form.username.clone()),
            reason: AuthFailureReason::Inactive,
            request: meta.clone(),
        })
        .await;
        // Audit M4 — do NOT reveal that the account exists-but-disabled.
        // Return the same generic message as unknown-user / wrong-password
        // so the login form can't be used to enumerate accounts. The
        // Inactive signal above still records the real reason for audit.
        return login_response(&state, &headers, Some("Invalid credentials."));
    }
    if !password_ok {
        // Audit M1 — count this failure toward the per-account lockout.
        #[cfg(feature = "cache")]
        {
            let _ = crate::account_lockout::shared()
                .record_failure(&format!("admin:{id}"))
                .await;
        }
        send_user_login_failed(UserLoginFailedContext {
            source: "admin",
            attempted_username: Some(form.username.clone()),
            reason: AuthFailureReason::InvalidCredentials,
            request: meta.clone(),
        })
        .await;
        return login_response(&state, &headers, Some("Invalid credentials."));
    }

    // Issue #367 — two-factor challenge. If the user has a confirmed
    // TOTP device, a valid authenticator code is required before the
    // session is granted. The password is already verified at this
    // point; a missing/wrong code re-renders the login form (the
    // password counts as "spent" so we don't reveal 2FA-enrolled status
    // any differently than a normal failure beyond the message).
    #[cfg(feature = "totp")]
    {
        if let Some(totp_secret) = super::totp_store::confirmed_secret(&state.pool, id).await {
            let code = form.totp_code.as_deref().unwrap_or("").trim();
            // 30s step, 6 digits, ±1 window — standard authenticator app
            // defaults, tolerant of one step of clock skew.
            if code.is_empty() || !crate::totp::verify(&totp_secret, code, 30, 6, 1) {
                send_user_login_failed(UserLoginFailedContext {
                    source: "admin",
                    attempted_username: Some(form.username.clone()),
                    reason: AuthFailureReason::InvalidCredentials,
                    request: meta.clone(),
                })
                .await;
                return login_response(
                    &state,
                    &headers,
                    Some("Enter the 6-digit code from your authenticator app."),
                );
            }
        }
    }

    // Audit M1 — successful login clears the failure counter + any lock.
    #[cfg(feature = "cache")]
    crate::account_lockout::shared()
        .clear(&format!("admin:{id}"))
        .await;

    // Audit N8 — bind the cookie to a fingerprint of the current
    // password hash so a password change/reset invalidates it.
    let auth_hash = session::password_fingerprint(&secret, stored_hash);
    let cookie_value = session::encode(
        &secret,
        AdminSession {
            user_id: id,
            username: form.username.clone(),
            is_superuser,
        },
        &auth_hash,
    );
    let cookie = format!(
        "{name}={val}; Path=/; HttpOnly; SameSite=Lax{secure}",
        name = SESSION_COOKIE,
        val = cookie_value,
        secure = if state.config.secure_cookies {
            "; Secure"
        } else {
            ""
        },
    );
    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(&cookie) {
        resp.headers_mut().insert(header::SET_COOKIE, v);
    }
    send_user_logged_in(UserLoggedInContext {
        source: "admin",
        user_id: id,
        username: form.username.clone(),
        is_superuser,
        request: meta,
    })
    .await;
    resp
}

// ============================================================ Change password (GET + POST)

async fn change_password_form(State(state): State<AppState>) -> Html<String> {
    Html(render_change_password_form(&state, None, None))
}

#[derive(serde::Deserialize)]
struct ChangePasswordInput {
    current_password: String,
    new_password: String,
    new_password_confirm: String,
}

async fn change_password_submit(
    State(state): State<AppState>,
    Form(form): Form<ChangePasswordInput>,
) -> Response {
    // The middleware guarantees a session is in scope here; if not,
    // bail loudly — a request reaching this handler without one is
    // a programmer bug.
    let Some(session) = super::session::current() else {
        return (StatusCode::UNAUTHORIZED, "session required").into_response();
    };

    if form.new_password != form.new_password_confirm {
        return Html(render_change_password_form(
            &state,
            None,
            Some("Confirmation password did not match."),
        ))
        .into_response();
    }
    if form.new_password.len() < 8 {
        return Html(render_change_password_form(
            &state,
            None,
            Some("New password must be at least 8 characters."),
        ))
        .into_response();
    }

    // Look up the current row by user_id (from the session) so we
    // can verify the *current* password before mutating the hash.
    let fields: Vec<&'static crate::core::FieldSchema> = AdminUser::SCHEMA.fields.iter().collect();
    // #562 — by_pk constructor.
    let select = SelectQuery::by_pk(AdminUser::SCHEMA, "id", SqlValue::I64(session.user_id));
    let row = crate::sql::select_one_row_as_json(&state.pool, &select, &fields)
        .await
        .ok()
        .flatten();
    let Some(row) = row else {
        return (StatusCode::UNAUTHORIZED, "user not found").into_response();
    };
    let stored_hash = row
        .get("password_hash")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    if !crate::passwords::verify(&form.current_password, stored_hash).unwrap_or(false) {
        return Html(render_change_password_form(
            &state,
            None,
            Some("Current password is incorrect."),
        ))
        .into_response();
    }

    let new_hash = match crate::passwords::hash(&form.new_password) {
        Ok(h) => h,
        Err(_) => {
            return Html(render_change_password_form(
                &state,
                None,
                Some("Internal hashing error."),
            ))
            .into_response();
        }
    };

    // Schema-driven UPDATE — keeps the bare admin compiling without
    // tenancy's typed query helpers.
    use crate::core::{Assignment, Expr, UpdateQuery};
    let q = UpdateQuery {
        model: AdminUser::SCHEMA,
        set: vec![Assignment {
            column: "password_hash",
            value: Expr::Literal(SqlValue::String(new_hash.clone())),
        }],
        where_clause: WhereExpr::Predicate(Filter {
            column: "id",
            op: Op::Eq,
            value: SqlValue::I64(session.user_id),
        }),
    };
    if let Err(e) = crate::sql::update_pool(&state.pool, &q).await {
        return Html(render_change_password_form(
            &state,
            None,
            Some(&format!("Update failed: {e}")),
        ))
        .into_response();
    }

    // Audit N8 — the cookie this request carries holds the OLD password
    // fingerprint, so the gate would sign this session out on the next
    // request. Re-issue the cookie with the NEW fingerprint so the
    // current device stays signed in while every *other* device's
    // pre-change cookie is invalidated (mirrors Django's
    // update_session_auth_hash).
    let mut resp = Html(render_change_password_form(
        &state,
        Some("Password updated."),
        None,
    ))
    .into_response();
    if let Some(secret) = state.config.session_secret.as_ref() {
        let auth_hash = session::password_fingerprint(secret, &new_hash);
        let cookie_value = session::encode(
            secret,
            AdminSession {
                user_id: session.user_id,
                username: session.username.clone(),
                is_superuser: session.is_superuser,
            },
            &auth_hash,
        );
        let cookie = format!(
            "{name}={val}; Path=/; HttpOnly; SameSite=Lax{secure}",
            name = SESSION_COOKIE,
            val = cookie_value,
            secure = if state.config.secure_cookies {
                "; Secure"
            } else {
                ""
            },
        );
        if let Ok(v) = HeaderValue::from_str(&cookie) {
            resp.headers_mut().insert(header::SET_COOKIE, v);
        }
    }
    resp
}

fn render_change_password_form(
    state: &AppState,
    success: Option<&str>,
    error: Option<&str>,
) -> String {
    let admin_prefix = &state.config.admin_prefix;
    let mut ctx = serde_json::json!({
        "title": "Change password",
        "action": format!("{admin_prefix}/account/password"),
        "success": success,
        "error": error,
    });
    super::templates::render_with_chrome(
        "change_password.html",
        &mut ctx,
        super::helpers::chrome_context(state, None),
    )
}

// ===================================================== TOTP 2FA enrollment (#367)

#[cfg(feature = "totp")]
#[derive(serde::Deserialize)]
struct TotpEnrollInput {
    #[serde(default)]
    totp_code: Option<String>,
    /// Present (`reset=1`) when re-enrolling from an already-enabled
    /// account — wipes the current device and shows a fresh setup.
    #[serde(default)]
    reset: Option<String>,
}

#[cfg(feature = "totp")]
fn render_totp_enroll(
    state: &AppState,
    already_enabled: bool,
    secret_base32: &str,
    otpauth_url: &str,
    error: Option<&str>,
    success: Option<&str>,
) -> String {
    let admin_prefix = &state.config.admin_prefix;
    let ctx = serde_json::json!({
        "title": "Two-factor authentication",
        "action": format!("{admin_prefix}/account/totp"),
        "admin_title": state.config.title.as_deref().unwrap_or("Rustango Admin"),
        "admin_prefix": admin_prefix,
        "static_url": &state.config.static_url,
        "already_enabled": already_enabled,
        "secret_base32": secret_base32,
        "otpauth_url": otpauth_url,
        "error": error,
        "success": success,
    });
    render_template("totp_enroll.html", &ctx)
}

/// Build an `otpauth://` URI for the session user against `secret`.
#[cfg(feature = "totp")]
fn enroll_otpauth(state: &AppState, account: &str, secret: &crate::totp::TotpSecret) -> String {
    let issuer = state.config.title.as_deref().unwrap_or("Rustango Admin");
    crate::totp::otpauth_url(issuer, account, secret)
}

#[cfg(feature = "totp")]
async fn totp_enroll_form(State(state): State<AppState>) -> Response {
    let Some(session) = super::session::current() else {
        return (StatusCode::UNAUTHORIZED, "session required").into_response();
    };
    let _ = super::totp_store::ensure_table(&state.pool).await;
    let device = super::totp_store::device(&state.pool, session.user_id).await;
    if device.as_ref().is_some_and(|d| d.confirmed) {
        return Html(render_totp_enroll(&state, true, "", "", None, None)).into_response();
    }
    // Reuse the pending secret if one exists, else generate + persist a
    // fresh (unconfirmed) one so a page reload is stable.
    let secret = match device.and_then(|d| crate::totp::TotpSecret::from_base32(&d.secret_base32)) {
        Some(s) => s,
        None => {
            let s = crate::totp::TotpSecret::generate();
            if super::totp_store::start_enrollment(&state.pool, session.user_id, &s)
                .await
                .is_err()
            {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    "could not start enrollment",
                )
                    .into_response();
            }
            s
        }
    };
    let otpauth = enroll_otpauth(&state, &session.username, &secret);
    Html(render_totp_enroll(
        &state,
        false,
        &secret.to_base32(),
        &otpauth,
        None,
        None,
    ))
    .into_response()
}

#[cfg(feature = "totp")]
async fn totp_enroll_submit(
    State(state): State<AppState>,
    Form(form): Form<TotpEnrollInput>,
) -> Response {
    let Some(session) = super::session::current() else {
        return (StatusCode::UNAUTHORIZED, "session required").into_response();
    };
    let _ = super::totp_store::ensure_table(&state.pool).await;

    // Re-enroll: wipe + regenerate, then show the fresh setup.
    if form.reset.is_some() {
        let s = crate::totp::TotpSecret::generate();
        let _ = super::totp_store::start_enrollment(&state.pool, session.user_id, &s).await;
        let otpauth = enroll_otpauth(&state, &session.username, &s);
        return Html(render_totp_enroll(
            &state,
            false,
            &s.to_base32(),
            &otpauth,
            None,
            None,
        ))
        .into_response();
    }

    // Confirm: verify the submitted code against the pending secret.
    let Some(device) = super::totp_store::device(&state.pool, session.user_id).await else {
        return Html(render_totp_enroll(
            &state,
            false,
            "",
            "",
            Some("No enrollment in progress — reload the page."),
            None,
        ))
        .into_response();
    };
    let Some(secret) = crate::totp::TotpSecret::from_base32(&device.secret_base32) else {
        return Html(render_totp_enroll(
            &state,
            false,
            "",
            "",
            Some("Stored setup key is invalid — re-enroll."),
            None,
        ))
        .into_response();
    };
    let code = form.totp_code.as_deref().unwrap_or("").trim();
    if code.is_empty() || !crate::totp::verify(&secret, code, 30, 6, 1) {
        let otpauth = enroll_otpauth(&state, &session.username, &secret);
        return Html(render_totp_enroll(
            &state,
            false,
            &device.secret_base32,
            &otpauth,
            Some("That code didn't match. Try again."),
            None,
        ))
        .into_response();
    }
    if super::totp_store::confirm(&state.pool, session.user_id)
        .await
        .is_err()
    {
        return Html(render_totp_enroll(
            &state,
            false,
            "",
            "",
            Some("Could not save — please try again."),
            None,
        ))
        .into_response();
    }
    Html(render_totp_enroll(
        &state,
        true,
        "",
        "",
        None,
        Some("Two-factor authentication is now enabled."),
    ))
    .into_response()
}

// ============================================================ Logout (POST)

async fn logout_submit(State(state): State<AppState>, headers: axum::http::HeaderMap) -> Response {
    use crate::signals::auth::{meta_from_headers, send_user_logged_out, UserLoggedOutContext};
    let meta = meta_from_headers(&headers, Some("/logout"));

    // Best-effort session decode so the signal carries the user id /
    // username when the cookie is still valid. Receivers that key off
    // those fields fall through to the `None` branch cleanly.
    let (user_id, username) = state
        .config
        .session_secret
        .as_ref()
        .and_then(|secret| {
            let raw = headers.get(header::COOKIE)?.to_str().ok()?;
            for part in raw.split(';').map(str::trim) {
                if let Some(val) = part.strip_prefix(&format!("{SESSION_COOKIE}=")) {
                    if let Some(sess) = session::decode(secret, val) {
                        return Some((Some(sess.user_id), Some(sess.username)));
                    }
                }
            }
            None
        })
        .unwrap_or((None, None));

    let cookie = format!(
        "{name}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0{secure}",
        name = SESSION_COOKIE,
        secure = if state.config.secure_cookies {
            "; Secure"
        } else {
            ""
        },
    );
    let mut resp = Redirect::to(&format!("{}/login", state.config.admin_prefix)).into_response();
    if let Ok(v) = HeaderValue::from_str(&cookie) {
        resp.headers_mut().insert(header::SET_COOKIE, v);
    }
    send_user_logged_out(UserLoggedOutContext {
        source: "admin",
        user_id,
        username,
        request: meta,
    })
    .await;
    resp
}

// ============================================================ Middleware

/// State threaded into the auth middleware — the signing secret +
/// the login URL to redirect to on missing session. Cloned per
/// request, kept Arc<…> so the underlying key isn't copied.
#[derive(Clone)]
pub(crate) struct SessionGate {
    pub(crate) secret: Arc<AdminSessionSecret>,
    pub(crate) login_path: String,
    /// #253 slice C — when `true`, non-superuser sessions are
    /// rejected with a 403 page. Default for the bare admin; mirrors
    /// Django's `is_staff` requirement (the bare admin has no
    /// per-model permission system yet, so the only access tier is
    /// "superuser"). Future epics layering in real permissions can
    /// flip this off and consult a `user_perms` set instead.
    pub(crate) require_superuser: bool,
    /// Audit N8 — pool for the per-request password-fingerprint check
    /// that invalidates cookies minted before a password change.
    pub(crate) pool: crate::sql::Pool,
}

/// Gate every admin request behind a valid session cookie. The
/// `/login` route bypasses the gate (mounted before this middleware
/// applies on the outer Router); embedded static assets at
/// `/__static__/...` also pass through.
///
/// On valid session: inserts `Extension<AdminSession>` into the
/// request so handlers can read the current user. When
/// `gate.require_superuser` is set (the bare-admin default), a
/// non-superuser session is rejected with a 403 page — Django's
/// "must be staff to access /admin" shape.
pub(crate) async fn require_session(
    State(gate): State<SessionGate>,
    mut request: Request<Body>,
    next: Next,
) -> Response {
    let path = request.uri().path();
    if path == gate.login_path || path == "/login" || path.starts_with("/__static__") {
        return next.run(request).await;
    }

    if let Some((mut session, cookie_auth_hash)) = read_session_cookie(&request, &gate.secret) {
        // Audit N8 + P1 — one per-request lookup re-derives the user's
        // LIVE state: it invalidates cookies minted before a password
        // change (fingerprint mismatch), and re-checks `active` +
        // `is_superuser` from the DB instead of trusting the cookie's
        // cached copy — so a deactivated or demoted admin loses access
        // immediately, not at the 8h cookie expiry.
        match gate_live_check(&gate, session.user_id, &cookie_auth_hash).await {
            // Password changed / user deleted / deactivated → force re-login.
            GateCheck::Reject => return Redirect::to(&gate.login_path).into_response(),
            // Row found + fingerprint matches: trust the LIVE flag.
            GateCheck::Live { is_superuser } => session.is_superuser = is_superuser,
            // Transient DB error: fail open on the *fingerprint/active*
            // checks (the cookie HMAC + exp still bound the session) but
            // keep the cookie's cached `is_superuser` for the gate below.
            GateCheck::DbError => {}
        }
        if gate.require_superuser && !session.is_superuser {
            // #253 slice C — render a 403 inline rather than redirect
            // to /login, so the operator gets a clear "you are signed
            // in but not allowed here" signal instead of an infinite
            // login → 403 → login loop.
            return forbidden_page(&session);
        }
        request.extensions_mut().insert(session.clone());
        // Scope the task-local so `chrome_context` (deep in the
        // template render stack) can read it without every handler
        // threading the session through its argument list.
        return super::session::CURRENT_SESSION
            .scope(session, next.run(request))
            .await;
    }

    // No valid session — bounce to the login form. Use 303 See Other
    // so the GET semantics are preserved (browsers follow with GET).
    Redirect::to(&gate.login_path).into_response()
}

/// #253 slice C — minimal 403 page for non-superuser sessions. Plain
/// HTML, no chrome (chrome rendering needs the same auth gate to
/// have already passed). The body invites the operator to contact
/// their administrator and offers a link to sign out + back to
/// login.
fn forbidden_page(session: &AdminSession) -> Response {
    // Tiny inline escape — the page renders BEFORE the admin chrome
    // (the gate fires before `next.run`), so we can't reach the
    // chrome's `render::escape` helper without rebuilding state.
    let mut username = String::with_capacity(session.username.len());
    for ch in session.username.chars() {
        match ch {
            '&' => username.push_str("&amp;"),
            '<' => username.push_str("&lt;"),
            '>' => username.push_str("&gt;"),
            '"' => username.push_str("&quot;"),
            '\'' => username.push_str("&#39;"),
            other => username.push(other),
        }
    }
    let body = format!(
        "<!doctype html>\
         <html><head><title>Forbidden</title>\
         <style>body{{font-family:system-ui;max-width:42em;margin:4em auto;padding:0 1em;line-height:1.5}}\
         h1{{font-size:1.4em}}\
         .meta{{color:#666;font-size:.9em}}\
         </style></head><body>\
         <h1>403 — Admin access required</h1>\
         <p>You are signed in as <strong>{username}</strong>, but only \
         superusers can use the admin.</p>\
         <p class=\"meta\">Ask your administrator to grant superuser \
         status, or sign out below if this isn't the account you \
         intended to use.</p>\
         <form method=\"post\" action=\"/logout\">\
           <button type=\"submit\">Sign out</button>\
         </form>\
         </body></html>"
    );
    let mut resp = Html(body).into_response();
    *resp.status_mut() = StatusCode::FORBIDDEN;
    resp
}

fn read_session_cookie(
    req: &Request<Body>,
    secret: &AdminSessionSecret,
) -> Option<(AdminSession, String)> {
    let raw = req.headers().get(header::COOKIE)?.to_str().ok()?;
    for part in raw.split(';').map(str::trim) {
        if let Some(val) = part.strip_prefix(&format!("{SESSION_COOKIE}=")) {
            return session::decode_full(secret, val);
        }
    }
    None
}

/// Outcome of the gate's per-request liveness lookup.
enum GateCheck {
    /// Row found and the password fingerprint matches; carries the
    /// user's LIVE `is_superuser` so the gate doesn't trust the cookie.
    Live { is_superuser: bool },
    /// Force re-login: password changed (fingerprint mismatch), user
    /// deleted, or the account is deactivated.
    Reject,
    /// Transient DB error — caller fails open on the liveness checks
    /// (the cookie HMAC + exp still bound the session).
    DbError,
}

/// Audit N8 + P1 — re-derive the user's live state in one lookup:
/// recompute the password fingerprint (invalidate cookies minted before
/// a password change), and read live `active` / `is_superuser` so a
/// deactivated or demoted admin loses access immediately rather than at
/// cookie expiry.
async fn gate_live_check(gate: &SessionGate, user_id: i64, cookie_auth_hash: &str) -> GateCheck {
    let fields: Vec<&'static crate::core::FieldSchema> = AdminUser::SCHEMA.fields.iter().collect();
    let select = SelectQuery::by_pk(AdminUser::SCHEMA, "id", SqlValue::I64(user_id));
    match crate::sql::select_one_row_as_json(&gate.pool, &select, &fields).await {
        Ok(Some(row)) => {
            let current = row
                .get("password_hash")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            if session::password_fingerprint(&gate.secret, current) != cookie_auth_hash {
                return GateCheck::Reject; // password changed since login
            }
            // `active` defaults true (matches the login check) so a
            // missing/null column doesn't lock everyone out; a real
            // `false` revokes the session.
            let active = row.get("active").and_then(|v| v.as_bool()).unwrap_or(true);
            if !active {
                return GateCheck::Reject;
            }
            let is_superuser = row
                .get("is_superuser")
                .and_then(|v| v.as_bool())
                .unwrap_or(false);
            GateCheck::Live { is_superuser }
        }
        Ok(None) => GateCheck::Reject, // user deleted
        Err(_) => GateCheck::DbError,
    }
}

#[cfg(all(test, feature = "postgres"))]
mod tests {
    use super::*;
    use crate::sql::sqlx::PgPool;
    use crate::sql::Pool;
    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt as _;

    // A lazily-connected pool — these tests exercise the CSRF gate,
    // which runs BEFORE any DB access, so the pool is never queried.
    fn test_state() -> AppState {
        let pool = Pool::Postgres(
            PgPool::connect_lazy("postgres://_:_@127.0.0.1:1/_unused")
                .expect("connect_lazy never fails"),
        );
        let mut config = super::super::urls::Config::default();
        config.session_secret = Some(crate::session::SessionSecret::from_bytes(vec![7u8; 32]));
        AppState {
            pool,
            config: Arc::new(config),
        }
    }

    #[tokio::test]
    async fn get_login_seeds_csrf_cookie_and_form_token() {
        let resp = public_router(test_state())
            .oneshot(
                Request::builder()
                    .uri("/login")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let set_cookie = resp
            .headers()
            .get(header::SET_COOKIE)
            .expect("GET should seed a CSRF cookie")
            .to_str()
            .unwrap();
        assert!(set_cookie.contains("rustango_csrf="), "{set_cookie}");
        let body = axum::body::to_bytes(resp.into_body(), 1 << 20)
            .await
            .unwrap();
        let body = std::str::from_utf8(&body).unwrap();
        assert!(
            body.contains(r#"name="_csrf""#),
            "form must carry the token"
        );
    }

    #[tokio::test]
    async fn post_login_without_csrf_token_is_rejected() {
        let resp = public_router(test_state())
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/login")
                    .header("content-type", "application/x-www-form-urlencoded")
                    .body(Body::from("username=alice&password=secret"))
                    .unwrap(),
            )
            .await
            .unwrap();
        // Re-render (200), NOT a 303 redirect — and no session cookie.
        assert_eq!(resp.status(), StatusCode::OK);
        let issued_session = resp.headers().get_all(header::SET_COOKIE).iter().any(|c| {
            c.to_str()
                .map(|s| s.contains(SESSION_COOKIE))
                .unwrap_or(false)
        });
        assert!(
            !issued_session,
            "a CSRF-less POST must not establish a session"
        );
        let body = axum::body::to_bytes(resp.into_body(), 1 << 20)
            .await
            .unwrap();
        assert!(std::str::from_utf8(&body).unwrap().contains("try again"));
    }
}