garrison 0.9.0

Garrison - 面向 Rust 生态的一站式身份认证鉴权框架
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
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! `httpdigest` 模块单元测试。

use super::algorithm::hex_encode;
use super::auth::current_unix_seconds;
use super::*;
use crate::secure::ct_eq::constant_time_eq;
use base64::{engine::general_purpose::STANDARD, Engine};
use std::sync::Arc;
use uuid::Uuid;

// 算法枚举测试

/// from_str 解析 MD5。
#[test]
fn algorithm_from_str_md5() {
    assert_eq!(
        "MD5".parse::<DigestAlgorithm>().unwrap(),
        DigestAlgorithm::Md5
    );
    // 大小写不敏感
    assert_eq!(
        "md5".parse::<DigestAlgorithm>().unwrap(),
        DigestAlgorithm::Md5
    );
}

/// from_str 解析 SHA256。
#[test]
fn algorithm_from_str_sha256() {
    assert_eq!(
        "SHA256".parse::<DigestAlgorithm>().unwrap(),
        DigestAlgorithm::Sha256
    );
    assert_eq!(
        "sha256".parse::<DigestAlgorithm>().unwrap(),
        DigestAlgorithm::Sha256
    );
}

/// from_str 拒绝未知算法。
#[test]
fn algorithm_from_str_unknown_errors() {
    assert!("SHA512".parse::<DigestAlgorithm>().is_err());
    assert!("".parse::<DigestAlgorithm>().is_err());
}

/// DigestAlgorithm::default() 返回 Sha256。
#[test]
fn algorithm_default_is_sha256() {
    assert_eq!(DigestAlgorithm::default(), DigestAlgorithm::Sha256);
}

// 构造与质询测试

/// new 构造合法实例。
#[test]
fn new_constructs_instance() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let challenge = auth.challenge();
    assert!(challenge.starts_with("Digest "));
}

/// new 拒绝未知算法。
#[test]
fn new_rejects_unknown_algorithm() {
    assert!(HttpDigestAuth::new("realm", "SHA512").is_err());
}

/// 质询头包含 RFC 7616 必要字段。
#[test]
fn challenge_contains_required_fields() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let challenge = auth.challenge();
    assert!(challenge.starts_with("Digest "));
    assert!(challenge.contains(r#"realm="test@realm""#));
    // qop 现在声明支持 auth 和 auth-int
    assert!(challenge.contains(r#"qop="auth,auth-int""#));
    assert!(challenge.contains("algorithm=MD5"));
    assert!(challenge.contains("nonce="));
}

/// nonce 每次生成为随机值。
#[test]
fn challenge_nonce_is_random() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    let c1 = auth.challenge();
    let c2 = auth.challenge();
    let n1 = extract_nonce(&c1).unwrap();
    let n2 = extract_nonce(&c2).unwrap();
    assert!(!n1.is_empty());
    assert_ne!(n1, n2);
}

/// SHA256 算法的质询头包含 algorithm=SHA256。
#[test]
fn challenge_sha256_algorithm() {
    let auth = HttpDigestAuth::new("realm", "SHA256").unwrap();
    let challenge = auth.challenge();
    assert!(challenge.contains("algorithm=SHA256"));
}

/// challenge 生成的 nonce 可被 is_nonce_valid 接受。
#[test]
fn challenge_nonce_is_valid() {
    let auth = HttpDigestAuth::new("realm", "SHA256").unwrap();
    let challenge = auth.challenge();
    let nonce = extract_nonce(&challenge).unwrap();
    assert!(auth.is_nonce_valid(&nonce));
}

/// with_nonce_ttl 设置 TTL。
#[test]
fn with_nonce_ttl_sets_ttl() {
    let auth = HttpDigestAuth::new("realm", "MD5")
        .unwrap()
        .with_nonce_ttl(60);
    assert_eq!(auth.nonce_ttl(), 60);
}

// compute_ha1 测试

/// compute_ha1 返回已知 MD5 值。
#[test]
fn compute_ha1_known_md5_value() {
    // "user:realm:pass" 的 MD5
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("user", "pass");
    // 验证:MD5("user:realm:pass") 应为已知值
    let expected_input = "user:realm:pass";
    let expected = md5::compute(expected_input.as_bytes());
    let expected_hex: String = expected.0.iter().map(|b| format!("{:02x}", b)).collect();
    assert_eq!(ha1, expected_hex);
}

/// compute_ha1 SHA256 返回 64 字符。
#[test]
fn compute_ha1_sha256_returns_64_chars() {
    let auth = HttpDigestAuth::new("realm", "SHA256").unwrap();
    let ha1 = auth.compute_ha1("user", "pass");
    assert_eq!(ha1.len(), 64);
}

// validate 测试(qop=auth)

/// 辅助函数 — 生成有效 nonce(base64(timestamp:uuid))。
fn make_valid_nonce() -> String {
    let timestamp = current_unix_seconds();
    let random = Uuid::new_v4().simple().to_string();
    let raw = format!("{}:{}", timestamp, random);
    STANDARD.encode(raw.as_bytes())
}

/// 辅助函数 — 生成过期 nonce(时间戳在 TTL 之前)。
fn make_expired_nonce(ttl: u64) -> String {
    let expired_timestamp = current_unix_seconds().saturating_sub(ttl + 10);
    let random = Uuid::new_v4().simple().to_string();
    let raw = format!("{}:{}", expired_timestamp, random);
    STANDARD.encode(raw.as_bytes())
}

/// 辅助函数 — 生成未来 nonce(时间戳在未来)。
fn make_future_nonce() -> String {
    let future_timestamp = current_unix_seconds() + 100;
    let random = Uuid::new_v4().simple().to_string();
    let raw = format!("{}:{}", future_timestamp, random);
    STANDARD.encode(raw.as_bytes())
}

/// 辅助函数 — 构造合法 MD5 Authorization header。
#[allow(clippy::too_many_arguments)]
fn build_md5_auth_header(
    _auth: &HttpDigestAuth,
    username: &str,
    realm: &str,
    nonce: &str,
    nc: &str,
    cnonce: &str,
    method: &str,
    uri: &str,
    ha1: &str,
) -> String {
    let ha2_input = format!("{}:{}", method, uri);
    let ha2 = md5::compute(ha2_input.as_bytes());
    let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
    let resp_input = format!("{}:{}:{}:{}:auth:{}", ha1, nonce, nc, cnonce, ha2_hex);
    let resp = md5::compute(resp_input.as_bytes());
    let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
    format!(
        r#"Digest username="{}", realm="{}", nonce="{}", uri="{}", response="{}", qop=auth, nc={}, cnonce="{}""#,
        username, realm, nonce, uri, resp_hex, nc, cnonce
    )
}

/// 辅助函数 — 构造合法 SHA256 Authorization header。
#[allow(clippy::too_many_arguments)]
fn build_sha256_auth_header(
    _auth: &HttpDigestAuth,
    username: &str,
    realm: &str,
    nonce: &str,
    nc: &str,
    cnonce: &str,
    method: &str,
    uri: &str,
    ha1: &str,
) -> String {
    use sha2::Digest;
    let ha2_input = format!("{}:{}", method, uri);
    let mut h2 = sha2::Sha256::new();
    h2.update(ha2_input.as_bytes());
    let ha2_hex: String = h2.finalize().iter().map(|b| format!("{:02x}", b)).collect();
    let resp_input = format!("{}:{}:{}:{}:auth:{}", ha1, nonce, nc, cnonce, ha2_hex);
    let mut h = sha2::Sha256::new();
    h.update(resp_input.as_bytes());
    let resp_hex: String = h.finalize().iter().map(|b| format!("{:02x}", b)).collect();
    format!(
        r#"Digest username="{}", realm="{}", nonce="{}", uri="{}", response="{}", qop=auth, nc={}, cnonce="{}""#,
        username, realm, nonce, uri, resp_hex, nc, cnonce
    )
}

/// 合法 Digest 响应校验通过(qop=auth)。
#[test]
fn validate_correct_password_succeeds() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(auth.validate(&header, method, uri, &ha1));
}

/// 错误密码生成的响应校验失败。
#[test]
fn validate_wrong_password_fails() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1_correct = auth.compute_ha1("admin", "secret");
    let ha1_wrong = auth.compute_ha1("admin", "wrong");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    // 客户端用错误密码计算 response
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1_wrong,
    );
    // 服务端用正确 ha1 校验 → 应失败
    assert!(!auth.validate(&header, method, uri, &ha1_correct));
}

/// 错误的 HTTP method 导致校验失败。
#[test]
fn validate_wrong_method_fails() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "POST";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    // 服务端用 GET 校验(method 不匹配)→ 应失败
    assert!(!auth.validate(&header, "GET", uri, &ha1));
}

/// 过期 nonce 被拒绝。
#[test]
fn validate_expired_nonce_rejected() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    // 使用过期 nonce(超过默认 300 秒 TTL)
    let nonce = make_expired_nonce(300);
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(!auth.validate(&header, method, uri, &ha1));
}

/// 未来 nonce 被拒绝(防止伪造未来时间戳)。
#[test]
fn validate_future_nonce_rejected() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_future_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    // nonce 时间戳在未来 → 应失败
    assert!(!auth.validate(&header, method, uri, &ha1));
}

/// 非 base64 格式的 nonce 被拒绝。
#[test]
fn validate_malformed_nonce_rejected() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    // "abc123nonce" 不是有效的 base64(timestamp:uuid) 格式
    let nonce = "abc123nonce";
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(!auth.validate(&header, method, uri, &ha1));
}

/// 自定义 TTL — 短 TTL 的过期 nonce 被拒绝,但刚生成的 nonce 通过。
#[test]
fn validate_custom_ttl_works() {
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_nonce_ttl(1);
    let ha1 = auth.compute_ha1("admin", "secret");
    // 生成 5 秒前的 nonce,超过 1 秒 TTL
    let nonce = make_expired_nonce(1);
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(!auth.validate(&header, method, uri, &ha1));
    let valid_nonce = make_valid_nonce();
    let valid_header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &valid_nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(auth.validate(&valid_header, method, uri, &ha1));
}

/// auth-int 经 validate(无 body)被拒:body 缺失即 fail-closed,防用空 body 预计算 response 绕过 body 绑定校验。
#[test]
fn validate_auth_int_rejected_without_body() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "POST";
    let uri = "/resource";
    // 攻击者视角:用空 body 计算 auth-int 的 response(HA2 = H(method:uri:H("")))
    let empty_body_hash = auth.algorithm.hash(b"");
    let ha2_input = format!("{}:{}:{}", method, uri, empty_body_hash);
    let ha2 = md5::compute(ha2_input.as_bytes());
    let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
    let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
    let resp = md5::compute(resp_input.as_bytes());
    let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
    let header = format!(
        r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
        nonce, uri, resp_hex, nc, cnonce
    );
    // 无 body 的 validate 对 auth-int 一律拒绝(即使 response 是按空 body 正确计算)
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "auth-int 在 body 缺失时应被拒绝(即使按空 body 正确计算 response)"
    );
    // 带 body(含空 body)的 validate_with_body 仍可正常校验
    assert!(
        auth.validate_with_body(&header, method, uri, b"", &ha1),
        "validate_with_body 携带(空)body 时应正常校验通过"
    );
}

/// validate_with_body 支持 qop=auth-int(MD5)。
#[test]
fn validate_with_body_auth_int_md5_succeeds() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "POST";
    let uri = "/resource";
    let body = b"hello world";
    // 计算 auth-int 的 response: HA2 = H(method:uri:H(body))
    let body_hash = auth.algorithm.hash(body);
    let ha2_input = format!("{}:{}:{}", method, uri, body_hash);
    let ha2 = md5::compute(ha2_input.as_bytes());
    let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
    let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
    let resp = md5::compute(resp_input.as_bytes());
    let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
    let header = format!(
        r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
        nonce, uri, resp_hex, nc, cnonce
    );
    assert!(auth.validate_with_body(&header, method, uri, body, &ha1));
}

/// validate_with_body 支持 qop=auth-int(SHA256)。
#[test]
fn validate_with_body_auth_int_sha256_succeeds() {
    let auth = HttpDigestAuth::new("test@realm", "SHA256").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "POST";
    let uri = "/resource";
    let body = b"hello world";
    // 用 SHA256 计算 auth-int 的 response
    use sha2::Digest;
    let body_hash = {
        let mut h = sha2::Sha256::new();
        h.update(body);
        h.finalize()
            .iter()
            .map(|b| format!("{:02x}", b))
            .collect::<String>()
    };
    let ha2_input = format!("{}:{}:{}", method, uri, body_hash);
    let mut h2 = sha2::Sha256::new();
    h2.update(ha2_input.as_bytes());
    let ha2_hex: String = h2.finalize().iter().map(|b| format!("{:02x}", b)).collect();
    let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
    let mut h = sha2::Sha256::new();
    h.update(resp_input.as_bytes());
    let resp_hex: String = h.finalize().iter().map(|b| format!("{:02x}", b)).collect();
    let header = format!(
        r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
        nonce, uri, resp_hex, nc, cnonce
    );
    assert!(auth.validate_with_body(&header, method, uri, body, &ha1));
}

/// validate_with_body 中 body 不匹配导致校验失败。
#[test]
fn validate_with_body_tampered_body_fails() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "POST";
    let uri = "/resource";
    let original_body = b"hello world";
    // 客户端用 original_body 计算 response
    let body_hash = auth.algorithm.hash(original_body);
    let ha2_input = format!("{}:{}:{}", method, uri, body_hash);
    let ha2 = md5::compute(ha2_input.as_bytes());
    let ha2_hex: String = ha2.0.iter().map(|b| format!("{:02x}", b)).collect();
    let resp_input = format!("{}:{}:{}:{}:auth-int:{}", ha1, nonce, nc, cnonce, ha2_hex);
    let resp = md5::compute(resp_input.as_bytes());
    let resp_hex: String = resp.0.iter().map(|b| format!("{:02x}", b)).collect();
    let header = format!(
        r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="{}", qop=auth-int, nc={}, cnonce="{}""#,
        nonce, uri, resp_hex, nc, cnonce
    );
    // 服务端用篡改后的 body 校验 → 应失败
    let tampered_body = b"tampered body";
    assert!(!auth.validate_with_body(&header, method, uri, tampered_body, &ha1));
}

/// validate_with_body 也支持 qop=auth(body 被忽略)。
#[test]
fn validate_with_body_supports_auth_qop() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    // 构造 qop=auth 的 header
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    // validate_with_body 也能校验 qop=auth(body 被忽略)
    assert!(auth.validate_with_body(&header, method, uri, b"any body", &ha1));
}

/// 格式错误的 Authorization header 返回 false。
#[test]
fn validate_malformed_header_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    let ha1 = "dummy";
    assert!(!auth.validate("Basic abc123", "GET", "/resource", ha1));
    assert!(!auth.validate("Digest username=\"admin\"", "GET", "/resource", ha1));
}

/// SHA256 算法的 validate 校验通过。
#[test]
fn validate_sha256_succeeds() {
    let auth = HttpDigestAuth::new("test@realm", "SHA256").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_sha256_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(auth.validate(&header, method, uri, &ha1));
}

// parse_authorization 边界路径测试

/// 覆盖 `split_once` 返回 None 的路径:header 缺参数部分时 validate 返回 false。
#[test]
fn validate_header_without_whitespace_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    // "Digest" 后无空格,split_once 返回 None
    assert!(!auth.validate("Digest", "GET", "/resource", "ha1"));
}

/// 覆盖 parse_digest_params 的未知 key 忽略分支:含未知参数的 header 仍可解析。
#[test]
fn validate_header_with_unknown_params_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    // 使用有效 nonce 但 response 不正确
    let nonce = make_valid_nonce();
    let header = format!(
        r#"Digest username="admin", realm="realm", nonce="{}", uri="/r", response="r", qop=auth, nc=1, cnonce="c", custom_param="x""#,
        nonce
    );
    // response 不正确,应返回 false(但解析本身不应出错)
    assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}

/// 覆盖 parse_digest_params 的引号转义分支:含转义字符的 header 可解析。
#[test]
fn validate_header_with_escaped_chars_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    let nonce = make_valid_nonce();
    // response 包含转义字符 \"
    let header = format!(
        r#"Digest username="ad\"min", realm="realm", nonce="{}", uri="/r", response="r", qop=auth, nc=1, cnonce="c""#,
        nonce
    );
    // response 不正确,应返回 false
    assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}

/// 覆盖 parse_digest_params 的 break 分支:key 后无 `=` 时 validate 返回 false。
#[test]
fn validate_header_with_key_without_equals_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    let nonce = make_valid_nonce();
    // "username" 后无 '=',parse_digest_params 应 break
    let header = format!(
        r#"Digest username realm="realm", nonce="{}", uri="/r", response="r", qop=auth, nc=1, cnonce="c""#,
        nonce
    );
    assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}

/// 覆盖 qop=None 分支:不含 qop 的 header 校验失败。
#[test]
fn validate_header_without_qop_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    let nonce = make_valid_nonce();
    let header = format!(
        r#"Digest username="admin", realm="realm", nonce="{}", uri="/r", response="r", nc=1, cnonce="c""#,
        nonce
    );
    assert!(!auth.validate(&header, "GET", "/r", "dummy_ha1"));
}

// is_nonce_valid 直接测试

/// is_nonce_valid 对空字符串返回 false。
#[test]
fn is_nonce_valid_empty_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    assert!(!auth.is_nonce_valid(""));
}

/// is_nonce_valid 对纯文本(非 base64)返回 false。
#[test]
fn is_nonce_valid_plain_text_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    assert!(!auth.is_nonce_valid("abc123nonce"));
}

/// is_nonce_valid 对缺少冒号分隔符的 base64 返回 false。
#[test]
fn is_nonce_valid_no_colon_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    // base64("12345") — 无冒号
    let nonce = STANDARD.encode(b"12345");
    assert!(!auth.is_nonce_valid(&nonce));
}

/// is_nonce_valid 对时间戳非数字返回 false。
#[test]
fn is_nonce_valid_non_numeric_timestamp_returns_false() {
    let auth = HttpDigestAuth::new("realm", "MD5").unwrap();
    let raw = "abc:def";
    let nonce = STANDARD.encode(raw.as_bytes());
    assert!(!auth.is_nonce_valid(&nonce));
}

// constant_time_eq 测试

/// 验证 constant_time_eq 对不同长度输入返回 false(含单侧为空)。
#[test]
fn constant_time_eq_different_lengths_returns_false() {
    assert!(!constant_time_eq(b"abc", b"ab"));
    assert!(!constant_time_eq(b"ab", b"abc"));
    assert!(!constant_time_eq(b"", b"abc"));
    assert!(!constant_time_eq(b"abc", b""));
}

/// 验证 constant_time_eq 对相同字符串返回 true。
#[test]
fn constant_time_eq_same_strings_returns_true() {
    assert!(constant_time_eq(b"abc", b"abc"));
    assert!(constant_time_eq(b"", b""));
}

/// 验证 constant_time_eq 对不同字符串返回 false。
#[test]
fn constant_time_eq_different_strings_returns_false() {
    assert!(!constant_time_eq(b"abc", b"xyz"));
}

/// 超长 response 拒绝:长度为公开协议参数(hex 后 MD5 32 / SHA-256 64),长度预校验在进入比较前拦截,防可控长度放大计算量。
#[test]
fn validate_oversized_response_rejected() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        "00000001",
        "0a4f113c",
        "GET",
        "/resource",
        &ha1,
    );
    // 将 32 位 response 替换为超长值(其余参数保持合法)
    let resp_start = header.find("response=\"").unwrap() + "response=\"".len();
    let resp_end = header[resp_start..].find('"').unwrap() + resp_start;
    let oversized = format!(
        "{}{}{}",
        &header[..resp_start],
        "a".repeat(4096),
        &header[resp_end..]
    );
    assert!(
        !auth.validate(&oversized, "GET", "/resource", &ha1),
        "超长 response 应被拒绝"
    );
    // 长度不足同型(31 位)
    let short = format!(
        "{}{}{}",
        &header[..resp_start],
        "a".repeat(31),
        &header[resp_end..]
    );
    assert!(
        !auth.validate(&short, "GET", "/resource", &ha1),
        "长度不足的 response 应被拒绝"
    );
}

/// 超长 nonce mac 段拒绝:mac 为公开定长(HMAC-SHA256 hex 64 字符),长度预校验在比较前拦截。
#[test]
fn is_nonce_valid_oversized_mac_returns_false() {
    let auth = HttpDigestAuth::new("realm", "SHA256")
        .unwrap()
        .with_server_key(b"server-secret-key-material-with-enough-bytes-32");
    let ts = current_unix_seconds();
    let uuid = Uuid::new_v4().simple().to_string();
    let oversized = format!("{}:{}:{}", ts, uuid, "a".repeat(4096));
    let forged = STANDARD.encode(oversized.as_bytes());
    assert!(!auth.is_nonce_valid(&forged), "超长 mac 段应被拒绝");
}

// hex_encode 测试

/// 验证 hex_encode 对空字节返回空字符串。
#[test]
fn hex_encode_empty_bytes() {
    assert_eq!(hex_encode(&[]), "");
}

/// 验证 hex_encode 对已知字节返回正确 hex。
#[test]
fn hex_encode_known_bytes() {
    assert_eq!(hex_encode(&[0x00, 0xff, 0x0a]), "00ff0a");
}

// nc 单调性校验测试(RFC 7616 §3.4.6 重放防护)

/// 注入 DAO 时首次请求 nc=00000001 通过。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_first_use_accepted_with_dao() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        auth.validate(&header, method, uri, &ha1),
        "vuln-0008: 首次使用 nonce 应通过 nc 校验"
    );
}

/// 注入 DAO 时同一 nonce 重复 nc 被拒(重放)。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_replay_rejected_with_dao() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        auth.validate(&header, method, uri, &ha1),
        "vuln-0008: 首次请求应通过"
    );
    // 第二次相同 nc:应被拒绝(重放)
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "vuln-0008: 相同 nc 重放应被拒绝"
    );
}

/// 注入 DAO 时 nc 回退被拒:首次 nc=00000003 通过,第二次 nc=00000002 失败。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_decrease_rejected_with_dao() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    // 第一次 nc=00000003
    let header1 = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        "00000003",
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        auth.validate(&header1, method, uri, &ha1),
        "vuln-0008: nc=3 应通过"
    );
    // 第二次 nc=00000002(回退)应被拒绝
    let header2 = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        "00000002",
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        !auth.validate(&header2, method, uri, &ha1),
        "vuln-0008: nc 回退(3→2)应被拒绝"
    );
}

/// 注入 DAO 时 nc=1→2→3 单调递增均通过。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_increasing_accepted_with_dao() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    for i in 1..=3u64 {
        let nc = format!("{:08x}", i);
        let header = build_md5_auth_header(
            &auth,
            "admin",
            "test@realm",
            &nonce,
            &nc,
            cnonce,
            method,
            uri,
            &ha1,
        );
        assert!(
            auth.validate(&header, method, uri, &ha1),
            "vuln-0008: nc={} 应通过(单调递增)",
            nc
        );
    }
}

/// 未注入 DAO 时跳过 nc 校验(fail-open):相同 nc 重放仍被接受,仅靠 nonce TTL 防护。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_skipped_without_dao() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        auth.validate(&header, method, uri, &ha1),
        "vuln-0008: 无 DAO 时首次请求应通过"
    );
    // 第二次相同 nc:仍通过(无 DAO 跳过 nc 校验,fail-open)
    assert!(
        auth.validate(&header, method, uri, &ha1),
        "vuln-0008: 无 DAO 时相同 nc 重放仍通过(fail-open)"
    );
}

/// 注入 DAO 时不同 nonce 的 nc 计数独立:各自 nc=1 均通过。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_isolates_nonces_with_dao() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let nc = "00000001";
    // nonce-A nc=1
    let nonce_a = make_valid_nonce();
    let header_a = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce_a,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        auth.validate(&header_a, method, uri, &ha1),
        "vuln-0008: nonce-A nc=1 应通过"
    );
    // nonce-B nc=1(不同 nonce,应独立计数,通过)
    let nonce_b = make_valid_nonce();
    let header_b = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce_b,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        auth.validate(&header_b, method, uri, &ha1),
        "vuln-0008: nonce-B nc=1 应通过(不同 nonce 独立计数)"
    );
}

// nc fail-closed 与运行时约束测试

/// current_thread runtime 下 validate_nc fail-closed:`block_in_place` 会 panic,故拒绝请求而非放行重放。
///
/// 注意:用不带 `flavor = "multi_thread"` 的 `#[tokio::test]` 构造该 runtime。
#[tokio::test]
async fn validate_nc_current_thread_runtime_fail_closed() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    // 第一次:current_thread runtime 下 fail-closed,应拒绝(不 panic,但拒绝重放风险)
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "vuln-0012: current_thread runtime 下 validate_nc 应 fail-closed,首次请求拒绝"
    );
    // 第二次相同 nc:仍 fail-closed,应拒绝
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "vuln-0012: current_thread runtime 下相同 nc 重放仍拒绝(fail-closed)"
    );
}

/// 始终返回 DAO 错误的 mock DAO:触发 validate_nc 的 DAO 错误 fail-closed 路径。
struct FailingDao;

#[async_trait::async_trait]
impl crate::dao::GarrisonDao for FailingDao {
    async fn get(&self, key: &str) -> crate::error::GarrisonResult<Option<String>> {
        Err(crate::error::GarrisonError::Dao(format!(
            "vuln-0012-failing-dao-get::{}",
            key
        )))
    }
    async fn set(
        &self,
        key: &str,
        _value: &str,
        _ttl_seconds: u64,
    ) -> crate::error::GarrisonResult<()> {
        Err(crate::error::GarrisonError::Dao(format!(
            "vuln-0012-failing-dao-set::{}",
            key
        )))
    }
    async fn update(&self, key: &str, _value: &str) -> crate::error::GarrisonResult<()> {
        Err(crate::error::GarrisonError::Dao(format!(
            "vuln-0012-failing-dao-update::{}",
            key
        )))
    }
    async fn expire(&self, key: &str, _seconds: u64) -> crate::error::GarrisonResult<()> {
        Err(crate::error::GarrisonError::Dao(format!(
            "vuln-0012-failing-dao-expire::{}",
            key
        )))
    }
    async fn delete(&self, key: &str) -> crate::error::GarrisonResult<()> {
        Err(crate::error::GarrisonError::Dao(format!(
            "vuln-0012-failing-dao-delete::{}",
            key
        )))
    }

    crate::atomic_test_fallback!();
}

/// DAO 错误时 validate_nc fail-closed(返回 false):nonce TTL 不足以防重放,失败必须拒绝。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_dao_error_fail_closed() {
    // atomic + 默认 trait 方法覆盖
    {
        use crate::dao::GarrisonDao;
        let d = FailingDao;
        let _ = d.set_if_absent("a", "v", 60).await;
        let _ = d.get_and_delete("a").await;
        let _ = d.incr("c", 60).await;
        let _ = d.decr("c").await;
        let _ = d.rename("a", "b").await;
        let _ = d.compare_and_swap("b", None, "v", 60).await;
        let _ = d.set_permanent("p", "v").await;
        let _ = d.get_timeout("k").await;
        let _ = d.get_with_ttl("k").await;
        let _ = d.keys("*").await;
        let _ = d.find_social_binding(0, "w", "o").await;
        let _ = d.insert_social_binding(0, "u", "w", "o", None, 0).await;
        let _ = d.compare_and_update_if_greater("k", 1, 60).await;
        let _ = d.eval_lua("r", vec![], vec![]).await;
        #[cfg(any(feature = "db-sqlite", feature = "db-postgres", feature = "db-mysql"))]
        {
            let _ = d.insert_credit_consumption(0, "r", 1, 1, 1, 0).await;
            let _ = d.query_credit_consumption(0, 0, 0).await;
            let _ = d.query_role_hierarchy_edges(0).await;
            let _ = d.insert_role_hierarchy_edge(0, "c", "p").await;
            let _ = d.delete_role_hierarchy_edge(0, "c", "p").await;
        }
    }
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(FailingDao);
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    // DAO 错误时 fail-closed,应拒绝
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "vuln-0012: DAO 错误时 validate_nc 应 fail-closed(拒绝请求)"
    );
    // 再次调用,DAO 仍错误,仍 fail-closed(拒绝重放)
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "vuln-0012: DAO 错误时相同 nc 重放仍拒绝(fail-closed)"
    );
}

/// 无 tokio runtime 时 `Handle::try_current()` 返回 `Err`,validate_nc fail-closed(返回 false)。
///
/// 注意:用普通 `#[test]`(不引入 runtime)与 `#[tokio::test]` 区分。
#[test]
fn validate_nc_no_runtime_fail_closed() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    // 无 tokio runtime 时 fail-closed,应拒绝(不 panic,但拒绝重放风险)
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "vuln-0012: 无 tokio runtime 时 validate_nc 应 fail-closed,拒绝请求"
    );
    // 第二次相同 nc:仍 fail-closed,应拒绝
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "vuln-0012: 无 tokio runtime 时相同 nc 重放仍拒绝(fail-closed)"
    );
}

/// 非 hex 格式 nc(`u64::from_str_radix` 解析失败)被拒:返回 false 而非 fail-open。
#[tokio::test(flavor = "multi_thread")]
async fn validate_nc_malformed_hex_rejected() {
    let dao: Arc<dyn crate::dao::GarrisonDao> = Arc::new(crate::dao::InMemoryDao::new());
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_dao(dao);
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    // "gggggggg" 不是有效的 hex 字符
    let nc = "gggggggg";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    // 构造 header 时 nc 字段直接放入(parse_authorization 仅提取字符串,不校验格式)
    let header = format!(
        r#"Digest username="admin", realm="test@realm", nonce="{}", uri="{}", response="dummy", qop=auth, nc={}, cnonce="{}""#,
        nonce, uri, nc, cnonce
    );
    // nc 非 hex 格式 → validate_nc 返回 false → validate 返回 false
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "LOW-2: 非 hex 格式的 nc 应被拒绝(不是 fail-open)"
    );
}

// Digest Auth URI 校验(RFC 7616 §3.4.6)

/// uri 不匹配被拒(防跨 URI 重放):response 基于 `/resource`、validate 用 `/other`,常量时间比对比 response 比对先拦截。
#[test]
fn validate_uri_mismatch_rejected() {
    let auth = HttpDigestAuth::new("test@realm", "MD5").unwrap();
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = make_valid_nonce();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let header_uri = "/resource";
    let actual_uri = "/other";
    // ha2 基于 header_uri 计算(模拟客户端对 /resource 的合法响应)
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        header_uri,
        &ha1,
    );
    // validate 使用 actual_uri(/other),与 header 中的 uri(/resource)不匹配
    assert!(
        !auth.validate(&header, method, actual_uri, &ha1),
        "CRITICAL-5: 客户端 uri 与实际请求 URI 不匹配应被拒绝"
    );
}

// nonce 服务端签名(防自铸 nonce)

/// 注入 server_key 后签名 nonce 通过 is_nonce_valid,自铸(无 HMAC / HMAC 错误)nonce 被拒。
#[test]
fn signed_nonce_roundtrip_and_self_minted_rejected() {
    let auth = HttpDigestAuth::new("realm", "SHA256")
        .unwrap()
        .with_server_key(b"server-secret-key-material-with-enough-bytes-32");
    // challenge 生成带签名 nonce
    let nonce = extract_nonce(&auth.challenge()).unwrap();
    assert!(auth.is_nonce_valid(&nonce), "签名 nonce 应有效");

    // 自铸:旧格式 2 段(无签名)应被拒
    let forged = STANDARD
        .encode(format!("{}:{}", current_unix_seconds(), Uuid::new_v4().simple()).as_bytes());
    assert!(!auth.is_nonce_valid(&forged), "无签名自铸 nonce 应被拒");

    // 自铸:3 段但 HMAC 错误应被拒
    let ts = current_unix_seconds();
    let uuid = Uuid::new_v4().simple().to_string();
    let forged3 = STANDARD.encode(format!("{}:{}:deadbeef", ts, uuid).as_bytes());
    assert!(
        !auth.is_nonce_valid(&forged3),
        "HMAC 错误的自铸 nonce 应被拒"
    );
}

/// 注入 server_key 后,完整 validate 流程对签名 nonce 通过、对自铸 nonce 拒绝。
#[test]
fn validate_rejects_self_minted_nonce_with_server_key() {
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_server_key(b"server-secret-key-material-with-enough-bytes-32");
    let ha1 = auth.compute_ha1("admin", "secret");
    // 自铸旧格式 nonce(无签名)
    let nonce = STANDARD
        .encode(format!("{}:{}", current_unix_seconds(), Uuid::new_v4().simple()).as_bytes());
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        !auth.validate(&header, method, uri, &ha1),
        "自铸 nonce 应被拒"
    );
}

/// 注入 server_key 后,challenge 签发的 nonce 可完成完整 validate 校验。
#[test]
fn validate_succeeds_with_signed_nonce() {
    let auth = HttpDigestAuth::new("test@realm", "MD5")
        .unwrap()
        .with_server_key(b"server-secret-key-material-with-enough-bytes-32");
    let ha1 = auth.compute_ha1("admin", "secret");
    let nonce = extract_nonce(&auth.challenge()).unwrap();
    let nc = "00000001";
    let cnonce = "0a4f113c";
    let method = "GET";
    let uri = "/resource";
    let header = build_md5_auth_header(
        &auth,
        "admin",
        "test@realm",
        &nonce,
        nc,
        cnonce,
        method,
        uri,
        &ha1,
    );
    assert!(
        auth.validate(&header, method, uri, &ha1),
        "签名 nonce 应完成完整校验"
    );
}

// 辅助函数

/// 从质询头中提取 nonce 值。
fn extract_nonce(challenge: &str) -> Option<String> {
    let start = challenge.find("nonce=\"")? + "nonce=\"".len();
    let end = challenge[start..].find('"')? + start;
    Some(challenge[start..end].to_string())
}