allowthem-server 0.0.9

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

use allowthem_core::types::User;
use allowthem_core::{AllowThem, AuthError};

#[derive(Clone)]
struct MfaConfig {
    issuer: String,
}

/// Create a router with MFA route handlers.
///
/// Returns a `Router<()>` with four endpoints:
/// - `POST /mfa/setup` — generates TOTP secret, returns otpauth URI and base32 secret
/// - `POST /mfa/confirm` — validates TOTP code, enables MFA, returns recovery codes
/// - `POST /mfa/disable` — disables MFA, deletes secret and recovery codes
/// - `POST /mfa/verify` — completes MFA login challenge with TOTP or recovery code
///
/// Setup/confirm/disable require an authenticated session (cookie-based).
/// Verify requires an mfa_token (from the two-step login flow).
///
/// ## Two-step login flow (for integrators)
///
/// When a user with MFA enabled logs in:
/// 1. Integrator verifies password via `db.find_for_login()` + `verify_password()`
/// 2. Integrator checks `db.has_mfa_enabled(user_id)` — if true:
/// 3. Integrator calls `db.create_mfa_challenge(user_id)` → returns `mfa_token`
/// 4. Integrator returns `{ mfa_required: true, mfa_token }` to client
/// 5. Client sends `POST /mfa/verify { mfa_token, code }` with TOTP or recovery code
/// 6. On success, a session is created and returned via Set-Cookie
pub fn mfa_routes(issuer: String) -> Router<()> {
    let config = MfaConfig { issuer };
    Router::new()
        .route("/mfa/setup", post(setup))
        .route("/mfa/confirm", post(confirm))
        .route("/mfa/disable", post(disable))
        .route("/mfa/verify", post(verify_mfa))
        .route("/auth/mfa/recover", post(recover))
        .route("/mfa/recovery-codes/regenerate", post(regenerate_codes))
        .route("/mfa/recovery-codes/count", get(recovery_code_count))
        .layer(Extension(config))
}

async fn authenticated_user(
    ath: &AllowThem,
    headers: &HeaderMap,
) -> Result<User, (StatusCode, Json<Value>)> {
    let cookie = headers
        .get(COOKIE)
        .and_then(|v| v.to_str().ok())
        .ok_or_else(|| {
            (
                StatusCode::UNAUTHORIZED,
                Json(json!({"error": "unauthenticated"})),
            )
        })?;

    let token = ath.parse_session_cookie(cookie).ok_or_else(|| {
        (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": "unauthenticated"})),
        )
    })?;

    let ttl = ath.session_config().ttl;
    let session = ath
        .db()
        .validate_session(&token, ttl)
        .await
        .map_err(|e| {
            tracing::error!("session validation error: {e}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": "internal error"})),
            )
        })?
        .ok_or_else(|| {
            (
                StatusCode::UNAUTHORIZED,
                Json(json!({"error": "unauthenticated"})),
            )
        })?;

    match ath.db().get_user(session.user_id).await {
        Ok(user) if user.is_active => Ok(user),
        Ok(_) => Err((
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": "unauthenticated"})),
        )),
        Err(AuthError::NotFound) => Err((
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": "unauthenticated"})),
        )),
        Err(e) => {
            tracing::error!("user lookup error: {e}");
            Err((
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": "internal error"})),
            ))
        }
    }
}

fn map_mfa_error(err: AuthError) -> (StatusCode, Json<Value>) {
    match err {
        AuthError::MfaAlreadyEnabled => (
            StatusCode::CONFLICT,
            Json(json!({"error": "MFA is already enabled"})),
        ),
        AuthError::MfaNotEnabled => (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "MFA is not enabled"})),
        ),
        AuthError::InvalidTotpCode => (
            StatusCode::BAD_REQUEST,
            Json(json!({"error": "invalid TOTP code"})),
        ),
        AuthError::MfaNotConfigured | AuthError::MfaEncryption(_) => {
            tracing::error!("MFA error: {err}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": "internal error"})),
            )
        }
        other => {
            tracing::error!("unexpected error in MFA route: {other}");
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": "internal error"})),
            )
        }
    }
}

/// POST /mfa/setup
///
/// Generates a TOTP secret for the authenticated user. Returns the otpauth URI
/// (for QR code rendering) and the base32-encoded secret.
async fn setup(
    Extension(ath): Extension<AllowThem>,
    Extension(config): Extension<MfaConfig>,
    headers: HeaderMap,
) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Value>)> {
    let user = authenticated_user(&ath, &headers).await?;

    let secret_b32 = ath
        .create_mfa_secret(user.id)
        .await
        .map_err(map_mfa_error)?;

    let uri = allowthem_core::totp::totp_uri(&secret_b32, user.email.as_str(), &config.issuer);

    Ok((
        StatusCode::OK,
        Json(json!({
            "secret": secret_b32,
            "otpauth_uri": uri,
        })),
    ))
}

#[derive(Deserialize)]
struct ConfirmBody {
    code: String,
}

/// POST /mfa/confirm
///
/// Validates the TOTP code against the user's pending secret. If valid,
/// enables MFA and returns 10 recovery codes (shown once).
async fn confirm(
    Extension(ath): Extension<AllowThem>,
    headers: HeaderMap,
    Json(body): Json<ConfirmBody>,
) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Value>)> {
    let user = authenticated_user(&ath, &headers).await?;

    let recovery_codes = ath
        .enable_mfa(user.id, &body.code)
        .await
        .map_err(map_mfa_error)?;

    Ok((
        StatusCode::OK,
        Json(json!({
            "message": "MFA enabled",
            "recovery_codes": recovery_codes,
        })),
    ))
}

/// POST /mfa/disable
///
/// Disables MFA for the authenticated user. Deletes the secret and all recovery codes.
async fn disable(
    Extension(ath): Extension<AllowThem>,
    headers: HeaderMap,
) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Value>)> {
    let user = authenticated_user(&ath, &headers).await?;

    ath.disable_mfa(user.id).await.map_err(map_mfa_error)?;

    Ok((StatusCode::OK, Json(json!({"message": "MFA disabled"}))))
}

#[derive(Deserialize)]
struct VerifyBody {
    mfa_token: String,
    code: String,
}

/// POST /mfa/verify
///
/// Completes the MFA login challenge. The client provides the `mfa_token`
/// (received after password verification) and a TOTP code or recovery code.
///
/// On success: creates a session and sets the session cookie.
/// On wrong code: returns 401 (the challenge token is NOT consumed, allowing retry).
/// On invalid/expired token: returns 401.
async fn verify_mfa(
    Extension(ath): Extension<AllowThem>,
    Json(body): Json<VerifyBody>,
) -> Response {
    let user_id = match ath.db().validate_mfa_challenge(&body.mfa_token).await {
        Ok(Some(uid)) => uid,
        Ok(None) => {
            return (
                StatusCode::UNAUTHORIZED,
                Json(json!({"error": "invalid or expired MFA token"})),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("MFA challenge validation error: {e}");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": "internal error"})),
            )
                .into_response();
        }
    };

    // Try TOTP first
    let totp_valid = match ath.verify_totp(user_id, &body.code).await {
        Ok(v) => v,
        Err(e) => return map_mfa_error(e).into_response(),
    };

    if !totp_valid {
        // Try recovery code
        let recovery_valid = match ath.db().verify_recovery_code(user_id, &body.code).await {
            Ok(v) => v,
            Err(e) => {
                tracing::error!("recovery code verification error: {e}");
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(json!({"error": "internal error"})),
                )
                    .into_response();
            }
        };

        if !recovery_valid {
            return (
                StatusCode::UNAUTHORIZED,
                Json(json!({"error": "invalid TOTP or recovery code"})),
            )
                .into_response();
        }
    }

    // Code is valid — consume the challenge and create a session
    let _ = ath.db().consume_mfa_challenge(&body.mfa_token).await;

    let token = allowthem_core::generate_token();
    let token_hash = allowthem_core::hash_token(&token);
    let expires = chrono::Utc::now() + ath.session_config().ttl;

    if let Err(e) = ath
        .db()
        .create_session(user_id, token_hash, None, None, expires)
        .await
    {
        tracing::error!("session creation error: {e}");
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({"error": "internal error"})),
        )
            .into_response();
    }

    ath.notify_user_active(user_id);
    ath.emit_event(allowthem_core::AuthEvent::new(
        "session.created",
        Some(user_id),
        serde_json::json!({ "user_id": user_id }),
    ))
    .await;

    let cookie_value = ath.session_cookie(&token);

    (
        StatusCode::OK,
        [(axum::http::header::SET_COOKIE, cookie_value)],
        Json(json!({"message": "MFA verification successful"})),
    )
        .into_response()
}

#[derive(Deserialize)]
struct RecoverBody {
    mfa_token: String,
    recovery_code: String,
}

/// POST /auth/mfa/recover
///
/// Completes MFA login using a recovery code. The client provides the
/// `mfa_token` (from the two-step login flow) and a one-time recovery code.
/// On success, the recovery code is consumed and a session is created.
/// Does NOT require an auth cookie (the user is mid-login).
async fn recover(Extension(ath): Extension<AllowThem>, Json(body): Json<RecoverBody>) -> Response {
    let user_id = match ath.db().validate_mfa_challenge(&body.mfa_token).await {
        Ok(Some(uid)) => uid,
        Ok(None) => {
            return (
                StatusCode::UNAUTHORIZED,
                Json(json!({"error": "invalid or expired MFA token"})),
            )
                .into_response();
        }
        Err(e) => {
            tracing::error!("MFA challenge validation error: {e}");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": "internal error"})),
            )
                .into_response();
        }
    };

    let consumed = match ath
        .db()
        .verify_recovery_code(user_id, &body.recovery_code)
        .await
    {
        Ok(v) => v,
        Err(e) => {
            tracing::error!("recovery code verification error: {e}");
            return (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(json!({"error": "internal error"})),
            )
                .into_response();
        }
    };

    if !consumed {
        return (
            StatusCode::UNAUTHORIZED,
            Json(json!({"error": "invalid recovery code"})),
        )
            .into_response();
    }

    // Recovery code accepted — consume the challenge and create a session
    let _ = ath.db().consume_mfa_challenge(&body.mfa_token).await;

    let token = allowthem_core::generate_token();
    let token_hash = allowthem_core::hash_token(&token);
    let expires = chrono::Utc::now() + ath.session_config().ttl;

    if let Err(e) = ath
        .db()
        .create_session(user_id, token_hash, None, None, expires)
        .await
    {
        tracing::error!("session creation error: {e}");
        return (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(json!({"error": "internal error"})),
        )
            .into_response();
    }

    ath.notify_user_active(user_id);
    ath.emit_event(allowthem_core::AuthEvent::new(
        "session.created",
        Some(user_id),
        serde_json::json!({ "user_id": user_id }),
    ))
    .await;

    let cookie_value = ath.session_cookie(&token);
    let remaining = ath
        .db()
        .remaining_recovery_codes(user_id)
        .await
        .unwrap_or(0);

    (
        StatusCode::OK,
        [(axum::http::header::SET_COOKIE, cookie_value)],
        Json(json!({
            "message": "recovery successful",
            "remaining_recovery_codes": remaining,
        })),
    )
        .into_response()
}

/// POST /mfa/recovery-codes/regenerate
///
/// Replaces all recovery codes with a fresh set of 10. Requires auth.
/// Returns the new codes (shown once).
async fn regenerate_codes(
    Extension(ath): Extension<AllowThem>,
    headers: HeaderMap,
) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Value>)> {
    let user = authenticated_user(&ath, &headers).await?;

    let has_mfa = ath.has_mfa_enabled(user.id).await.map_err(map_mfa_error)?;
    if !has_mfa {
        return Err(map_mfa_error(AuthError::MfaNotEnabled));
    }

    let codes = ath
        .regenerate_recovery_codes(user.id)
        .await
        .map_err(map_mfa_error)?;

    Ok((
        StatusCode::OK,
        Json(json!({
            "recovery_codes": codes,
        })),
    ))
}

/// GET /mfa/recovery-codes/count
///
/// Returns the number of unused recovery codes remaining. Requires auth.
async fn recovery_code_count(
    Extension(ath): Extension<AllowThem>,
    headers: HeaderMap,
) -> Result<(StatusCode, Json<Value>), (StatusCode, Json<Value>)> {
    let user = authenticated_user(&ath, &headers).await?;

    let count = ath
        .remaining_recovery_codes(user.id)
        .await
        .map_err(map_mfa_error)?;

    Ok((StatusCode::OK, Json(json!({"remaining": count}))))
}

#[cfg(test)]
mod tests {
    use super::*;
    use allowthem_core::handle::AllowThemBuilder;
    use allowthem_core::sessions::{generate_token, hash_token};
    use allowthem_core::types::Email;
    use axum::body::Body;
    use axum::http::Request;
    use chrono::{Duration, Utc};
    use totp_rs::{Algorithm, Secret, TOTP};
    use tower::ServiceExt;

    const TEST_MFA_KEY: [u8; 32] = [0x42; 32];

    async fn test_app() -> (AllowThem, Router) {
        let ath = AllowThemBuilder::new("sqlite::memory:")
            .cookie_secure(false)
            .mfa_key(TEST_MFA_KEY)
            .build()
            .await
            .unwrap();

        let routes = mfa_routes("allowthem-test".into());
        let app = routes.layer(axum::middleware::from_fn_with_state(
            ath.clone(),
            crate::cors::inject_ath_into_extensions,
        ));
        (ath, app)
    }

    async fn create_user_session(ath: &AllowThem) -> (allowthem_core::types::UserId, String) {
        let email = Email::new("mfa-user@example.com".to_string()).unwrap();
        let user = ath
            .db()
            .create_user(email, "password123", None, None)
            .await
            .unwrap();

        let token = generate_token();
        let token_hash = hash_token(&token);
        let expires = Utc::now() + Duration::hours(24);
        ath.db()
            .create_session(user.id, token_hash, None, None, expires)
            .await
            .unwrap();

        let cookie = format!("{}={}", ath.session_config().cookie_name, token.as_str());
        (user.id, cookie)
    }

    async fn read_body(resp: axum::http::Response<Body>) -> Value {
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        serde_json::from_slice(&bytes).unwrap()
    }

    #[tokio::test]
    async fn setup_returns_otpauth_uri() {
        let (ath, app) = test_app().await;
        let (_user_id, cookie) = create_user_session(&ath).await;

        let req = Request::builder()
            .method("POST")
            .uri("/mfa/setup")
            .header("cookie", &cookie)
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        let uri = body["otpauth_uri"].as_str().unwrap();
        assert!(uri.starts_with("otpauth://totp/"));
        assert!(uri.contains("allowthem-test"));
        assert!(body["secret"].as_str().is_some());
    }

    #[tokio::test]
    async fn confirm_with_valid_code_enables_mfa() {
        let (ath, app) = test_app().await;
        let (user_id, cookie) = create_user_session(&ath).await;

        // Step 1: Setup
        let secret_b32 = ath.create_mfa_secret(user_id).await.unwrap();

        // Step 2: Generate a valid code
        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Encoded(secret_b32).to_bytes().unwrap(),
            None,
            String::new(),
        )
        .unwrap();
        let valid_code = totp.generate_current().unwrap();

        // Step 3: Confirm
        let req = Request::builder()
            .method("POST")
            .uri("/mfa/confirm")
            .header("cookie", &cookie)
            .header("content-type", "application/json")
            .body(Body::from(format!(r#"{{"code":"{valid_code}"}}"#)))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        assert_eq!(body["message"], "MFA enabled");
        let codes = body["recovery_codes"].as_array().unwrap();
        assert_eq!(codes.len(), 10);

        // Verify MFA is actually enabled
        let enabled = ath.has_mfa_enabled(user_id).await.unwrap();
        assert!(enabled);
    }

    #[tokio::test]
    async fn confirm_with_invalid_code_fails() {
        let (ath, app) = test_app().await;
        let (user_id, cookie) = create_user_session(&ath).await;

        ath.create_mfa_secret(user_id).await.unwrap();

        let req = Request::builder()
            .method("POST")
            .uri("/mfa/confirm")
            .header("cookie", &cookie)
            .header("content-type", "application/json")
            .body(Body::from(r#"{"code":"000000"}"#))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
        let body = read_body(resp).await;
        assert_eq!(body["error"], "invalid TOTP code");
    }

    #[tokio::test]
    async fn disable_removes_mfa() {
        let (ath, app) = test_app().await;
        let (user_id, cookie) = create_user_session(&ath).await;

        // Setup and enable MFA via core methods
        let secret_b32 = ath.create_mfa_secret(user_id).await.unwrap();
        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Encoded(secret_b32).to_bytes().unwrap(),
            None,
            String::new(),
        )
        .unwrap();
        let code = totp.generate_current().unwrap();
        ath.enable_mfa(user_id, &code).await.unwrap();

        // Disable via route
        let req = Request::builder()
            .method("POST")
            .uri("/mfa/disable")
            .header("cookie", &cookie)
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        assert_eq!(body["message"], "MFA disabled");

        let enabled = ath.has_mfa_enabled(user_id).await.unwrap();
        assert!(!enabled);
    }

    #[tokio::test]
    async fn setup_requires_auth() {
        let (_ath, app) = test_app().await;

        let req = Request::builder()
            .method("POST")
            .uri("/mfa/setup")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let body = read_body(resp).await;
        assert_eq!(body["error"], "unauthenticated");
    }

    /// Helper: create user, enable MFA, return (user_id, TOTP instance, recovery_codes)
    async fn setup_mfa_user(ath: &AllowThem) -> (allowthem_core::types::UserId, TOTP, Vec<String>) {
        let email = Email::new("mfa-login@example.com".to_string()).unwrap();
        let user = ath
            .db()
            .create_user(email, "password123", None, None)
            .await
            .unwrap();

        let secret_b32 = ath.create_mfa_secret(user.id).await.unwrap();
        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Encoded(secret_b32).to_bytes().unwrap(),
            None,
            String::new(),
        )
        .unwrap();
        let code = totp.generate_current().unwrap();
        let recovery_codes = ath.enable_mfa(user.id, &code).await.unwrap();

        (user.id, totp, recovery_codes)
    }

    #[tokio::test]
    async fn verify_with_valid_totp_creates_session() {
        let (ath, app) = test_app().await;
        let (user_id, totp, _) = setup_mfa_user(&ath).await;

        let mfa_token = ath.db().create_mfa_challenge(user_id).await.unwrap();
        let code = totp.generate_current().unwrap();

        let req = Request::builder()
            .method("POST")
            .uri("/mfa/verify")
            .header("content-type", "application/json")
            .body(Body::from(format!(
                r#"{{"mfa_token":"{mfa_token}","code":"{code}"}}"#
            )))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        assert!(
            resp.headers().get("set-cookie").is_some(),
            "session cookie must be set"
        );
        let body = read_body(resp).await;
        assert_eq!(body["message"], "MFA verification successful");
    }

    #[tokio::test]
    async fn verify_with_wrong_code_fails() {
        let (ath, app) = test_app().await;
        let (user_id, _, _) = setup_mfa_user(&ath).await;

        let mfa_token = ath.db().create_mfa_challenge(user_id).await.unwrap();

        let req = Request::builder()
            .method("POST")
            .uri("/mfa/verify")
            .header("content-type", "application/json")
            .body(Body::from(format!(
                r#"{{"mfa_token":"{mfa_token}","code":"000000"}}"#
            )))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let body = read_body(resp).await;
        assert_eq!(body["error"], "invalid TOTP or recovery code");
    }

    #[tokio::test]
    async fn verify_with_invalid_token_fails() {
        let (_ath, app) = test_app().await;

        let req = Request::builder()
            .method("POST")
            .uri("/mfa/verify")
            .header("content-type", "application/json")
            .body(Body::from(
                r#"{"mfa_token":"garbage-token","code":"123456"}"#,
            ))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let body = read_body(resp).await;
        assert_eq!(body["error"], "invalid or expired MFA token");
    }

    #[tokio::test]
    async fn verify_with_recovery_code_creates_session() {
        let (ath, app) = test_app().await;
        let (user_id, _, recovery_codes) = setup_mfa_user(&ath).await;

        let mfa_token = ath.db().create_mfa_challenge(user_id).await.unwrap();

        let req = Request::builder()
            .method("POST")
            .uri("/mfa/verify")
            .header("content-type", "application/json")
            .body(Body::from(format!(
                r#"{{"mfa_token":"{mfa_token}","code":"{}"}}"#,
                recovery_codes[0]
            )))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        assert!(resp.headers().get("set-cookie").is_some());

        // Recovery code consumed
        let remaining = ath.db().remaining_recovery_codes(user_id).await.unwrap();
        assert_eq!(remaining, 9);
    }

    #[tokio::test]
    async fn verify_wrong_code_does_not_consume_challenge() {
        let (ath, _) = test_app().await;
        let (user_id, totp, _) = setup_mfa_user(&ath).await;

        let mfa_token = ath.db().create_mfa_challenge(user_id).await.unwrap();

        // First attempt: wrong code
        let challenge_user = ath.db().validate_mfa_challenge(&mfa_token).await.unwrap();
        assert!(
            challenge_user.is_some(),
            "challenge must exist before retry"
        );

        // Wrong code doesn't consume it — challenge still valid
        let still_valid = ath.db().validate_mfa_challenge(&mfa_token).await.unwrap();
        assert!(
            still_valid.is_some(),
            "challenge must survive failed verification"
        );

        // Now succeed with correct code
        let code = totp.generate_current().unwrap();
        let totp_valid = ath.verify_totp(user_id, &code).await.unwrap();
        assert!(totp_valid);
    }

    // --- M28: Recovery code routes ---

    #[tokio::test]
    async fn recover_with_valid_recovery_code_creates_session() {
        let (ath, app) = test_app().await;
        let (user_id, _, recovery_codes) = setup_mfa_user(&ath).await;

        let mfa_token = ath.db().create_mfa_challenge(user_id).await.unwrap();

        let req = Request::builder()
            .method("POST")
            .uri("/auth/mfa/recover")
            .header("content-type", "application/json")
            .body(Body::from(format!(
                r#"{{"mfa_token":"{mfa_token}","recovery_code":"{}"}}"#,
                recovery_codes[0]
            )))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        assert!(
            resp.headers().get("set-cookie").is_some(),
            "session cookie must be set"
        );
        let body = read_body(resp).await;
        assert_eq!(body["message"], "recovery successful");
        assert_eq!(body["remaining_recovery_codes"], 9);
    }

    #[tokio::test]
    async fn recover_with_invalid_code_fails() {
        let (ath, app) = test_app().await;
        let (user_id, _, _) = setup_mfa_user(&ath).await;

        let mfa_token = ath.db().create_mfa_challenge(user_id).await.unwrap();

        let req = Request::builder()
            .method("POST")
            .uri("/auth/mfa/recover")
            .header("content-type", "application/json")
            .body(Body::from(format!(
                r#"{{"mfa_token":"{mfa_token}","recovery_code":"ZZZZZZZZ"}}"#
            )))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let body = read_body(resp).await;
        assert_eq!(body["error"], "invalid recovery code");
    }

    #[tokio::test]
    async fn recover_with_already_used_code_fails() {
        let (ath, _) = test_app().await;
        let (user_id, _, recovery_codes) = setup_mfa_user(&ath).await;

        // Consume the code directly
        let consumed = ath
            .db()
            .verify_recovery_code(user_id, &recovery_codes[0])
            .await
            .unwrap();
        assert!(consumed);

        // Try to recover with the same consumed code
        let mfa_token = ath.db().create_mfa_challenge(user_id).await.unwrap();

        let app = mfa_routes("allowthem-test".into()).layer(axum::middleware::from_fn_with_state(
            ath.clone(),
            crate::cors::inject_ath_into_extensions,
        ));
        let req = Request::builder()
            .method("POST")
            .uri("/auth/mfa/recover")
            .header("content-type", "application/json")
            .body(Body::from(format!(
                r#"{{"mfa_token":"{mfa_token}","recovery_code":"{}"}}"#,
                recovery_codes[0]
            )))
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        let body = read_body(resp).await;
        assert_eq!(body["error"], "invalid recovery code");
    }

    #[tokio::test]
    async fn regenerate_returns_10_new_codes() {
        let (ath, app) = test_app().await;
        let (user_id, cookie) = create_user_session(&ath).await;

        // Setup and enable MFA
        let secret_b32 = ath.create_mfa_secret(user_id).await.unwrap();
        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Encoded(secret_b32).to_bytes().unwrap(),
            None,
            String::new(),
        )
        .unwrap();
        let code = totp.generate_current().unwrap();
        let old_codes = ath.enable_mfa(user_id, &code).await.unwrap();

        // Regenerate
        let req = Request::builder()
            .method("POST")
            .uri("/mfa/recovery-codes/regenerate")
            .header("cookie", &cookie)
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        let new_codes = body["recovery_codes"].as_array().unwrap();
        assert_eq!(new_codes.len(), 10);

        // Old codes should no longer work
        let old_valid = ath
            .db()
            .verify_recovery_code(user_id, &old_codes[0])
            .await
            .unwrap();
        assert!(
            !old_valid,
            "old codes must be invalidated after regeneration"
        );

        // New codes should work
        let new_code = new_codes[0].as_str().unwrap();
        let new_valid = ath
            .db()
            .verify_recovery_code(user_id, new_code)
            .await
            .unwrap();
        assert!(new_valid, "new codes must work");
    }

    #[tokio::test]
    async fn count_returns_remaining_codes() {
        let (ath, app) = test_app().await;
        let (user_id, cookie) = create_user_session(&ath).await;

        // Setup and enable MFA
        let secret_b32 = ath.create_mfa_secret(user_id).await.unwrap();
        let totp = TOTP::new(
            Algorithm::SHA1,
            6,
            1,
            30,
            Secret::Encoded(secret_b32).to_bytes().unwrap(),
            None,
            String::new(),
        )
        .unwrap();
        let code = totp.generate_current().unwrap();
        let recovery_codes = ath.enable_mfa(user_id, &code).await.unwrap();

        // Check initial count
        let req = Request::builder()
            .method("GET")
            .uri("/mfa/recovery-codes/count")
            .header("cookie", &cookie)
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();

        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        assert_eq!(body["remaining"], 10);

        // Consume one code
        ath.db()
            .verify_recovery_code(user_id, &recovery_codes[0])
            .await
            .unwrap();

        // Check count again (need a new app since oneshot consumed it)
        let app2 = mfa_routes("allowthem-test".into()).layer(axum::middleware::from_fn_with_state(
            ath.clone(),
            crate::cors::inject_ath_into_extensions,
        ));
        let req2 = Request::builder()
            .method("GET")
            .uri("/mfa/recovery-codes/count")
            .header("cookie", &cookie)
            .body(Body::empty())
            .unwrap();
        let resp2 = app2.oneshot(req2).await.unwrap();

        assert_eq!(resp2.status(), StatusCode::OK);
        let body2 = read_body(resp2).await;
        assert_eq!(body2["remaining"], 9);
    }
}