oauth2-passkey 0.6.0

OAuth2 and Passkey authentication library for Rust web applications
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
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
use super::*;
use crate::storage::CacheData;
use http::HeaderValue;

// Test helper function to replace the removed store_token_in_cache function
async fn store_token_in_cache(
    token_type: &str,
    token: &str,
    ttl: u64,
    expires_at: DateTime<Utc>,
    user_agent: Option<String>,
) -> Result<String, OAuth2Error> {
    let stored_token = StoredToken {
        token: token.to_string(),
        expires_at,
        user_agent,
        ttl,
    };

    let cache_prefix =
        CachePrefix::new(token_type.to_string()).map_err(OAuth2Error::convert_storage_error)?;

    Ok(
        store_cache_auto::<_, OAuth2Error>(cache_prefix, stored_token, ttl)
            .await?
            .as_str()
            .to_string(),
    )
}

/// Test state parameter encoding and decoding roundtrip
///
/// This test verifies that StateParams can be encoded to base64url format and decoded back
/// to the original values, ensuring the serialization roundtrip maintains data integrity.
/// It creates a StateParams object in memory with all fields populated, encodes it,
/// validates the base64url format, then decodes and verifies all fields match.
///
#[test]
fn test_encode_decode_state() {
    // Create a state params object with all fields populated
    let state_params = StateParams {
        csrf_id: "csrf123".to_string(),
        nonce_id: "nonce456".to_string(),
        pkce_id: "pkce789".to_string(),
        misc_id: Some("misc123".to_string()),
        mode_id: Some("mode456".to_string()),
        provider: "google".to_string(),
    };

    // Encode the state
    let encoded = encode_state(state_params).unwrap();

    // Verify the encoded state is a valid base64url string
    assert!(!encoded.contains('+'));
    assert!(!encoded.contains('/'));
    assert!(!encoded.contains('='));

    // Decode the state
    let decoded = decode_state(&encoded).unwrap();

    // Verify all fields match the original
    assert_eq!(decoded.csrf_id, "csrf123");
    assert_eq!(decoded.nonce_id, "nonce456");
    assert_eq!(decoded.pkce_id, "pkce789");
    assert_eq!(decoded.misc_id, Some("misc123".to_string()));
    assert_eq!(decoded.mode_id, Some("mode456".to_string()));
    assert_eq!(decoded.provider, "google");
}

/// Test state parameter encoding and decoding with minimal fields
///
/// This test verifies that StateParams encoding and decoding works correctly when only
/// required fields are populated and optional fields are None. It creates a StateParams
/// object in memory with minimal data, encodes it to base64url, decodes it back, and
/// verifies all fields including the None values are preserved correctly.
///
#[test]
fn test_encode_decode_state_minimal() {
    // Create a state params object with only required fields
    let state_params = StateParams {
        csrf_id: "csrf123".to_string(),
        nonce_id: "nonce456".to_string(),
        pkce_id: "pkce789".to_string(),
        misc_id: None,
        mode_id: None,
        provider: "google".to_string(),
    };

    // Encode the state
    let encoded = encode_state(state_params).unwrap();

    // Decode the state
    let decoded = decode_state(&encoded).unwrap();

    // Verify all fields match the original
    assert_eq!(decoded.csrf_id, "csrf123");
    assert_eq!(decoded.nonce_id, "nonce456");
    assert_eq!(decoded.pkce_id, "pkce789");
    assert_eq!(decoded.misc_id, None);
    assert_eq!(decoded.mode_id, None);
}

/// Test OAuth2State validation with invalid base64 input
///
/// This test verifies that `OAuth2State::new` returns an appropriate error
/// when given a string that contains invalid base64 characters. This tests the validation
/// boundary where external data is converted to a type-safe OAuth2State.
///
#[test]
fn test_oauth2_state_validation_invalid_base64() {
    // Try to create an OAuth2State from invalid base64 string
    let result = crate::OAuth2State::new("this is not base64!!!".to_string());

    // Verify it returns an error
    assert!(result.is_err());
    match result {
        Err(OAuth2Error::DecodeState(_)) => {}
        Ok(_) => {
            unreachable!("Expected DecodeState error but got Ok");
        }
        Err(err) => {
            unreachable!("Expected DecodeState error, got {:?}", err);
        }
    }
}

/// Test OAuth2State validation with invalid JSON payload
///
/// This test verifies that `OAuth2State::new` returns an appropriate error
/// when given valid base64 that contains invalid JSON. This tests the validation
/// boundary where external data is converted to a type-safe OAuth2State.
///
#[test]
fn test_oauth2_state_validation_invalid_json() {
    // Encode some invalid JSON
    let invalid_json = "not valid json";
    let encoded = URL_SAFE_NO_PAD.encode(invalid_json);

    // Try to create OAuth2State from invalid JSON (valid base64)
    let result = crate::OAuth2State::new(encoded);

    // Verify it returns an error
    assert!(result.is_err());
    match result {
        Err(OAuth2Error::DecodeState(_)) => {}
        Ok(_) => {
            unreachable!("Expected DecodeState error but got Ok");
        }
        Err(err) => {
            unreachable!("Expected DecodeState error, got {:?}", err);
        }
    }
}

/// Test successful origin validation with matching origin header
///
/// This test verifies that `validate_origin` succeeds when the Origin header
/// in the request matches the expected origin derived from the callback URL.
/// It creates HTTP headers with a matching origin and validates against a
/// callback URL from the same origin.
///
#[tokio::test]
async fn test_validate_origin_success() {
    // Create headers with matching origin
    let mut headers = HeaderMap::new();
    headers.insert("Origin", HeaderValue::from_static("https://example.com"));

    // Validate against matching URL
    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;

    // Should succeed
    assert!(result.is_ok());
}

/// Test origin validation fallback to Referer header
///
/// This test verifies that `validate_origin` can successfully validate using the
/// Referer header when no Origin header is present. It creates HTTP headers with
/// only a Referer header and validates that the origin is correctly extracted
/// from the referer URL and matches the expected callback URL origin.
///
#[tokio::test]
async fn test_validate_origin_with_referer() {
    // Create headers with matching referer but no origin
    let mut headers = HeaderMap::new();
    headers.insert(
        "Referer",
        HeaderValue::from_static("https://example.com/login"),
    );

    // Validate against matching URL
    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;

    // Should succeed
    assert!(result.is_ok());
}

/// Test origin validation when Origin header is the literal string "null"
///
/// Browsers send `Origin: null` for cross-origin form_post redirects.
/// The function should fall back to the Referer header in this case.
#[tokio::test]
async fn test_validate_origin_null_with_referer() {
    let mut headers = HeaderMap::new();
    headers.insert("Origin", HeaderValue::from_static("null"));
    headers.insert(
        "Referer",
        HeaderValue::from_static("https://example.com/login"),
    );

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(
        result.is_ok(),
        "Origin: null should fall back to matching Referer"
    );
}

/// Test origin validation when Origin is "null" and no Referer is present
///
/// When Origin is "null" and there is no Referer to fall back to, validation
/// must still reject the request.
#[tokio::test]
async fn test_validate_origin_null_without_referer() {
    let mut headers = HeaderMap::new();
    headers.insert("Origin", HeaderValue::from_static("null"));

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(result.is_err());
    match result {
        Err(OAuth2Error::InvalidOrigin(_)) => {}
        Ok(_) => unreachable!("Expected InvalidOrigin error but got Ok"),
        Err(err) => unreachable!("Expected InvalidOrigin error, got {:?}", err),
    }
}

/// Subdomain-confusion attacker host must not match expected origin.
///
/// `https://example.com.attacker.example/...` previously satisfied
/// `starts_with("https://example.com")` because the next character was a
/// valid host-segment byte. Structural origin comparison rejects it.
#[tokio::test]
async fn test_validate_origin_rejects_subdomain_confusion() {
    let mut headers = HeaderMap::new();
    headers.insert(
        "Origin",
        HeaderValue::from_static("https://example.com.attacker.example"),
    );

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(
        result.is_err(),
        "subdomain-confusion Origin must be rejected"
    );
}

/// Same defense, exercised via the Referer fallback path.
#[tokio::test]
async fn test_validate_origin_rejects_subdomain_confusion_via_referer() {
    let mut headers = HeaderMap::new();
    headers.insert(
        "Referer",
        HeaderValue::from_static("https://example.com.attacker.example/path"),
    );

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(
        result.is_err(),
        "subdomain-confusion Referer must be rejected"
    );
}

/// `additional_allowed_origins` entries must also resist subdomain confusion.
/// Mirrors the Entra preset path where `https://login.live.com` is registered
/// as an extra allowed origin.
#[tokio::test]
async fn test_validate_origin_rejects_subdomain_confusion_in_additional() {
    let mut headers = HeaderMap::new();
    headers.insert(
        "Origin",
        HeaderValue::from_static("https://login.live.com.attacker.example"),
    );

    let result = validate_origin(
        &headers,
        "https://example.com/oauth2/callback",
        &["https://login.live.com".to_string()],
    )
    .await;
    assert!(
        result.is_err(),
        "subdomain confusion against additional_allowed_origins must be rejected"
    );
}

/// RFC 3986: scheme and host are case-insensitive. Different casing must match.
#[tokio::test]
async fn test_validate_origin_case_insensitive_host() {
    let mut headers = HeaderMap::new();
    headers.insert("Origin", HeaderValue::from_static("https://EXAMPLE.com"));

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(result.is_ok(), "case-insensitive host must match");
}

/// Explicit default port must match the implicit form (https:443).
#[tokio::test]
async fn test_validate_origin_default_port_normalization() {
    let mut headers = HeaderMap::new();
    headers.insert(
        "Origin",
        HeaderValue::from_static("https://example.com:443"),
    );

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(
        result.is_ok(),
        "explicit default port :443 must match implicit form"
    );
}

/// Non-default port mismatch must be rejected.
#[tokio::test]
async fn test_validate_origin_different_port_rejected() {
    let mut headers = HeaderMap::new();
    headers.insert(
        "Origin",
        HeaderValue::from_static("https://example.com:8443"),
    );

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(result.is_err(), "different port must not match");
}

/// Malformed Referer must be rejected, not treated as a wildcard match.
#[tokio::test]
async fn test_validate_origin_invalid_url_rejected() {
    let mut headers = HeaderMap::new();
    headers.insert("Referer", HeaderValue::from_static("not-a-url"));

    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;
    assert!(result.is_err(), "unparseable candidate must be rejected");
}

/// An unparseable entry in `additional_allowed_origins` must be silently
/// dropped (fail-closed): it neither matches anything nor short-circuits
/// the check, and a sibling valid entry still works.
#[tokio::test]
async fn test_validate_origin_unparseable_additional_origin_dropped() {
    let mut headers = HeaderMap::new();
    headers.insert("Origin", HeaderValue::from_static("https://login.live.com"));

    let result = validate_origin(
        &headers,
        "https://example.com/oauth2/callback",
        &[
            "not-a-valid-url".to_string(),
            "https://login.live.com".to_string(),
        ],
    )
    .await;
    assert!(
        result.is_ok(),
        "valid sibling allowed origin must still match when an unparseable entry is present"
    );

    // And the unparseable entry on its own does not authorize anything.
    let mut headers2 = HeaderMap::new();
    headers2.insert(
        "Origin",
        HeaderValue::from_static("https://attacker.example"),
    );
    let result2 = validate_origin(
        &headers2,
        "https://example.com/oauth2/callback",
        &["not-a-valid-url".to_string()],
    )
    .await;
    assert!(
        result2.is_err(),
        "unparseable additional_allowed_origins entry must not authorize anything"
    );
}

/// Tests for validate_origin with mismatched origin
///
/// This test verifies that `validate_origin` correctly validates an origin
/// when given a valid origin. It performs the following steps:
/// 1. Initializes a test environment
/// 2. Creates a test origin directly in the database
/// 3. Calls `validate_origin` to validate the origin
/// 4. Verifies that the origin was successfully validated
///
#[tokio::test]
async fn test_validate_origin_mismatch() {
    // Create headers with non-matching origin
    let mut headers = HeaderMap::new();
    headers.insert("Origin", HeaderValue::from_static("https://attacker.com"));

    // Validate against different URL
    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;

    // Should fail
    assert!(result.is_err());
    match result {
        Err(OAuth2Error::InvalidOrigin(_)) => {}
        Ok(_) => {
            unreachable!("Expected InvalidOrigin error but got Ok");
        }
        Err(err) => {
            unreachable!("Expected InvalidOrigin error, got {:?}", err);
        }
    }
}

/// Tests for validate_origin with missing origin
///
/// This test verifies that `validate_origin` correctly validates an origin
/// when given a valid origin. It performs the following steps:
/// 1. Initializes a test environment
/// 2. Creates a test origin directly in the database
/// 3. Calls `validate_origin` to validate the origin
/// 4. Verifies that the origin was successfully validated
///
#[tokio::test]
async fn test_validate_origin_missing() {
    // Create headers with no origin or referer
    let headers = HeaderMap::new();

    // Validate against URL
    let result = validate_origin(&headers, "https://example.com/oauth2/callback", &[]).await;

    // Should fail
    assert!(result.is_err());
    match result {
        Err(OAuth2Error::InvalidOrigin(_)) => {}
        Ok(_) => {
            unreachable!("Expected InvalidOrigin error but got Ok");
        }
        Err(err) => {
            unreachable!("Expected InvalidOrigin error, got {:?}", err);
        }
    }
}

/// Test origin validation accepts an origin listed in `additional_allowed_origins`
///
/// Providers like Microsoft Entra B2C route credential entry through a different
/// host than the OIDC endpoints (e.g. `login.live.com` vs `login.microsoftonline.com`),
/// so the Referer on the `form_post` callback is that alternate host. The provider
/// config declares it via `additional_allowed_origins`, and `validate_origin` must
/// accept it even though it doesn't match the authorization endpoint's origin.
#[tokio::test]
async fn test_validate_origin_additional_allowed() {
    let mut headers = HeaderMap::new();
    headers.insert("Origin", HeaderValue::from_static("null"));
    headers.insert(
        "Referer",
        HeaderValue::from_static("https://login.live.com/oauth20_authorize.srf"),
    );

    let allowed = vec!["https://login.live.com".to_string()];
    let result = validate_origin(
        &headers,
        "https://login.microsoftonline.com/common/oauth2/v2.0/token",
        &allowed,
    )
    .await;

    assert!(
        result.is_ok(),
        "Referer on an additional_allowed_origins host should be accepted"
    );
}

/// Test token storage and retrieval roundtrip in cache
///
/// This test verifies that tokens can be stored in the cache system and then successfully
/// retrieved with all metadata intact. It configures an in-memory cache, stores a token
/// with TTL and user agent information, retrieves it, and validates that all fields
/// including expiration time are preserved correctly.
///
#[tokio::test]
async fn test_store_and_get_token_from_cache() {
    use crate::test_utils::init_test_environment;
    use chrono::{Duration, Utc};
    init_test_environment().await;

    // Create test data
    let token_type = "test_token";
    let token = "test_token_value_12345";
    let ttl = 300; // 5 minutes
    let expires_at = Utc::now() + Duration::seconds(ttl as i64);
    let user_agent = Some("Test User Agent".to_string());

    // Store the token
    let result = store_token_in_cache(token_type, token, ttl, expires_at, user_agent.clone()).await;
    assert!(result.is_ok(), "Should successfully store token");
    let token_id = result.unwrap();

    // Verify token_id is generated (should be non-empty and deterministic length based on base64url encoding of 32 bytes)
    assert!(!token_id.is_empty(), "Token ID should not be empty");
    // 32 bytes base64url encoded = approximately 43 characters
    assert_eq!(
        token_id.len(),
        43,
        "Token ID should be 43 characters long (32 bytes base64url encoded)"
    );

    // Retrieve the token
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let retrieved_result = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
        .await
        .and_then(|opt| {
            opt.ok_or_else(|| {
                OAuth2Error::SecurityTokenNotFound("test_type-session not found".to_string())
            })
        });
    assert!(
        retrieved_result.is_ok(),
        "Should successfully retrieve token"
    );

    let stored_token = retrieved_result.unwrap();
    assert_eq!(stored_token.token, token);
    assert_eq!(stored_token.user_agent, user_agent);
    assert_eq!(stored_token.ttl, ttl);

    // Verify expires_at is preserved (within 1 second tolerance)
    let time_diff = (stored_token.expires_at - expires_at).num_seconds();
    assert!(time_diff.abs() < 1, "Expiration time should be preserved");
}

/// Test get_token_from_store behavior when token doesn't exist
///
/// This test verifies that `get_token_from_store` returns the appropriate SecurityTokenNotFound
/// error when attempting to retrieve a token that doesn't exist in the cache. It configures
/// an in-memory cache, attempts to retrieve a non-existent token, and validates that the
/// correct error type and message are returned.
///
#[tokio::test]
async fn test_get_token_from_store_not_found() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    // Try to get a token that doesn't exist
    let cache_prefix = CachePrefix::new("test_type".to_string()).unwrap();
    let cache_key = CacheKey::new("nonexistent_id".to_string()).unwrap();
    let result = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
        .await
        .and_then(|opt| {
            opt.ok_or_else(|| {
                OAuth2Error::SecurityTokenNotFound("test-session not found".to_string())
            })
        });

    // Verify it returns SecurityTokenNotFound error
    assert!(result.is_err());
    match result {
        Err(OAuth2Error::SecurityTokenNotFound(msg)) => {
            assert!(msg.contains("test-session not found"));
        }
        Ok(_) => {
            unreachable!("Expected SecurityTokenNotFound error but got Ok");
        }
        Err(err) => {
            unreachable!("Expected SecurityTokenNotFound error, got {:?}", err);
        }
    }
}

/// Test token removal from cache store using direct cache API
///
/// This test verifies that `remove_data` can successfully remove a token
/// from the cache. It configures an in-memory cache, stores a token, verifies it exists,
/// removes it, and then confirms the token is no longer retrievable, returning the
/// appropriate SecurityTokenNotFound error.
///
#[tokio::test]
async fn test_remove_token_from_store() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = "test_remove";
    let token_value = "test_token_value";
    let ttl = 300; // 5 minutes
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = Some("test-agent".to_string());

    // Store a token first
    let token_id =
        store_token_in_cache(token_type, token_value, ttl, expires_at, user_agent.clone())
            .await
            .unwrap();

    // Verify the token was stored
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let stored_token = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_token.token, token_value);

    // Remove the token
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let result = remove_data::<OAuth2Error>(cache_prefix, cache_key).await;
    assert!(result.is_ok());

    // Verify the token is no longer available
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let get_result = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
        .await
        .and_then(|opt| {
            opt.ok_or_else(|| {
                OAuth2Error::SecurityTokenNotFound("test-session not found".to_string())
            })
        });
    assert!(get_result.is_err());
    match get_result {
        Err(OAuth2Error::SecurityTokenNotFound(_)) => {}
        Ok(_) => {
            unreachable!("Expected SecurityTokenNotFound error after removal but got Ok");
        }
        Err(err) => {
            unreachable!(
                "Expected SecurityTokenNotFound error after removal, got {:?}",
                err
            );
        }
    }
}

/// Test token generation and storage functionality
///
/// This test verifies that `generate_store_token` can generate a secure random token,
/// store it in the cache with metadata, and return both the token and token ID.
/// It validates that both generated values have the expected length, are different
/// from each other, and that the stored token can be retrieved with correct metadata.
///
#[tokio::test]
async fn test_generate_store_token() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = TokenType::Csrf;
    let ttl = 600; // 10 minutes
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = Some("test-generate-agent".to_string());

    // Generate and store a token
    let result = generate_store_token(token_type, ttl, expires_at, user_agent.clone()).await;
    assert!(result.is_ok());

    let (token, token_id) = result.unwrap();

    // Verify both token and token_id are generated with expected lengths
    assert_eq!(
        token.len(),
        43,
        "Generated token should be 43 characters long"
    );
    assert_eq!(
        token_id.len(),
        43,
        "Generated token_id should be 43 characters long"
    );

    // Verify token and token_id are different
    assert_ne!(token, token_id, "Token and token_id should be different");

    // Verify the token can be retrieved from storage
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let stored_token = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(stored_token.token, token);
    assert_eq!(stored_token.user_agent, user_agent);
    assert_eq!(stored_token.ttl, ttl);

    // Verify expires_at is preserved (within 1 second tolerance)
    let time_diff = (stored_token.expires_at - expires_at).num_seconds();
    assert!(time_diff.abs() < 1, "Expiration time should be preserved");
}

/// Test token generation randomness and uniqueness
///
/// This test verifies that `generate_store_token` generates unique, random tokens
/// on each invocation. It generates multiple tokens and validates that all generated
/// tokens and token IDs are unique, ensuring the cryptographic randomness is working
/// correctly and preventing token collisions.
///
#[tokio::test]
async fn test_generate_store_token_randomness() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = TokenType::Nonce;
    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = None;

    // Generate multiple tokens to verify randomness
    let (token1, token_id1) = generate_store_token(token_type, ttl, expires_at, user_agent.clone())
        .await
        .unwrap();
    let (token2, token_id2) = generate_store_token(token_type, ttl, expires_at, user_agent.clone())
        .await
        .unwrap();

    // Verify tokens are different (randomness check)
    assert_ne!(token1, token2, "Generated tokens should be different");
    assert_ne!(
        token_id1, token_id2,
        "Generated token IDs should be different"
    );

    // Verify both tokens can be retrieved independently
    let cache_prefix1 = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key1 = CacheKey::new(token_id1.clone()).unwrap();
    let cache_prefix2 = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key2 = CacheKey::new(token_id2.clone()).unwrap();
    let stored_token1 = get_data::<StoredToken, OAuth2Error>(cache_prefix1, cache_key1)
        .await
        .unwrap()
        .unwrap();
    let stored_token2 = get_data::<StoredToken, OAuth2Error>(cache_prefix2, cache_key2)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(stored_token1.token, token1);
    assert_eq!(stored_token2.token, token2);
}

/// Test get_uid_from_stored_session behavior when misc_id is None
///
/// This test verifies that `get_uid_from_stored_session_by_state_param` returns Ok(None)
/// when the StateParams has no misc_id field set. It creates StateParams without a misc_id
/// and validates that the function correctly handles this case by returning None rather
/// than attempting to retrieve a session.
///
#[tokio::test]
async fn test_get_uid_from_stored_session_no_misc_id() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    // Create state params without misc_id
    let state_params = StateParams {
        csrf_id: "csrf123".to_string(),
        nonce_id: "nonce456".to_string(),
        pkce_id: "pkce789".to_string(),
        misc_id: None,
        mode_id: None,
        provider: "google".to_string(),
    };

    // Call the function
    let result = get_uid_from_stored_session_by_state_param(&state_params).await;

    // Should return Ok(None) when misc_id is None
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

/// Test get_uid_from_stored_session behavior when token is not found
///
/// This test verifies that `get_uid_from_stored_session_by_state_param` returns Ok(None)
/// when the misc_id token doesn't exist in the cache. It configures an in-memory cache,
/// creates StateParams with a misc_id that doesn't correspond to any stored token,
/// and validates that the function handles the missing token gracefully.
///
#[tokio::test]
async fn test_get_uid_from_stored_session_token_not_found() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    // Create state params with misc_id pointing to non-existent token
    let state_params = StateParams {
        csrf_id: "csrf123".to_string(),
        nonce_id: "nonce456".to_string(),
        pkce_id: "pkce789".to_string(),
        misc_id: Some("nonexistent_misc_id".to_string()),
        mode_id: None,
        provider: "google".to_string(),
    };

    // Call the function
    let result = get_uid_from_stored_session_by_state_param(&state_params).await;

    // Should return Ok(None) when token is not found in cache
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

/// Test delete_session_and_misc_token behavior when misc_id is None
///
/// This test verifies that `delete_session_and_misc_token_from_store` successfully returns
/// Ok(()) when the StateParams has no misc_id field set. It creates StateParams without
/// a misc_id and validates that the function handles this case gracefully without attempting
/// to delete a non-existent token.
///
#[tokio::test]
async fn test_delete_session_and_misc_token_no_misc_id() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    // Create state params without misc_id
    let state_params = StateParams {
        csrf_id: "csrf123".to_string(),
        nonce_id: "nonce456".to_string(),
        pkce_id: "pkce789".to_string(),
        misc_id: None,
        mode_id: None,
        provider: "google".to_string(),
    };

    // Call the function
    let result = delete_session_and_misc_token_from_store(&state_params).await;

    // Should return Ok(()) when misc_id is None
    assert!(result.is_ok());
}

/// Test delete_session_and_misc_token behavior when token doesn't exist
///
/// This test verifies that `delete_session_and_misc_token_from_store` successfully returns
/// Ok(()) even when the misc_id points to a non-existent token in the cache. It configures
/// an in-memory cache, creates StateParams with a misc_id that doesn't exist, and validates
/// that the function handles missing tokens gracefully.
///
#[tokio::test]
async fn test_delete_session_and_misc_token_token_not_found() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    // Create state params with misc_id pointing to non-existent token
    let state_params = StateParams {
        csrf_id: "csrf123".to_string(),
        nonce_id: "nonce456".to_string(),
        pkce_id: "pkce789".to_string(),
        misc_id: Some("nonexistent_misc_id".to_string()),
        mode_id: None,
        provider: "google".to_string(),
    };

    // Call the function
    let result = delete_session_and_misc_token_from_store(&state_params).await;

    // Should return Ok(()) when token is not found in cache (graceful handling)
    assert!(result.is_ok());
}

/// Tests for get_mode_from_stored_session_not_found
///
/// This test verifies that `get_mode_from_stored_session_not_found` correctly retrieves a mode
/// when given a valid mode. It performs the following steps:
/// 1. Initializes a test environment
/// 2. Creates a test mode directly in the database
/// 3. Calls `get_mode_from_stored_session_not_found` to retrieve the mode
/// 4. Verifies that the mode was successfully retrieved
///
#[tokio::test]
async fn test_get_mode_from_stored_session_not_found() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    // Call the function with a non-existent mode_id
    let result = get_mode_from_stored_session("nonexistent_mode_id").await;

    // Should return Ok(None) when mode token is not found in cache
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

/// Test successful mode retrieval from stored session
///
/// This test verifies that `get_mode_from_stored_session` can successfully retrieve and
/// parse an OAuth2Mode from the cache when given a valid mode token ID. It stores a
/// mode token in the cache, retrieves it using the mode ID, and validates that the
/// correct OAuth2Mode value is returned.
///
#[tokio::test]
async fn test_get_mode_from_stored_session_valid_mode() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let mode_type = "mode";
    let mode = OAuth2Mode::Login;
    let mode_value = mode.as_str(); // Use as_str() to get valid string representation
    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = None;

    // Store a mode token
    let mode_id = store_token_in_cache(mode_type, mode_value, ttl, expires_at, user_agent)
        .await
        .unwrap();

    // Call the function
    let result = get_mode_from_stored_session(&mode_id).await;

    // Should return Ok(Some(OAuth2Mode::Login))
    assert!(result.is_ok());
    let retrieved_mode = result.unwrap();
    assert!(retrieved_mode.is_some());

    // Verify it's the correct mode using PartialEq
    assert_eq!(retrieved_mode.unwrap(), mode);
}

/// Test mode retrieval with invalid mode value
///
/// This test verifies that `get_mode_from_stored_session` returns Ok(None) when the
/// stored token contains an invalid OAuth2Mode value that cannot be parsed. It stores
/// an invalid mode string in the cache, attempts to retrieve and parse it, and validates
/// that the function handles the parsing failure gracefully.
///
#[tokio::test]
async fn test_get_mode_from_stored_session_invalid_mode() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let mode_type = "mode";
    let invalid_mode_value = "invalid_mode_value"; // Invalid OAuth2Mode value
    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = None;

    // Store an invalid mode token
    let mode_id = store_token_in_cache(mode_type, invalid_mode_value, ttl, expires_at, user_agent)
        .await
        .unwrap();

    // Call the function
    let result = get_mode_from_stored_session(&mode_id).await;

    // Should return Ok(None) when mode value is invalid
    assert!(result.is_ok());
    assert!(result.unwrap().is_none());
}

/// Test token caching with zero TTL (immediate expiration)
///
/// This test verifies that `store_token_in_cache` can handle tokens with zero TTL
/// and immediate expiration times. It stores a token with zero TTL, retrieves it,
/// and validates that the token is stored with the correct expiration metadata,
/// even when already expired at storage time.
///
#[tokio::test]
async fn test_cache_token_with_zero_ttl() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = "test_zero_ttl";
    let token = "test_token_zero_ttl";
    let ttl = 0; // Zero TTL
    let expires_at = Utc::now(); // Immediate expiration
    let user_agent = Some("test-agent".to_string());

    // Store token with zero TTL
    let result = store_token_in_cache(token_type, token, ttl, expires_at, user_agent.clone()).await;
    assert!(
        result.is_ok(),
        "Should successfully store token with zero TTL"
    );

    let token_id = result.unwrap();

    // Should still be able to retrieve it immediately (cache doesn't enforce TTL for memory store)
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let stored_token = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
    assert!(
        stored_token.is_ok(),
        "Should be able to retrieve token with zero TTL"
    );
    let token_data = stored_token.unwrap().unwrap();
    assert_eq!(token_data.ttl, 0);
    assert_eq!(token_data.token, token);
}

/// Test token caching with maximum realistic TTL
///
/// This test verifies that `store_token_in_cache` can handle tokens with very large
/// but realistic TTL values (1 year). It stores a token with maximum TTL, retrieves it,
/// and validates that the system handles large TTL values gracefully without overflow
/// or storage issues.
///
#[tokio::test]
async fn test_cache_token_with_max_ttl() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = "test_max_ttl";
    let token = "test_token_max_ttl";
    // Use a realistic maximum TTL (1 year = 31,536,000 seconds)
    // instead of u64::MAX which causes chrono overflow
    let ttl = 31_536_000_u64; // 1 year in seconds
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = None;

    // Should handle large but realistic TTL values gracefully
    let result = store_token_in_cache(token_type, token, ttl, expires_at, user_agent).await;
    assert!(result.is_ok(), "Should handle realistic large TTL values");

    let token_id = result.unwrap();
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let stored_token = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
    assert!(stored_token.is_ok(), "Should retrieve token with large TTL");
    assert_eq!(stored_token.unwrap().unwrap().ttl, ttl);
}

/// Test concurrent token operations and thread safety
///
/// This test verifies that the cache token operations are thread-safe when multiple
/// concurrent operations are performed simultaneously. It spawns multiple tokio tasks
/// that generate and store tokens concurrently, then validates that all operations
/// complete successfully and all generated token IDs are unique.
///
#[tokio::test]
async fn test_concurrent_token_operations() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = "test_concurrent";
    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);

    // Perform concurrent token storage operations
    let handles = (0..10)
        .map(|i| {
            let user_agent = Some(format!("agent-{i}"));
            tokio::spawn(async move {
                store_token_in_cache(
                    token_type,
                    &format!("token-{i}"),
                    ttl,
                    expires_at,
                    user_agent,
                )
                .await
            })
        })
        .collect::<Vec<_>>();

    // Wait for all operations to complete
    let mut results = Vec::new();
    for handle in handles {
        results.push(handle.await);
    }

    // Verify all operations succeeded
    let mut token_ids = Vec::new();
    for result in results {
        let token_id = result.unwrap().unwrap();
        token_ids.push(token_id);
    }

    // Verify all tokens are unique and can be retrieved
    for (i, token_id) in token_ids.iter().enumerate() {
        let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
        let cache_key = CacheKey::new(token_id.clone()).unwrap();
        let stored_token = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
        assert!(stored_token.is_ok());

        let token_data = stored_token.unwrap().unwrap();
        assert_eq!(token_data.token, format!("token-{i}"));
        assert_eq!(token_data.user_agent, Some(format!("agent-{i}")));
    }

    // Verify all token IDs are unique
    let unique_count = token_ids
        .iter()
        .collect::<std::collections::HashSet<_>>()
        .len();
    assert_eq!(unique_count, 10, "All token IDs should be unique");
}

/// Test token storage with different type prefixes
///
/// This test verifies that tokens can be stored and retrieved using different type prefixes
/// (csrf, nonce, pkce, access, refresh) without conflicts. It stores the same token content
/// under different prefixes, then retrieves each one to ensure proper namespace isolation
/// and that all prefixes work correctly with the cache system.
///
#[tokio::test]
async fn test_token_storage_with_different_prefixes() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = Some("test-agent".to_string());

    // Store tokens with different prefixes but same token ID
    let token_prefixes = ["csrf", "nonce", "pkce", "access", "refresh"];
    let same_token_content = "same_token_content";

    let mut stored_tokens = Vec::new();

    for prefix in &token_prefixes {
        let token_id = store_token_in_cache(
            prefix,
            same_token_content,
            ttl,
            expires_at,
            user_agent.clone(),
        )
        .await
        .unwrap();
        stored_tokens.push((prefix, token_id));
    }

    // Verify each token can be retrieved with its respective prefix
    for (prefix, token_id) in &stored_tokens {
        let cache_prefix = CachePrefix::new(prefix.to_string()).unwrap();
        let cache_key = CacheKey::new(token_id.clone()).unwrap();
        let retrieved = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
        assert!(
            retrieved.is_ok(),
            "Should retrieve token for prefix: {prefix}"
        );

        let token_data = retrieved.unwrap().unwrap();
        assert_eq!(token_data.token, same_token_content);
        assert_eq!(token_data.user_agent, user_agent);
    }

    // Verify tokens with different prefixes don't interfere
    for (prefix1, token_id1) in &stored_tokens {
        for (prefix2, _) in &stored_tokens {
            if prefix1 != prefix2 {
                // Trying to get token with wrong prefix should fail
                let cache_prefix = CachePrefix::new(prefix2.to_string()).unwrap();
                let cache_key = CacheKey::new(token_id1.clone()).unwrap();
                let wrong_retrieval = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
                    .await
                    .and_then(|opt| {
                        opt.ok_or_else(|| {
                            OAuth2Error::SecurityTokenNotFound("token not found".to_string())
                        })
                    });
                assert!(
                    wrong_retrieval.is_err(),
                    "Should not retrieve token for {prefix2} with {prefix1}'s token_id"
                );
            }
        }
    }
}

/// Test token storage with edge case inputs
///
/// This test verifies that the token storage system handles edge cases gracefully,
/// including empty token content, very long token values, and special characters.
/// It tests the robustness of the storage and retrieval mechanisms with various
/// boundary conditions and unusual but valid inputs.
///
#[tokio::test]
async fn test_token_storage_edge_cases() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);

    // Test with empty token content
    let empty_token_result = store_token_in_cache("test", "", ttl, expires_at, None).await;
    assert!(
        empty_token_result.is_ok(),
        "Should handle empty token content"
    );

    if let Ok(token_id) = empty_token_result {
        let cache_prefix = CachePrefix::new("test".to_string()).unwrap();
        let cache_key = CacheKey::new(token_id.clone()).unwrap();
        let retrieved = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
        assert!(retrieved.is_ok());
        assert_eq!(retrieved.unwrap().unwrap().token, "");
    }

    // Test with very long token content
    let long_token = "a".repeat(10000); // 10KB token
    let long_token_result =
        store_token_in_cache("test_long", &long_token, ttl, expires_at, None).await;
    assert!(
        long_token_result.is_ok(),
        "Should handle large token content"
    );

    if let Ok(token_id) = long_token_result {
        let cache_prefix = CachePrefix::new("test_long".to_string()).unwrap();
        let cache_key = CacheKey::new(token_id.clone()).unwrap();
        let retrieved = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
        assert!(retrieved.is_ok());
        assert_eq!(retrieved.unwrap().unwrap().token, long_token);
    }

    // Test with special characters in token
    let special_token = "token_with_特殊字符_🔐_\n\t\r";
    let special_result =
        store_token_in_cache("test_special", special_token, ttl, expires_at, None).await;
    assert!(
        special_result.is_ok(),
        "Should handle special characters in token"
    );

    if let Ok(token_id) = special_result {
        let cache_prefix = CachePrefix::new("test_special".to_string()).unwrap();
        let cache_key = CacheKey::new(token_id.clone()).unwrap();
        let retrieved = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
        assert!(retrieved.is_ok());
        assert_eq!(retrieved.unwrap().unwrap().token, special_token);
    }
}

/// Test token storage with independent token IDs
///
/// This test verifies that storing multiple tokens of the same type generates
/// independent token IDs rather than overwriting existing tokens. It stores two
/// different tokens of the same type, validates that they receive different IDs,
/// and confirms that both tokens can be independently retrieved with their
/// respective content and metadata.
///
#[tokio::test]
async fn test_token_overwrite_same_id() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = "test_overwrite";
    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);

    // Store first token
    let token1 = "first_token";
    let user_agent1 = Some("agent1".to_string());
    let token_id1 = store_token_in_cache(token_type, token1, ttl, expires_at, user_agent1.clone())
        .await
        .unwrap();

    // Store second token
    let token2 = "second_token";
    let user_agent2 = Some("agent2".to_string());
    let token_id2 = store_token_in_cache(token_type, token2, ttl, expires_at, user_agent2.clone())
        .await
        .unwrap();

    // Verify both tokens exist independently (different IDs should be generated)
    assert_ne!(
        token_id1, token_id2,
        "Different tokens should have different IDs"
    );

    let cache_prefix1 = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key1 = CacheKey::new(token_id1.clone()).unwrap();
    let cache_prefix2 = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key2 = CacheKey::new(token_id2.clone()).unwrap();
    let retrieved1 = get_data::<StoredToken, OAuth2Error>(cache_prefix1, cache_key1)
        .await
        .unwrap()
        .unwrap();
    let retrieved2 = get_data::<StoredToken, OAuth2Error>(cache_prefix2, cache_key2)
        .await
        .unwrap()
        .unwrap();

    assert_eq!(retrieved1.token, token1);
    assert_eq!(retrieved1.user_agent, user_agent1);
    assert_eq!(retrieved2.token, token2);
    assert_eq!(retrieved2.user_agent, user_agent2);
}

/// Test multiple remove operations on the same token
///
/// This test verifies that the token removal system handles multiple removal attempts
/// gracefully, including repeated removals of the same token and concurrent removal
/// operations. It tests that the system doesn't fail when attempting to remove
/// already-removed tokens and handles race conditions properly.
///
#[tokio::test]
async fn test_multiple_remove_operations() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = "test_multiple_remove";
    let ttl = 300;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);

    // Store a token
    let token_id = store_token_in_cache(token_type, "test_token", ttl, expires_at, None)
        .await
        .unwrap();

    // Verify token exists
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let retrieved = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
    assert!(retrieved.is_ok());

    // Remove the token
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let remove_result1 = remove_data::<OAuth2Error>(cache_prefix, cache_key).await;
    assert!(remove_result1.is_ok());

    // Verify token is gone
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let get_after_remove = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
        .await
        .and_then(|opt| {
            opt.ok_or_else(|| OAuth2Error::SecurityTokenNotFound("token not found".to_string()))
        });
    assert!(get_after_remove.is_err());

    // Try to remove the same token again (should handle gracefully)
    let cache_prefix2 = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key2 = CacheKey::new(token_id.clone()).unwrap();
    let remove_result2 = remove_data::<OAuth2Error>(cache_prefix2, cache_key2).await;
    assert!(remove_result2.is_ok(), "Second removal should not fail");

    // Try multiple concurrent removals of the same token
    let remove_handles = (0..5)
        .map(|_| {
            let token_id_clone = token_id.clone();
            let token_type_clone = token_type;
            tokio::spawn(async move {
                let (cache_prefix, cache_key) = (
                    CachePrefix::new(token_type_clone.to_string()).unwrap(),
                    CacheKey::new(token_id_clone.clone()).unwrap(),
                );
                remove_data::<OAuth2Error>(cache_prefix, cache_key).await
            })
        })
        .collect::<Vec<_>>();

    let mut remove_results = Vec::new();
    for handle in remove_handles {
        remove_results.push(handle.await);
    }
    for result in remove_results {
        assert!(
            result.unwrap().is_ok(),
            "Concurrent removals should not fail"
        );
    }
}

/// Test cache operations with tokens that have past expiration times
///
/// This test verifies that the cache system can handle tokens with expiration times
/// set in the past. It stores a token with a past expiration time and validates that
/// the token can still be stored and retrieved, while confirming that the expiration
/// metadata is preserved correctly for potential cleanup operations.
///
#[tokio::test]
async fn test_cache_operations_with_past_expiration() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = "test_past_expiration";
    let ttl = 300;
    // Set expiration time in the past
    let expires_at = Utc::now() - chrono::Duration::hours(1);

    // Store token with past expiration
    let token_id = store_token_in_cache(token_type, "expired_token", ttl, expires_at, None)
        .await
        .unwrap();

    // Should still be able to retrieve it (cache doesn't automatically expire in memory store)
    let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
    let cache_key = CacheKey::new(token_id.clone()).unwrap();
    let retrieved = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key).await;
    assert!(retrieved.is_ok());

    let token_data = retrieved.unwrap().unwrap();
    assert_eq!(token_data.token, "expired_token");
    // Verify the past expiration time is preserved
    assert!(token_data.expires_at < Utc::now());
}

/// Test cache serialization and deserialization roundtrip
///
/// This test verifies that StoredToken objects can be properly serialized to CacheData
/// and deserialized back while preserving all field values. It creates a complex token
/// with various data types, performs the conversion roundtrip, and validates that all
/// fields including timestamps and user agent strings are correctly preserved.
///
#[tokio::test]
async fn test_cache_serialization_round_trip() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let _token_type = "test_serialization";
    let ttl = 3600;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = Some("Mozilla/5.0 (Test) AppleWebKit/537.36".to_string());

    // Create a complex token with various data types
    let original_token = StoredToken {
        token: "complex_token_12345!@#$%".to_string(),
        expires_at,
        user_agent: user_agent.clone(),
        ttl,
    };

    // Convert to CacheData and back
    let cache_data = CacheData::from(original_token.clone());
    let recovered_token = StoredToken::try_from(cache_data);

    assert!(recovered_token.is_ok());
    let recovered = recovered_token.unwrap();

    // Verify all fields are preserved exactly
    assert_eq!(recovered.token, original_token.token);
    assert_eq!(
        recovered.expires_at.timestamp_millis(),
        original_token.expires_at.timestamp_millis()
    );
    assert_eq!(recovered.user_agent, original_token.user_agent);
    assert_eq!(recovered.ttl, original_token.ttl);
}

/// Test token generation consistency and behavior patterns
///
/// This test verifies that `generate_store_token` produces consistent behavior across
/// multiple invocations. It generates multiple tokens and validates that each generation
/// produces tokens of consistent length, that all tokens are unique, and that the
/// storage and retrieval process works reliably for each generated token.
///
#[tokio::test]
async fn test_generate_store_token_consistency() {
    use crate::test_utils::init_test_environment;
    init_test_environment().await;

    let token_type = TokenType::Pkce;
    let ttl = 600;
    let expires_at = Utc::now() + chrono::Duration::seconds(ttl as i64);
    let user_agent = Some("consistency-test-agent".to_string());

    // Generate multiple tokens and verify consistency
    for _i in 0..10 {
        let (token, token_id) =
            generate_store_token(token_type, ttl, expires_at, user_agent.clone())
                .await
                .unwrap();

        // Verify token characteristics
        assert_eq!(token.len(), 43, "Generated token should be 43 characters");
        assert_eq!(
            token_id.len(),
            43,
            "Generated token ID should be 43 characters"
        );
        assert_ne!(token, token_id, "Token and token ID should be different");

        // Verify storage and retrieval
        let cache_prefix = CachePrefix::new(token_type.to_string()).unwrap();
        let cache_key = CacheKey::new(token_id.clone()).unwrap();
        let retrieved = get_data::<StoredToken, OAuth2Error>(cache_prefix, cache_key)
            .await
            .unwrap()
            .unwrap();

        assert_eq!(retrieved.token, token);
        assert_eq!(retrieved.user_agent, user_agent);
        assert_eq!(retrieved.ttl, ttl);

        // Verify expiration time consistency (within 1 second tolerance)
        let time_diff = (retrieved.expires_at - expires_at).num_seconds().abs();
        assert!(time_diff <= 1, "Expiration time should be consistent");
    }
}