huskarl-login 0.2.2

OAuth2/OIDC login flow helpers for huskarl.
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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
use std::{
    convert::Infallible,
    sync::Mutex,
    time::{Duration, SystemTime},
};

use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use bytes::Bytes;
use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use huskarl::{
    core::{
        BoxedError,
        crypto::cipher::{AeadSealer, AeadV1Sealer, BoxedAeadCipher},
        http::{HttpClient, HttpResponse},
        secrets::{Secret, SecretBytes, SecretOutput},
    },
    grant::{
        authorization_code::{PendingState, StartOutput},
        core::TokenResponse,
    },
    token::RefreshToken,
};
use huskarl_crypto_native::aead::{AesGcmKey, AesGcmKeyType};

use super::{
    LoginEngine, SessionPersistence, error_chain, is_cors_preflight, is_navigation_request,
};
use crate::{
    LoginConfig, LoginGrant, Session, SessionDriver, SessionError, grant::CompletedLogin,
    session::sealed::Sealed,
};

// ── TestSecret / cipher ───────────────────────────────────────────────────

#[derive(Clone)]
struct TestSecret(SecretBytes);

impl Secret for TestSecret {
    type Output = SecretBytes;
    type Error = Infallible;
    async fn get_secret_value(&self) -> Result<SecretOutput<SecretBytes>, Infallible> {
        Ok(SecretOutput {
            value: self.0.clone(),
            identity: None,
        })
    }
}

async fn test_cipher() -> BoxedAeadCipher {
    let key = AesGcmKey::from_secret(
        AesGcmKeyType::Aes256,
        TestSecret(SecretBytes::new(vec![0u8; 32])),
        |_| None,
    )
    .await
    .unwrap();
    BoxedAeadCipher::new(key)
}

// ── MockHttpClient ────────────────────────────────────────────────────────

struct MockHttpResponse;

impl HttpResponse for MockHttpResponse {
    type Error = Infallible;
    fn status(&self) -> StatusCode {
        unimplemented!()
    }
    fn headers(&self) -> HeaderMap {
        unimplemented!()
    }
    async fn body(self) -> Result<Bytes, Infallible> {
        unimplemented!()
    }
}

struct MockHttpClient;

impl HttpClient for MockHttpClient {
    type Response = MockHttpResponse;
    type Error = Infallible;
    type ResponseError = Infallible;
    async fn execute(&self, _: http::Request<Bytes>) -> Result<MockHttpResponse, Infallible> {
        unimplemented!()
    }
}

// ── MockSession ───────────────────────────────────────────────────────────

struct MockSession {
    state: crate::SessionState,
}

impl Session for MockSession {
    fn state(&self) -> &crate::SessionState {
        &self.state
    }
    fn set_state(&mut self, s: crate::SessionState) {
        self.state = s;
    }
}

fn session_with(
    token_expiry: SystemTime,
    refresh_token: Option<RefreshToken>,
    created_at: SystemTime,
    last_active: SystemTime,
) -> MockSession {
    MockSession {
        state: crate::SessionState::builder()
            .token_expiry(token_expiry)
            .maybe_refresh_token(refresh_token)
            .created_at(created_at)
            .last_active(last_active)
            .build(),
    }
}

fn valid_session() -> MockSession {
    session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now(),
        SystemTime::now(),
    )
}

// ── MockSessionStore ──────────────────────────────────────────────────────

struct MockSessionStore {
    session: Mutex<Option<MockSession>>,
    save_called: Mutex<bool>,
    touch_called: Mutex<bool>,
    delete_called: Mutex<bool>,
}

impl MockSessionStore {
    fn with_session(s: MockSession) -> Self {
        Self {
            session: Mutex::new(Some(s)),
            save_called: Mutex::new(false),
            touch_called: Mutex::new(false),
            delete_called: Mutex::new(false),
        }
    }
    fn empty() -> Self {
        Self {
            session: Mutex::new(None),
            save_called: Mutex::new(false),
            touch_called: Mutex::new(false),
            delete_called: Mutex::new(false),
        }
    }
    fn save_called(&self) -> bool {
        *self.save_called.lock().unwrap()
    }
    fn touch_called(&self) -> bool {
        *self.touch_called.lock().unwrap()
    }
    fn delete_called(&self) -> bool {
        *self.delete_called.lock().unwrap()
    }
}

impl Sealed for MockSessionStore {}

impl SessionDriver for MockSessionStore {
    type SessionType = MockSession;
    type LoadError = Infallible;

    async fn create(
        &self,
        _: CompletedLogin,
        _: Duration,
        _: &HeaderMap,
    ) -> Result<(MockSession, Vec<HeaderValue>), SessionError> {
        unimplemented!()
    }
    async fn load(&self, _: &HeaderMap) -> Result<Option<MockSession>, Infallible> {
        Ok(self.session.lock().unwrap().take())
    }
    async fn save(&self, _: &MockSession, _: &HeaderMap) -> Result<Vec<HeaderValue>, SessionError> {
        *self.save_called.lock().unwrap() = true;
        Ok(vec![])
    }
    async fn touch(
        &self,
        _: &MockSession,
        _: &HeaderMap,
    ) -> Result<Vec<HeaderValue>, SessionError> {
        *self.touch_called.lock().unwrap() = true;
        Ok(vec![])
    }
    async fn delete(
        &self,
        _: &MockSession,
        _: &HeaderMap,
    ) -> Result<Vec<HeaderValue>, SessionError> {
        *self.delete_called.lock().unwrap() = true;
        Ok(vec![])
    }
}

// ── ErrorSessionStore — load always fails ─────────────────────────────────

#[derive(Debug)]
struct StoreLoadError;
impl std::fmt::Display for StoreLoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("store load error")
    }
}
impl std::error::Error for StoreLoadError {}

struct ErrorSessionStore;
impl Sealed for ErrorSessionStore {}
impl SessionDriver for ErrorSessionStore {
    type SessionType = MockSession;
    type LoadError = StoreLoadError;

    async fn create(
        &self,
        _: CompletedLogin,
        _: Duration,
        _: &HeaderMap,
    ) -> Result<(MockSession, Vec<HeaderValue>), SessionError> {
        unimplemented!()
    }
    async fn load(&self, _: &HeaderMap) -> Result<Option<MockSession>, StoreLoadError> {
        Err(StoreLoadError)
    }
    async fn save(&self, _: &MockSession, _: &HeaderMap) -> Result<Vec<HeaderValue>, SessionError> {
        unimplemented!()
    }
    async fn touch(
        &self,
        _: &MockSession,
        _: &HeaderMap,
    ) -> Result<Vec<HeaderValue>, SessionError> {
        unimplemented!()
    }
    async fn delete(
        &self,
        _: &MockSession,
        _: &HeaderMap,
    ) -> Result<Vec<HeaderValue>, SessionError> {
        unimplemented!()
    }
}

// ── MockGrant ─────────────────────────────────────────────────────────────

struct MockGrant {
    authorization_url: &'static str,
}

impl LoginGrant for MockGrant {
    async fn start(&self, _: &impl HttpClient, _: Vec<String>) -> Result<StartOutput, BoxedError> {
        Ok(StartOutput {
            authorization_url: self.authorization_url.parse().unwrap(),
            expires_in: None,
            pending_state: PendingState {
                redirect_uri: "https://app.example.com/callback".to_owned(),
                pkce_verifier: None,
                state: "mock_state".to_owned(),
                nonce: "mock_nonce".to_owned(),
                dpop_jkt: None,
            },
        })
    }

    async fn complete(
        &self,
        _: &impl HttpClient,
        _: &PendingState,
        _: String,
        _: String,
        _: Option<String>,
    ) -> Result<CompletedLogin, BoxedError> {
        Err(BoxedError::from_err("\0".parse::<http::Uri>().unwrap_err()))
    }

    // Note: constructing a successful TokenResponse requires huskarl's
    // pub(crate) RawTokenResponse::into_token_response, so only the failure
    // path is testable here. The success path (Continue { Save }) is covered
    // indirectly by the persist_session test with Save persistence.
    async fn refresh(
        &self,
        _: &impl HttpClient,
        _: &RefreshToken,
    ) -> Result<TokenResponse, BoxedError> {
        Err(BoxedError::from_err("\0".parse::<http::Uri>().unwrap_err()))
    }
}

// ── Engine / config helpers ───────────────────────────────────────────────

fn default_config() -> LoginConfig {
    LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .build()
        .unwrap()
}

fn config_with_logout() -> LoginConfig {
    LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .logout_path("/logout".to_owned())
        .build()
        .unwrap()
}

async fn engine(
    store: MockSessionStore,
) -> LoginEngine<MockGrant, MockSessionStore, MockHttpClient> {
    engine_with_config(store, default_config()).await
}

async fn engine_with_config(
    store: MockSessionStore,
    config: LoginConfig,
) -> LoginEngine<MockGrant, MockSessionStore, MockHttpClient> {
    LoginEngine::builder()
        .config(config)
        .grant(MockGrant {
            authorization_url: "https://auth.example.com/authorize",
        })
        .session_store(store)
        .cipher(test_cipher().await)
        .http_client(MockHttpClient)
        .build()
}

// ── Header / URI helpers ──────────────────────────────────────────────────

fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
    let mut map = HeaderMap::new();
    for (name, value) in pairs {
        map.insert(
            HeaderName::from_bytes(name.as_bytes()).unwrap(),
            HeaderValue::from_str(value).unwrap(),
        );
    }
    map
}

fn nav_headers() -> HeaderMap {
    headers(&[("sec-fetch-mode", "navigate")])
}

fn api_headers() -> HeaderMap {
    headers(&[("accept", "application/json")])
}

// ── Login-state cookie helper ─────────────────────────────────────────────

async fn seal_login_cookie(state: &str, original_url: &str) -> String {
    let cipher = test_cipher().await;
    let sealer = AeadV1Sealer::new(cipher);
    let cookie = super::LoginStateCookie {
        original_url: original_url.to_owned(),
        pending_state: PendingState {
            redirect_uri: "https://app.example.com/callback".to_owned(),
            pkce_verifier: None,
            state: state.to_owned(),
            nonce: "test_nonce".to_owned(),
            dpop_jkt: None,
        },
    };
    let payload = crate::cookie::encode_payload(&cookie).unwrap();
    let bundle = sealer.seal(&payload, state.as_bytes()).await.unwrap();
    URL_SAFE_NO_PAD.encode(&bundle)
}

fn headers_with_login_cookie(state: &str, value: &str) -> HeaderMap {
    let name = crate::cookie::login_state_cookie_name(
        state,
        true,
        "/callback",
        crate::cookie::DEFAULT_LOGIN_COOKIE_PREFIX,
    );
    headers(&[("cookie", &format!("{name}={value}"))])
}

// ── is_navigation_request ─────────────────────────────────────────────────

#[test]
fn xhr_header_returns_false() {
    assert!(!is_navigation_request(&headers(&[(
        "x-requested-with",
        "XMLHttpRequest"
    )])));
}

#[test]
fn xhr_header_is_case_insensitive() {
    assert!(!is_navigation_request(&headers(&[(
        "x-requested-with",
        "xmlhttprequest"
    )])));
}

#[test]
fn sec_fetch_mode_navigate_returns_true() {
    assert!(is_navigation_request(&headers(&[(
        "sec-fetch-mode",
        "navigate"
    )])));
}

#[test]
fn sec_fetch_mode_cors_returns_false() {
    assert!(!is_navigation_request(&headers(&[(
        "sec-fetch-mode",
        "cors"
    )])));
}

#[test]
fn sec_fetch_mode_no_cors_returns_false() {
    assert!(!is_navigation_request(&headers(&[(
        "sec-fetch-mode",
        "no-cors"
    )])));
}

#[test]
fn sec_fetch_dest_document_returns_true() {
    assert!(is_navigation_request(&headers(&[(
        "sec-fetch-dest",
        "document"
    )])));
}

#[test]
fn sec_fetch_dest_empty_returns_false() {
    assert!(!is_navigation_request(&headers(&[(
        "sec-fetch-dest",
        "empty"
    )])));
}

#[test]
fn sec_fetch_dest_image_returns_false() {
    assert!(!is_navigation_request(&headers(&[(
        "sec-fetch-dest",
        "image"
    )])));
}

#[test]
fn accept_text_html_returns_true() {
    assert!(is_navigation_request(&headers(&[(
        "accept",
        "text/html,application/xhtml+xml,*/*;q=0.8"
    )])));
}

#[test]
fn accept_xhtml_only_returns_true() {
    assert!(is_navigation_request(&headers(&[(
        "accept",
        "application/xhtml+xml"
    )])));
}

#[test]
fn accept_json_returns_false() {
    assert!(!is_navigation_request(&headers(&[(
        "accept",
        "application/json"
    )])));
}

#[test]
fn no_relevant_headers_returns_false() {
    assert!(!is_navigation_request(&HeaderMap::new()));
}

#[test]
fn xhr_overrides_sec_fetch_navigate() {
    let h = headers(&[
        ("x-requested-with", "XMLHttpRequest"),
        ("sec-fetch-mode", "navigate"),
    ]);
    assert!(!is_navigation_request(&h));
}

#[test]
fn sec_fetch_mode_overrides_accept() {
    let h = headers(&[("sec-fetch-mode", "cors"), ("accept", "text/html")]);
    assert!(!is_navigation_request(&h));
}

// ── error_chain ───────────────────────────────────────────────────────────

#[test]
fn error_chain_formats_single_error() {
    let err = "not-a-number".parse::<i32>().unwrap_err();
    let chain = error_chain(&err);
    assert!(!chain.is_empty());
    assert!(chain.contains("invalid digit"), "got: {chain}");
}

// ── Routing ───────────────────────────────────────────────────────────────

#[tokio::test]
async fn callback_path_is_handled() {
    let e = engine(MockSessionStore::empty()).await;
    let uri = "/callback".parse().unwrap();
    let resp = e
        .try_handle_login_route("/callback", &Method::GET, &HeaderMap::new(), &uri)
        .await;
    assert!(resp.is_some());
}

#[tokio::test]
async fn logout_path_is_handled_when_configured() {
    let e = engine_with_config(MockSessionStore::empty(), config_with_logout()).await;
    let uri = "/logout".parse().unwrap();
    let resp = e
        .try_handle_login_route("/logout", &Method::GET, &HeaderMap::new(), &uri)
        .await;
    assert!(resp.is_some());
}

#[tokio::test]
async fn logout_path_returns_none_when_unconfigured() {
    let e = engine(MockSessionStore::empty()).await;
    let uri = "/logout".parse().unwrap();
    let resp = e
        .try_handle_login_route("/logout", &Method::GET, &HeaderMap::new(), &uri)
        .await;
    assert!(resp.is_none());
}

#[test]
fn cors_preflight_is_detected() {
    let h = headers(&[("access-control-request-method", "POST")]);
    assert!(is_cors_preflight(&Method::OPTIONS, &h));
}

#[test]
fn options_without_acr_header_is_not_preflight() {
    assert!(!is_cors_preflight(&Method::OPTIONS, &api_headers()));
}

// ── Session management ────────────────────────────────────────────────────

#[tokio::test]
async fn redirect_to_login_navigation_returns_302() {
    let e = engine(MockSessionStore::empty()).await;
    let uri = "/protected".parse().unwrap();
    let r = e.redirect_to_login(&nav_headers(), &uri).await;
    assert_eq!(r.status, StatusCode::FOUND);
    let loc = r
        .headers
        .iter()
        .find(|(n, _)| *n == http::header::LOCATION)
        .map(|(_, v)| v.to_str().unwrap());
    assert_eq!(loc, Some("https://auth.example.com/authorize"));
}

#[tokio::test]
async fn redirect_to_login_navigation_sets_login_state_cookie() {
    let e = engine(MockSessionStore::empty()).await;
    let uri = "/protected".parse().unwrap();
    let r = e.redirect_to_login(&nav_headers(), &uri).await;
    let has_login_cookie = r.headers.iter().any(|(n, v)| {
        *n == http::header::SET_COOKIE && v.to_str().unwrap().contains("huskarl_login_")
    });
    assert!(has_login_cookie);
}

#[tokio::test]
async fn redirect_to_login_api_returns_401() {
    let e = engine(MockSessionStore::empty()).await;
    let uri = "/api/data".parse().unwrap();
    let r = e.redirect_to_login(&api_headers(), &uri).await;
    assert_eq!(r.status, StatusCode::UNAUTHORIZED);
}

#[tokio::test]
async fn load_session_empty_store_returns_none() {
    let e = engine(MockSessionStore::empty()).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_none());
    assert!(loaded.clear_cookies.is_empty());
}

#[tokio::test]
async fn load_session_valid_returns_skip_when_recently_active() {
    // last_active is "now" — well within the default 1h touch_min_interval.
    let e = engine(MockSessionStore::with_session(valid_session())).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    let (_session, persistence) = loaded.session.expect("session present");
    assert!(matches!(persistence, SessionPersistence::Skip));
    assert!(loaded.clear_cookies.is_empty());
}

#[tokio::test]
async fn load_session_valid_returns_touch_when_interval_elapsed() {
    // last_active is 2h ago — past the default 1h touch_min_interval.
    let session = session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now() - Duration::from_hours(2),
        SystemTime::now() - Duration::from_hours(2),
    );
    let e = engine(MockSessionStore::with_session(session)).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    let (_session, persistence) = loaded.session.expect("session present");
    assert!(matches!(persistence, SessionPersistence::Touch));
    assert!(loaded.clear_cookies.is_empty());
}

#[tokio::test]
async fn touch_min_interval_skips_recent_activity() {
    // last_active is "now" — well within a 60s touch_min_interval.
    let config = LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .touch_min_interval(Duration::from_mins(1))
        .build()
        .unwrap();
    let e = engine_with_config(MockSessionStore::with_session(valid_session()), config).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    let (_, persistence) = loaded.session.expect("session present");
    assert!(matches!(persistence, SessionPersistence::Skip));
}

#[tokio::test]
async fn touch_min_interval_touches_after_interval_elapsed() {
    // last_active is 120s ago — exceeds a 60s touch_min_interval.
    let session = session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now() - Duration::from_mins(2),
        SystemTime::now() - Duration::from_mins(2),
    );
    let config = LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .touch_min_interval(Duration::from_mins(1))
        .build()
        .unwrap();
    let e = engine_with_config(MockSessionStore::with_session(session), config).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    let (_, persistence) = loaded.session.expect("session present");
    assert!(matches!(persistence, SessionPersistence::Touch));
}

#[tokio::test]
async fn persist_skip_calls_neither_save_nor_touch() {
    let config = LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .touch_min_interval(Duration::from_mins(1))
        .build()
        .unwrap();
    let e = engine_with_config(MockSessionStore::with_session(valid_session()), config).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    let (session, persistence) = loaded.session.expect("session present");
    assert!(matches!(persistence, SessionPersistence::Skip));
    let headers = e
        .persist_session(&session, persistence, &api_headers())
        .await
        .unwrap();
    assert!(headers.is_empty());
    assert!(!e.session_store().save_called());
    assert!(!e.session_store().touch_called());
}

#[tokio::test]
async fn login_state_cookie_uses_configured_ttl() {
    let config = LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .login_state_ttl(Duration::from_mins(30))
        .build()
        .unwrap();
    let e = engine_with_config(MockSessionStore::empty(), config).await;
    let uri = "/protected".parse().unwrap();
    let r = e.redirect_to_login(&nav_headers(), &uri).await;
    let cookie = r
        .headers
        .iter()
        .find(|(n, v)| {
            *n == http::header::SET_COOKIE && v.to_str().unwrap().contains("huskarl_login_")
        })
        .expect("login-state cookie");
    assert!(cookie.1.to_str().unwrap().contains("Max-Age=1800"));
}

#[tokio::test]
async fn max_lifetime_expired_clears_session() {
    let session = session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now() - Duration::from_secs(7201),
        SystemTime::now(),
    );
    let config = LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .max_lifetime(Duration::from_hours(1))
        .build()
        .unwrap();
    let e = engine_with_config(MockSessionStore::with_session(session), config).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_none());
    assert!(e.session_store().delete_called());
}

#[tokio::test]
async fn idle_timeout_expired_clears_session() {
    let session = session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now(),
        SystemTime::now() - Duration::from_secs(1801),
    );
    let config = LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .idle_timeout(Duration::from_mins(15))
        .build()
        .unwrap();
    let store = MockSessionStore::with_session(session);
    let e = engine_with_config(store, config).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_none());
    assert!(e.session_store().delete_called());
}

#[tokio::test]
async fn token_expired_no_refresh_token_clears_session() {
    let session = session_with(
        SystemTime::now() - Duration::from_mins(1),
        None,
        SystemTime::now(),
        SystemTime::now(),
    );
    let store = MockSessionStore::with_session(session);
    let e = engine(store).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_none());
    assert!(e.session_store().delete_called());
}

#[tokio::test]
async fn token_expired_refresh_fails_clears_session() {
    use huskarl::core::secrets::SecretString;
    let session = session_with(
        SystemTime::now() - Duration::from_mins(1),
        Some(RefreshToken::new(SecretString::new("test_refresh"), None)),
        SystemTime::now(),
        SystemTime::now(),
    );
    let store = MockSessionStore::with_session(session);
    let e = engine(store).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_none());
    assert!(e.session_store().delete_called());
}

// ── Refresh retry ─────────────────────────────────────────────────────────

#[derive(Debug)]
struct FlakyError {
    retryable: bool,
}

impl std::fmt::Display for FlakyError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("flaky transport error")
    }
}

impl std::error::Error for FlakyError {}

impl huskarl::core::Error for FlakyError {
    fn is_retryable(&self) -> bool {
        self.retryable
    }
}

struct RetryGrant {
    refresh_calls: std::sync::atomic::AtomicU32,
    /// Number of leading attempts that should fail. The next attempt succeeds
    /// if a `token_response` is available, otherwise it keeps failing.
    fail_first_n: u32,
    retryable: bool,
}

impl RetryGrant {
    fn refresh_count(&self) -> u32 {
        self.refresh_calls.load(std::sync::atomic::Ordering::SeqCst)
    }
}

impl LoginGrant for RetryGrant {
    async fn start(&self, _: &impl HttpClient, _: Vec<String>) -> Result<StartOutput, BoxedError> {
        unimplemented!()
    }

    async fn complete(
        &self,
        _: &impl HttpClient,
        _: &PendingState,
        _: String,
        _: String,
        _: Option<String>,
    ) -> Result<CompletedLogin, BoxedError> {
        unimplemented!()
    }

    async fn refresh(
        &self,
        _: &impl HttpClient,
        _: &RefreshToken,
    ) -> Result<TokenResponse, BoxedError> {
        let attempt = self
            .refresh_calls
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst)
            + 1;
        if attempt <= self.fail_first_n {
            return Err(BoxedError::from_err(FlakyError {
                retryable: self.retryable,
            }));
        }
        // We never actually succeed in these tests — constructing a successful
        // TokenResponse requires huskarl-internal APIs. We assert call counts,
        // not the post-refresh Continue path.
        Err(BoxedError::from_err(FlakyError {
            retryable: self.retryable,
        }))
    }
}

async fn engine_with_retry_grant(
    grant: RetryGrant,
) -> LoginEngine<RetryGrant, MockSessionStore, MockHttpClient> {
    use huskarl::core::secrets::SecretString;
    let session = session_with(
        SystemTime::now() - Duration::from_mins(1),
        Some(RefreshToken::new(SecretString::new("test_refresh"), None)),
        SystemTime::now(),
        SystemTime::now(),
    );
    LoginEngine::builder()
        .config(default_config())
        .grant(grant)
        .session_store(MockSessionStore::with_session(session))
        .cipher(test_cipher().await)
        .http_client(MockHttpClient)
        .build()
}

#[tokio::test]
async fn refresh_retries_when_error_is_retryable() {
    let grant = RetryGrant {
        refresh_calls: std::sync::atomic::AtomicU32::new(0),
        fail_first_n: u32::MAX,
        retryable: true,
    };
    let e = engine_with_retry_grant(grant).await;
    let _ = e.load_session(&HeaderMap::new()).await;
    // Initial call + REFRESH_MAX_ATTEMPTS - 1 retries == REFRESH_MAX_ATTEMPTS total.
    assert_eq!(e.grant.refresh_count(), super::REFRESH_MAX_ATTEMPTS);
}

#[tokio::test]
async fn refresh_does_not_retry_when_error_is_non_retryable() {
    let grant = RetryGrant {
        refresh_calls: std::sync::atomic::AtomicU32::new(0),
        fail_first_n: u32::MAX,
        retryable: false,
    };
    let e = engine_with_retry_grant(grant).await;
    let _ = e.load_session(&HeaderMap::new()).await;
    // Non-retryable AS rejection (e.g. invalid_grant) must short-circuit at
    // the first attempt — retrying would just amplify load.
    assert_eq!(e.grant.refresh_count(), 1);
}

#[tokio::test]
async fn load_session_store_error_bubbles_up() {
    let e = LoginEngine::builder()
        .config(default_config())
        .grant(MockGrant {
            authorization_url: "https://auth.example.com/authorize",
        })
        .session_store(ErrorSessionStore)
        .cipher(test_cipher().await)
        .http_client(MockHttpClient)
        .build();
    let err = e.load_session(&HeaderMap::new()).await;
    assert!(err.is_err());
}

// ── persist_session ───────────────────────────────────────────────────────

#[tokio::test]
async fn persist_save_calls_store_save() {
    let e = engine(MockSessionStore::with_session(valid_session())).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    let (session, _) = loaded.session.expect("session present");
    e.persist_session(&session, SessionPersistence::Save, &api_headers())
        .await
        .unwrap();
    assert!(e.session_store().save_called());
    assert!(!e.session_store().touch_called());
}

#[tokio::test]
async fn persist_touch_calls_store_touch() {
    let e = engine(MockSessionStore::with_session(valid_session())).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    let (session, _) = loaded.session.expect("session present");
    e.persist_session(&session, SessionPersistence::Touch, &api_headers())
        .await
        .unwrap();
    assert!(e.session_store().touch_called());
    assert!(!e.session_store().save_called());
}

// ── Callback handler ──────────────────────────────────────────────────────

async fn callback_status(path_and_query: &str, request_headers: &HeaderMap) -> StatusCode {
    let e = engine(MockSessionStore::empty()).await;
    let uri = path_and_query.parse().unwrap();
    e.try_handle_login_route("/callback", &Method::GET, request_headers, &uri)
        .await
        .expect("callback handled")
        .status
}

#[tokio::test]
async fn callback_no_params_returns_400() {
    assert_eq!(
        callback_status("/callback", &HeaderMap::new()).await,
        StatusCode::BAD_REQUEST
    );
}

#[tokio::test]
async fn callback_missing_code_returns_400() {
    assert_eq!(
        callback_status("/callback?state=abc", &HeaderMap::new()).await,
        StatusCode::BAD_REQUEST
    );
}

#[tokio::test]
async fn callback_missing_state_returns_400() {
    assert_eq!(
        callback_status("/callback?code=authcode", &HeaderMap::new()).await,
        StatusCode::BAD_REQUEST
    );
}

#[tokio::test]
async fn callback_as_error_returns_403() {
    assert_eq!(
        callback_status("/callback?error=access_denied", &HeaderMap::new()).await,
        StatusCode::FORBIDDEN,
    );
}

#[tokio::test]
async fn callback_as_error_with_description_returns_403() {
    assert_eq!(
        callback_status(
            "/callback?error=access_denied&error_description=User+denied+access",
            &HeaderMap::new(),
        )
        .await,
        StatusCode::FORBIDDEN,
    );
}

#[tokio::test]
async fn callback_no_state_cookie_returns_400() {
    let status = callback_status("/callback?code=authcode&state=mystate", &HeaderMap::new()).await;
    assert_eq!(status, StatusCode::BAD_REQUEST);
}

#[tokio::test]
async fn callback_malformed_base64_cookie_returns_400() {
    let state = "teststate";
    let h = headers_with_login_cookie(state, "not-valid!!!base64");
    assert_eq!(
        callback_status(&format!("/callback?code=authcode&state={state}"), &h).await,
        StatusCode::BAD_REQUEST,
    );
}

#[tokio::test]
async fn callback_tampered_aead_bundle_returns_400() {
    let state = "teststate";
    let fake = URL_SAFE_NO_PAD.encode(b"this is not an AEAD ciphertext bundle");
    let h = headers_with_login_cookie(state, &fake);
    assert_eq!(
        callback_status(&format!("/callback?code=authcode&state={state}"), &h).await,
        StatusCode::BAD_REQUEST,
    );
}

#[tokio::test]
async fn callback_mismatched_state_aad_returns_400() {
    // Seal with AAD "right_state", present under state "wrong_state" — AEAD auth fails.
    let sealed = seal_login_cookie("right_state", "https://app.example.com/page").await;
    let wrong = "wrong_state";
    let h = headers_with_login_cookie(wrong, &sealed);
    assert_eq!(
        callback_status(&format!("/callback?code=authcode&state={wrong}"), &h).await,
        StatusCode::BAD_REQUEST,
    );
}

#[tokio::test]
async fn callback_valid_cookie_exchange_fails_returns_502() {
    let state = "valid_state";
    let sealed = seal_login_cookie(state, "https://app.example.com/page").await;
    let h = headers_with_login_cookie(state, &sealed);
    assert_eq!(
        callback_status(&format!("/callback?code=authcode&state={state}"), &h).await,
        StatusCode::BAD_GATEWAY,
    );
}

// ── Logout handler ────────────────────────────────────────────────────────

#[tokio::test]
async fn logout_without_session_redirects_to_base_url() {
    let e = engine_with_config(MockSessionStore::empty(), config_with_logout()).await;
    let uri = "/logout".parse().unwrap();
    let r = e
        .try_handle_login_route("/logout", &Method::GET, &HeaderMap::new(), &uri)
        .await
        .expect("logout handled");
    assert_eq!(r.status, StatusCode::FOUND);
    let loc = r
        .headers
        .iter()
        .find(|(n, _)| *n == http::header::LOCATION)
        .map(|(_, v)| v.to_str().unwrap());
    assert_eq!(loc, Some("https://app.example.com/"));
}

#[tokio::test]
async fn logout_with_session_deletes_session() {
    let e = engine_with_config(
        MockSessionStore::with_session(valid_session()),
        config_with_logout(),
    )
    .await;
    let uri = "/logout".parse().unwrap();
    let _ = e
        .try_handle_login_route("/logout", &Method::GET, &HeaderMap::new(), &uri)
        .await;
    assert!(e.session_store().delete_called());
}

#[tokio::test]
async fn logout_redirects_to_configured_post_logout_uri() {
    let config = LoginConfig::builder()
        .callback_path("/callback".to_owned())
        .scopes(vec![])
        .base_url("https://app.example.com".parse().unwrap())
        .logout_path("/logout".to_owned())
        .post_logout_redirect_uri("https://app.example.com/signed-out".to_owned())
        .build()
        .unwrap();
    let e = engine_with_config(MockSessionStore::empty(), config).await;
    let uri = "/logout".parse().unwrap();
    let r = e
        .try_handle_login_route("/logout", &Method::GET, &HeaderMap::new(), &uri)
        .await
        .expect("logout handled");
    let loc = r
        .headers
        .iter()
        .find(|(n, _)| *n == http::header::LOCATION)
        .map(|(_, v)| v.to_str().unwrap());
    assert_eq!(loc, Some("https://app.example.com/signed-out"));
}

// ── Clock-skew handling ───────────────────────────────────────────────────

#[tokio::test]
async fn small_future_skew_is_tolerated() {
    // last_active 10s in the future — within MAX_CLOCK_SKEW.
    let session = session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now(),
        SystemTime::now() + Duration::from_secs(10),
    );
    let e = engine(MockSessionStore::with_session(session)).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_some());
    assert!(!e.session_store().delete_called());
}

#[tokio::test]
async fn future_created_at_clears_session() {
    // created_at 1 hour in the future — well past MAX_CLOCK_SKEW.
    let session = session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now() + Duration::from_hours(1),
        SystemTime::now(),
    );
    let store = MockSessionStore::with_session(session);
    let e = engine(store).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_none());
    assert!(e.session_store().delete_called());
}

#[tokio::test]
async fn future_last_active_clears_session() {
    // last_active 1 hour in the future — well past MAX_CLOCK_SKEW.
    let session = session_with(
        SystemTime::now() + Duration::from_hours(1),
        None,
        SystemTime::now(),
        SystemTime::now() + Duration::from_hours(1),
    );
    let store = MockSessionStore::with_session(session);
    let e = engine(store).await;
    let loaded = e.load_session(&HeaderMap::new()).await.unwrap();
    assert!(loaded.session.is_none());
    assert!(e.session_store().delete_called());
}