zenith-web 0.1.0

Zenith Web 应用框架:编译期 Trie 路由、类型化 Extractor、中间件 DAG、静态文件服务、统一错误处理
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
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
//! 静态文件服务
//!
//! 支持 Range 请求、条件请求(ETag/Last-Modified)、缓存控制

use std::fs;
use std::io::{Read, Seek, SeekFrom};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use zenith_api::CanonicalResponse;

use crate::error::WebError;

/// 静态文件配置
#[derive(Debug, Clone)]
pub struct StaticConfig {
    /// 根目录
    pub root: PathBuf,
    /// 默认文件(目录请求时返回)
    pub default_file: String,
    /// 目录列表
    pub directory_listing: bool,
    /// 缓存控制(秒)
    pub cache_max_age: u32,
    /// 是否支持 Range 请求
    pub enable_range: bool,
    /// 是否支持条件请求
    pub enable_conditional: bool,
    /// 单文件最大读取字节数(防止大文件内存耗尽 DoS)
    pub max_file_size: usize,
}

/// 单文件默认读取上限:16 MiB
pub const DEFAULT_MAX_FILE_SIZE: usize = 16 * 1024 * 1024;

impl StaticConfig {
    /// 创建静态文件配置,`root` 指定根目录
    pub fn new(root: impl Into<PathBuf>) -> Self {
        Self {
            root: root.into(),
            default_file: "index.html".to_string(),
            directory_listing: false,
            cache_max_age: 3600,
            enable_range: true,
            enable_conditional: true,
            max_file_size: DEFAULT_MAX_FILE_SIZE,
        }
    }

    /// 设置默认文件名(目录请求时返回)
    pub fn with_default_file(mut self, file: &str) -> Self {
        self.default_file = file.to_string();
        self
    }

    /// 设置是否启用目录列表
    pub fn with_directory_listing(mut self, enabled: bool) -> Self {
        self.directory_listing = enabled;
        self
    }

    /// 设置缓存控制最大时长(秒)
    pub fn with_cache_max_age(mut self, seconds: u32) -> Self {
        self.cache_max_age = seconds;
        self
    }

    /// 设置是否支持 Range 请求
    pub fn with_range(mut self, enabled: bool) -> Self {
        self.enable_range = enabled;
        self
    }

    /// 设置是否支持条件请求(ETag/Last-Modified)
    pub fn with_conditional(mut self, enabled: bool) -> Self {
        self.enable_conditional = enabled;
        self
    }

    /// 设置单文件最大读取字节数(超过则返回 413,防止内存耗尽 DoS)
    pub fn with_max_file_size(mut self, max: usize) -> Self {
        self.max_file_size = max;
        self
    }
}

impl Default for StaticConfig {
    fn default() -> Self {
        Self::new(PathBuf::from("static"))
    }
}

/// 拒绝最终组件符号链接的安全打开(修复 `resolve_path` canonicalize →
/// open 之间的 TOCTOU 符号链接窗口)
///
/// 语义:
/// - Linux 平台附加 fcntl `O_NOFOLLOW`(`0x20000`,asm-generic/fcntl.h):
///   最终组件若在 canonicalize 校验后被调换成符号链接,open 以 ELOOP
///   失败(fail-closed),杜绝读取越出 `static_root` 的目标文件;
///   对正常普通文件行为完全不变(resolve_path 已把中间组件的符号链接
///   全部解析到真实 inode,只有"校验后调换"的窗口需要本旗标兜底)。
/// - 其他平台(window/macOS 等):无等价开箱旗标可用时回退普通 open,
///   由 canonicalize 前置校验兜底(与修复前行为一致,未劣化)。
#[cfg(target_os = "linux")]
fn open_nofollow(path: &Path) -> std::io::Result<fs::File> {
    use std::os::unix::fs::OpenOptionsExt;
    fs::OpenOptions::new()
        .read(true)
        .custom_flags(0x20000) // O_NOFOLLOW(Linux asm-generic/fcntl.h)
        .open(path)
}

/// 见 [`open_nofollow`] 的 Linux 版本;非 Linux 平台回退普通 open + symlink 检查。
///
/// # 非 Linux TOCTOU 限制
///
/// 非 Linux 平台(Windows/macOS 等)无等价 `O_NOFOLLOW` 旗标可用。
/// 此实现使用 `symlink_metadata`(不跟随符号链接)在打开前检查最终
/// 组件是否为符号链接:若是则拒绝(fail-closed)。
///
/// **已知限制**:`symlink_metadata` 与 `File::open` 之间存在 TOCTOU
/// 窗口——理论上攻击者可在此间隙将普通文件替换为符号链接。生产环境
/// 使用 Linux `O_NOFOLLOW` 提供完整保护;非 Linux 仅用于开发环境。
#[cfg(not(target_os = "linux"))]
fn open_nofollow(path: &Path) -> std::io::Result<fs::File> {
    if fs::symlink_metadata(path)
        .map(|m| m.file_type().is_symlink())
        .unwrap_or(false)
    {
        return Err(std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "symlink rejected (non-Linux TOCTOU check)",
        ));
    }
    fs::File::open(path)
}

/// 静态文件服务处理器
#[derive(Debug, Clone)]
pub struct StaticFileServer {
    config: StaticConfig,
}

impl StaticFileServer {
    /// 创建静态文件服务器,`config` 指定配置
    pub fn new(config: StaticConfig) -> Self {
        Self { config }
    }

    /// 处理静态文件请求(无请求头,不启用条件/Range)
    pub fn serve(&self, requested_path: &str) -> Result<CanonicalResponse, WebError> {
        self.serve_with_headers(requested_path, &[])
    }

    /// 处理静态文件请求(带请求头,支持条件请求与 Range)
    ///
    /// `headers` 为 `(name, value)` 请求头切片,名称按 ASCII 大小写不敏感匹配。
    pub fn serve_with_headers(
        &self,
        requested_path: &str,
        headers: &[(&str, &str)],
    ) -> Result<CanonicalResponse, WebError> {
        let file_path = self.resolve_path(requested_path)?;
        let metadata = fs::metadata(&file_path)
            .map_err(|_| WebError::NotFound(format!("File not found: {}", requested_path)))?;

        if metadata.is_dir() {
            return self.serve_directory(&file_path, headers);
        }

        self.serve_file_with_headers(&file_path, &metadata, headers)
    }

    /// 解析安全路径(防止路径遍历攻击)
    fn resolve_path(&self, requested_path: &str) -> Result<PathBuf, WebError> {
        let root = self.config.root.canonicalize().map_err(|e| {
            WebError::InternalError(format!("Failed to resolve root: {}", e))
        })?;

        let clean_path = requested_path.trim_start_matches('/');
        let full_path = root.join(clean_path);

        // 路径遍历防护
        let canonical = full_path.canonicalize().map_err(|_| {
            WebError::NotFound(format!("File not found: {}", requested_path))
        })?;

        if !canonical.starts_with(&root) {
            return Err(WebError::Forbidden(
                "Path traversal detected".to_string(),
            ));
        }

        Ok(canonical)
    }

    /// 服务目录
    fn serve_directory(
        &self,
        dir_path: &Path,
        headers: &[(&str, &str)],
    ) -> Result<CanonicalResponse, WebError> {
        let default_file = dir_path.join(&self.config.default_file);
        if default_file.exists()
            && let Ok(metadata) = fs::metadata(&default_file) {
                return self.serve_file_with_headers(&default_file, &metadata, headers);
            }

        if self.config.directory_listing {
            self.generate_directory_listing(dir_path)
        } else {
            Err(WebError::Forbidden(
                "Directory listing disabled".to_string(),
            ))
        }
    }

    /// 服务文件(支持条件请求与 Range)
    fn serve_file_with_headers(
        &self,
        file_path: &Path,
        metadata: &fs::Metadata,
        headers: &[(&str, &str)],
    ) -> Result<CanonicalResponse, WebError> {
        let file_size = metadata.len();
        let file_name = file_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("unknown");

        // 生成 ETag 和 Last-Modified(条件请求与响应头都需要)
        let etag = self.generate_etag(file_path, metadata)?;
        let last_modified = self.format_last_modified(metadata)?;
        let modified = metadata
            .modified()
            .map_err(|e| WebError::InternalError(format!("{}", e)))?;
        let last_modified_secs = Self::time_to_epoch(modified);
        let content_type = Self::guess_content_type(file_name);

        // 按名称查找请求头(ASCII 大小写不敏感)
        let find_hdr = |name: &str| -> Option<&str> {
            headers
                .iter()
                .find(|(n, _)| n.eq_ignore_ascii_case(name))
                .map(|(_, v)| *v)
        };

        // --- 条件请求:If-None-Match / If-Modified-Since → 304 Not Modified ---
        if self.config.enable_conditional {
            let not_modified = if let Some(inm) = find_hdr("if-none-match") {
                // If-None-Match 优先于 If-Modified-Since(RFC 7232 §6)
                Self::etag_matches(inm, &etag)
            } else if let Some(ims) = find_hdr("if-modified-since") {
                // 文件 Last-Modified <= If-Modified-Since → 304
                Self::parse_http_date(ims)
                    .map(|ims_secs| last_modified_secs <= ims_secs)
                    .unwrap_or(false)
            } else {
                false
            };
            if not_modified {
                return Self::build_not_modified(&etag, &last_modified, self.config.cache_max_age);
            }
        }

        // --- Range 请求:bytes=start-end → 206 Partial Content / 416 ---
        if self.config.enable_range {
            if let Some(range_hdr) = find_hdr("range") {
                match Self::parse_range(range_hdr, file_size) {
                    Some((start, end)) => {
                        // 区间长度(end 为闭区间,故 +1),全部用 checked 算术
                        let length = end
                            .checked_sub(start)
                            .and_then(|l| l.checked_add(1))
                            .ok_or_else(|| {
                                WebError::InternalError("Range length overflow".to_string())
                            })?;
                        if usize::try_from(length)
                            .map(|l| l > self.config.max_file_size)
                            .unwrap_or(true)
                        {
                            return Err(WebError::Custom {
                                status: 413,
                                message: "Payload Too Large".to_string(),
                            });
                        }
                        let content = self.read_range(file_path, start, length)?;
                        return Self::build_partial_content(
                            content,
                            &content_type,
                            start,
                            end,
                            file_size,
                            &etag,
                            &last_modified,
                            self.config.cache_max_age,
                        );
                    }
                    None => {
                        // 无效/不可满足区间 → 416 Range Not Satisfiable
                        return Self::build_range_not_satisfiable(file_size);
                    }
                }
            }
        }

        // --- 有界读取:最多 max_file_size 字节,防止大文件内存耗尽 DoS ---
        if file_size > self.config.max_file_size as u64 {
            return Err(WebError::Custom {
                status: 413,
                message: "Payload Too Large".to_string(),
            });
        }
        let content = self.read_bounded(file_path)?;

        // 构建正常 200 响应
        let mut response = CanonicalResponse::new(200);

        response
            .add_header(b"content-type", content_type.as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(b"content-length", content.len().to_string().as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(b"etag", etag.as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(b"last-modified", last_modified.as_bytes())
            .map_err(WebError::from)?;
        if self.config.enable_range {
            response
                .add_header(b"accept-ranges", b"bytes")
                .map_err(WebError::from)?;
        }
        response
            .add_header(
                b"cache-control",
                format!("public, max-age={}", self.config.cache_max_age).as_bytes(),
            )
            .map_err(WebError::from)?;
        response.set_body(content);

        Ok(response)
    }

    /// 有界读取:循环 `Read::read` 到增长缓冲,超过 `max_file_size` 立即失败
    ///
    /// 不使用 `fs::read`(会一次性把任意大小文件载入内存),而是分块读取并在
    /// 每次写入前检查上限,防止内存耗尽 DoS。
    fn read_bounded(&self, file_path: &Path) -> Result<Vec<u8>, WebError> {
        let mut file = open_nofollow(file_path)
            .map_err(|e| WebError::InternalError(format!("Failed to open file: {}", e)))?;
        let mut buf = Vec::new();
        let mut tmp = [0u8; 8192];
        loop {
            let n = file
                .read(&mut tmp)
                .map_err(|e| WebError::InternalError(format!("Failed to read file: {}", e)))?;
            if n == 0 {
                break;
            }
            if buf.len().saturating_add(n) > self.config.max_file_size {
                return Err(WebError::Custom {
                    status: 413,
                    message: "Payload Too Large".to_string(),
                });
            }
            buf.extend_from_slice(&tmp[..n]);
        }
        Ok(buf)
    }

    /// 读取字节区间 `[start, start + length)`,循环读取保证读满(处理短读)
    fn read_range(&self, file_path: &Path, start: u64, length: u64) -> Result<Vec<u8>, WebError> {
        // TOCTOU 防护:与 read_bounded 一致使用 open_nofollow(O_NOFOLLOW),
        // 防止 canonicalize 后、open 前符号链接替换攻击
        let mut file = open_nofollow(file_path)
            .map_err(|e| WebError::InternalError(format!("Failed to open file: {}", e)))?;
        file.seek(SeekFrom::Start(start))
            .map_err(|e| WebError::InternalError(format!("Failed to seek file: {}", e)))?;
        let buf_len = usize::try_from(length)
            .map_err(|_| WebError::InternalError("Range length exceeds usize".to_string()))?;
        let mut buf = vec![0u8; buf_len];
        let mut filled = 0usize;
        while filled < buf.len() {
            let n = file
                .read(&mut buf[filled..])
                .map_err(|e| WebError::InternalError(format!("Failed to read range: {}", e)))?;
            if n == 0 {
                // 文件提前结束:截断到实际读到的字节
                buf.truncate(filled);
                break;
            }
            filled += n;
        }
        Ok(buf)
    }

    /// 构建 304 Not Modified 响应(空体,保留 ETag/Last-Modified/Cache-Control)
    fn build_not_modified(
        etag: &str,
        last_modified: &str,
        cache_max_age: u32,
    ) -> Result<CanonicalResponse, WebError> {
        let mut response = CanonicalResponse::new(304);
        response
            .add_header(b"etag", etag.as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(b"last-modified", last_modified.as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(
                b"cache-control",
                format!("public, max-age={}", cache_max_age).as_bytes(),
            )
            .map_err(WebError::from)?;
        Ok(response)
    }

    /// 构建 206 Partial Content 响应
    fn build_partial_content(
        content: Vec<u8>,
        content_type: &str,
        start: u64,
        end: u64,
        file_size: u64,
        etag: &str,
        last_modified: &str,
        cache_max_age: u32,
    ) -> Result<CanonicalResponse, WebError> {
        let mut response = CanonicalResponse::new(206);
        response
            .add_header(b"content-type", content_type.as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(b"content-length", content.len().to_string().as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(
                b"content-range",
                format!("bytes {}-{}/{}", start, end, file_size).as_bytes(),
            )
            .map_err(WebError::from)?;
        response
            .add_header(b"etag", etag.as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(b"last-modified", last_modified.as_bytes())
            .map_err(WebError::from)?;
        response
            .add_header(b"accept-ranges", b"bytes")
            .map_err(WebError::from)?;
        response
            .add_header(
                b"cache-control",
                format!("public, max-age={}", cache_max_age).as_bytes(),
            )
            .map_err(WebError::from)?;
        response.set_body(content);
        Ok(response)
    }

    /// 构建 416 Range Not Satisfiable 响应(带 Content-Range: bytes */size)
    fn build_range_not_satisfiable(file_size: u64) -> Result<CanonicalResponse, WebError> {
        let mut response = CanonicalResponse::new(416);
        response
            .add_header(b"content-range", format!("bytes */{}", file_size).as_bytes())
            .map_err(WebError::from)?;
        Ok(response)
    }

    /// ETag 匹配(RFC 7232 §2.3.2):支持 `*` 与逗号分隔列表,weak/strong 比较
    fn etag_matches(inm: &str, etag: &str) -> bool {
        let inm = inm.trim();
        if inm == "*" {
            return true;
        }
        // 比较时忽略 weak 前缀 W/
        let etag_norm = etag.strip_prefix("W/").unwrap_or(etag);
        inm.split(',').any(|tag| {
            let tag = tag.trim();
            let tag = tag.strip_prefix("W/").unwrap_or(tag);
            tag.eq_ignore_ascii_case(etag_norm)
        })
    }

    /// 解析 Range 头(`bytes=start-end`),返回 `[start, end]` 闭区间。
    /// 支持 `bytes=start-`(到结尾)与 `bytes=-N`(最后 N 字节)。
    /// 无效/不可满足返回 `None`(调用方返回 416)。全程使用 checked 算术。
    fn parse_range(range_hdr: &str, file_size: u64) -> Option<(u64, u64)> {
        if file_size == 0 {
            return None;
        }
        let s = range_hdr.trim();
        let s = s.strip_prefix("bytes=")?;
        let s = s.trim();
        // 仅支持第一个区间(多区间回退到 None → 416,保持简单且安全)
        let s = s.split(',').next()?;
        let s = s.trim();
        let (start_str, end_str) = s.split_once('-')?;
        let start_str = start_str.trim();
        let end_str = end_str.trim();

        let last = file_size.checked_sub(1)?;

        if start_str.is_empty() {
            // 后缀区间:bytes=-N → 最后 N 字节
            let n: u64 = end_str.parse().ok()?;
            if n == 0 {
                return None;
            }
            let start = if n >= file_size {
                0
            } else {
                file_size.checked_sub(n)?
            };
            Some((start, last))
        } else {
            let start: u64 = start_str.parse().ok()?;
            if start >= file_size {
                return None;
            }
            let end = if end_str.is_empty() {
                // 开放区间:bytes=start-
                last
            } else {
                let end: u64 = end_str.parse().ok()?;
                // end 为闭区间,截断到文件末尾
                if end > last {
                    last
                } else {
                    end
                }
            };
            if start > end {
                return None;
            }
            Some((start, end))
        }
    }

    /// HTTP 日期解析(RFC 7231 IMF-fixdate):`Sun, 06 Nov 1994 08:49:37 GMT` → epoch 秒
    fn parse_http_date(date: &str) -> Option<u64> {
        let s = date.trim();
        // 跳过星期与逗号(如存在)
        let s = s
            .split_once(',')
            .map(|(_, rest)| rest.trim())
            .unwrap_or(s);
        let mut parts = s.split_whitespace();
        let day_str = parts.next()?;
        let mon_str = parts.next()?;
        let year_str = parts.next()?;
        let time_str = parts.next()?;

        let day: u32 = day_str.parse().ok()?;
        let month = Self::month_to_num(mon_str)?;
        let year: u32 = year_str.parse().ok()?;
        let (hour, min, sec) = {
            let mut tp = time_str.split(':');
            let h: u32 = tp.next()?.parse().ok()?;
            let m: u32 = tp.next()?.parse().ok()?;
            let s: u32 = tp.next()?.parse().ok()?;
            (h, m, s)
        };
        Some(Self::datetime_to_epoch(year, month, day, hour, min, sec))
    }

    /// 月份缩写 → 月份数字(1-12)
    fn month_to_num(mon: &str) -> Option<u32> {
        match mon {
            "Jan" => Some(1),
            "Feb" => Some(2),
            "Mar" => Some(3),
            "Apr" => Some(4),
            "May" => Some(5),
            "Jun" => Some(6),
            "Jul" => Some(7),
            "Aug" => Some(8),
            "Sep" => Some(9),
            "Oct" => Some(10),
            "Nov" => Some(11),
            "Dec" => Some(12),
            _ => None,
        }
    }

    /// 日期时间 → epoch 秒([`epoch_to_datetime`](Self::epoch_to_datetime) 的逆运算,saturating 算术)
    fn datetime_to_epoch(year: u32, month: u32, day: u32, hour: u32, min: u32, sec: u32) -> u64 {
        let mut secs = 0u64;
        for y in 1970..year {
            secs = secs.saturating_add(if Self::is_leap_year(y) {
                366 * 86400
            } else {
                365 * 86400
            });
        }
        let days_in_months: [u32; 12] = if Self::is_leap_year(year) {
            [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        } else {
            [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        };
        // day_of_year = (day - 1) + 该月之前各月天数之和
        let mut day_of_year: u64 = (day.saturating_sub(1)) as u64;
        for &days in days_in_months.iter().take((month as usize).saturating_sub(1)) {
            day_of_year = day_of_year.saturating_add(days as u64);
        }
        secs = secs.saturating_add(day_of_year.saturating_mul(86400));
        secs = secs.saturating_add((hour as u64).saturating_mul(3600));
        secs = secs.saturating_add((min as u64).saturating_mul(60));
        secs = secs.saturating_add(sec as u64);
        secs
    }

    /// 生成 ETag
    fn generate_etag(&self, _file_path: &Path, metadata: &fs::Metadata) -> Result<String, WebError> {
        let modified = metadata
            .modified()
            .map_err(|e| WebError::InternalError(format!("{}", e)))?;
        let len = metadata.len();

        Ok(format!(
            "\"{:x}-{:x}\"",
            Self::time_to_epoch(modified),
            len
        ))
    }

    /// 格式化 Last-Modified (RFC 7231)
    fn format_last_modified(&self, metadata: &fs::Metadata) -> Result<String, WebError> {
        let modified = metadata
            .modified()
            .map_err(|e| WebError::InternalError(format!("{}", e)))?;

        let duration = modified
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|_| WebError::InternalError("Time error".to_string()))?;

        let secs = duration.as_secs();
        let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
        let months = [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        ];

        let (year, month, day, hour, min, sec, week_day) = Self::epoch_to_datetime(secs);
        let week = days[week_day as usize];
        let mon = months[month as usize];

        Ok(format!(
            "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT",
            week, day, mon, year, hour, min, sec
        ))
    }

    fn time_to_epoch(time: SystemTime) -> u64 {
        time.duration_since(SystemTime::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or_else(|_| 0)
    }

    fn epoch_to_datetime(secs: u64) -> (u32, u32, u32, u32, u32, u32, u32) {
        let mut year = 1970u32;
        let mut remaining = secs;

        loop {
            let year_secs = if Self::is_leap_year(year) { 366 * 86400 } else { 365 * 86400 };
            if remaining < year_secs {
                break;
            }
            remaining -= year_secs;
            year += 1;
        }

        let days_in_months: [u32; 12] = if Self::is_leap_year(year) {
            [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        } else {
            [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        };

        let day_of_year = (remaining / 86400) as u32;
        let time_of_day = remaining % 86400;

        let mut month = 0u32;
        let mut day = day_of_year + 1;
        for (i, &days) in days_in_months.iter().enumerate() {
            if day <= days {
                month = i as u32 + 1;
                break;
            }
            day -= days;
        }

        let hour = (time_of_day / 3600) as u32;
        let min = ((time_of_day % 3600) / 60) as u32;
        let sec = (time_of_day % 60) as u32;
        let week_day = (day_of_year + Self::days_since_epoch(year)) % 7;

        (year, month, day, hour, min, sec, week_day)
    }

    fn is_leap_year(year: u32) -> bool {
        (year.is_multiple_of(4) && !year.is_multiple_of(100)) || year.is_multiple_of(400)
    }

    fn days_since_epoch(year: u32) -> u32 {
        let mut days = 0u32;
        for y in 1970..year {
            days += if Self::is_leap_year(y) { 366 } else { 365 };
        }
        days
    }

    fn guess_content_type(filename: &str) -> String {
        let ext = Path::new(filename)
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_lowercase();

        match ext.as_str() {
            "html" | "htm" => "text/html".to_string(),
            "css" => "text/css".to_string(),
            "js" => "application/javascript".to_string(),
            "json" => "application/json".to_string(),
            "svg" => "image/svg+xml".to_string(),
            "png" => "image/png".to_string(),
            "jpg" | "jpeg" => "image/jpeg".to_string(),
            "gif" => "image/gif".to_string(),
            "ico" => "image/x-icon".to_string(),
            "webp" => "image/webp".to_string(),
            "woff" => "font/woff".to_string(),
            "woff2" => "font/woff2".to_string(),
            "ttf" => "font/ttf".to_string(),
            "pdf" => "application/pdf".to_string(),
            "zip" => "application/zip".to_string(),
            "xml" => "application/xml".to_string(),
            "txt" => "text/plain".to_string(),
            _ => "application/octet-stream".to_string(),
        }
    }

    fn generate_directory_listing(&self, dir_path: &Path) -> Result<CanonicalResponse, WebError> {
        /// HTML 转义(防存储型 XSS)
        fn html_escape(s: &str) -> String {
            s.replace('&', "&amp;")
                .replace('<', "&lt;")
                .replace('>', "&gt;")
                .replace('"', "&quot;")
                .replace('\'', "&#x27;")
        }

        let mut entries = Vec::new();
        if let Ok(read_dir) = fs::read_dir(dir_path) {
            for entry in read_dir.flatten() {
                let name = entry.file_name();
                let name_str = name.to_string_lossy().to_string();
                let is_dir = entry.path().is_dir();
                entries.push((name_str, is_dir));
            }
        }

        entries.sort();

        let mut html = String::from("<!DOCTYPE html><html><head><title>Directory listing</title></head><body>");
        html.push_str("<h1>Directory listing</h1><ul>");
        for (name, is_dir) in &entries {
            let suffix = if *is_dir { "/" } else { "" };
            // 文件名必须 HTML 转义(防存储型 XSS:恶意文件名注入 <script> 等)
            let esc = html_escape(name);
            html.push_str(&format!(
                "<li><a href=\"{}{}\">{}{}</a></li>",
                esc, suffix, esc, suffix
            ));
        }
        html.push_str("</ul></body></html>");

        let mut response = CanonicalResponse::new(200);
        response
            .add_header(b"content-type", b"text/html")
            .map_err(WebError::from)?;
        response.set_body(html.into_bytes());
        Ok(response)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::PathBuf;

    fn create_test_dir() -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let id = COUNTER.fetch_add(1, Ordering::SeqCst);
        
        let mut dir = std::env::temp_dir();
        dir.push(format!("zenith_static_test_{}_{}", std::process::id(), id));
        if dir.exists() {
            fs::remove_dir_all(&dir).ok();
        }
        fs::create_dir_all(&dir).unwrap();
        
        // 创建测试文件
        fs::write(dir.join("index.html"), b"<html>hello</html>").unwrap();
        fs::write(dir.join("style.css"), b"body { color: red; }").unwrap();
        fs::write(dir.join("app.js"), b"console.log('hi')").unwrap();
        fs::write(dir.join("data.json"), b"{}").unwrap();
        fs::write(dir.join("image.png"), b"\x89PNG\r\n\x1a\n").unwrap();
        
        // 创建子目录
        let subdir = dir.join("subdir");
        fs::create_dir_all(&subdir).unwrap();
        fs::write(subdir.join("nested.txt"), b"nested content").unwrap();
        
        dir
    }

    fn cleanup_test_dir(dir: &PathBuf) {
        if dir.exists() {
            fs::remove_dir_all(dir).ok();
        }
    }

    /// 回归(TOCTOU 符号链接窗口):Linux 下 `open_nofollow` 必须拒绝
    /// 最终组件符号链接(ELOOP 拒绝,fail-closed);普通文件行为不变。
    #[cfg(target_os = "linux")]
    #[test]
    fn open_nofollow_rejects_symlink_and_opens_regular() {
        use std::os::unix::fs::symlink;
        let dir = create_test_dir();
        let target = dir.join("index.html");
        let link = dir.join("evil_link");

        // 目录内符号链接 → 拒绝
        symlink(&target, &link).expect("create symlink");
        let err = open_nofollow(&link).unwrap_err();
        assert!(
            err.raw_os_error().is_some(),
            "symlink open must fail with os error: {err}"
        );

        // 指向静态根外部的符号链接(模拟逃逸尝试)→ 必须拒绝
        let escape_link = dir.join("escape");
        symlink("/etc/passwd", &escape_link).expect("create escape symlink");
        assert!(
            open_nofollow(&escape_link).is_err(),
            "escape symlink must be rejected"
        );

        // 普通文件:行为完全不变
        assert!(
            open_nofollow(&target).is_ok(),
            "regular file must open normally"
        );

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_static_config_defaults() {
        let config = StaticConfig::new("/tmp");
        assert_eq!(config.default_file, "index.html");
        assert!(!config.directory_listing);
        assert_eq!(config.cache_max_age, 3600);
        assert!(config.enable_range);
        assert!(config.enable_conditional);
    }

    #[test]
    fn test_static_config_builders() {
        let config = StaticConfig::new("/tmp")
            .with_default_file("default.htm")
            .with_directory_listing(true)
            .with_cache_max_age(7200)
            .with_range(false)
            .with_conditional(false);
        
        assert_eq!(config.default_file, "default.htm");
        assert!(config.directory_listing);
        assert_eq!(config.cache_max_age, 7200);
        assert!(!config.enable_range);
        assert!(!config.enable_conditional);
    }

    #[test]
    fn test_static_config_default_trait() {
        let config = StaticConfig::default();
        assert_eq!(config.root, PathBuf::from("static"));
        assert_eq!(config.default_file, "index.html");
    }

    #[test]
    fn test_guess_content_type_all_types() {
        assert_eq!(StaticFileServer::guess_content_type("index.html"), "text/html");
        assert_eq!(StaticFileServer::guess_content_type("page.htm"), "text/html");
        assert_eq!(StaticFileServer::guess_content_type("style.css"), "text/css");
        assert_eq!(StaticFileServer::guess_content_type("app.js"), "application/javascript");
        assert_eq!(StaticFileServer::guess_content_type("data.json"), "application/json");
        assert_eq!(StaticFileServer::guess_content_type("image.svg"), "image/svg+xml");
        assert_eq!(StaticFileServer::guess_content_type("image.png"), "image/png");
        assert_eq!(StaticFileServer::guess_content_type("photo.jpg"), "image/jpeg");
        assert_eq!(StaticFileServer::guess_content_type("photo.jpeg"), "image/jpeg");
        assert_eq!(StaticFileServer::guess_content_type("anim.gif"), "image/gif");
        assert_eq!(StaticFileServer::guess_content_type("favicon.ico"), "image/x-icon");
        assert_eq!(StaticFileServer::guess_content_type("img.webp"), "image/webp");
        assert_eq!(StaticFileServer::guess_content_type("font.woff"), "font/woff");
        assert_eq!(StaticFileServer::guess_content_type("font.woff2"), "font/woff2");
        assert_eq!(StaticFileServer::guess_content_type("font.ttf"), "font/ttf");
        assert_eq!(StaticFileServer::guess_content_type("doc.pdf"), "application/pdf");
        assert_eq!(StaticFileServer::guess_content_type("archive.zip"), "application/zip");
        assert_eq!(StaticFileServer::guess_content_type("data.xml"), "application/xml");
        assert_eq!(StaticFileServer::guess_content_type("notes.txt"), "text/plain");
        assert_eq!(StaticFileServer::guess_content_type("unknown.xyz"), "application/octet-stream");
        assert_eq!(StaticFileServer::guess_content_type("noextension"), "application/octet-stream");
    }

    #[test]
    fn test_guess_content_type_case_insensitive() {
        assert_eq!(StaticFileServer::guess_content_type("FILE.HTML"), "text/html");
        assert_eq!(StaticFileServer::guess_content_type("Image.PNG"), "image/png");
        assert_eq!(StaticFileServer::guess_content_type("data.JSON"), "application/json");
    }

    fn with_canonical_root(config: StaticConfig) -> (StaticConfig, PathBuf) {
        let canonical = config.root.canonicalize().unwrap();
        let mut config = config;
        config.root = canonical.clone();
        (config, canonical)
    }

    #[test]
    fn test_resolve_path_traversal_relative() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.resolve_path("../../../etc/passwd");
        assert!(result.is_err());
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_resolve_path_traversal_encoded() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.resolve_path("..%2F..%2Fetc%2Fpasswd");
        assert!(result.is_err());
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_resolve_path_normal() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.resolve_path("index.html");
        assert!(result.is_ok());
        let path = result.unwrap();
        assert!(path.ends_with("index.html"));
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_resolve_path_nested() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.resolve_path("subdir/nested.txt");
        assert!(result.is_ok());
        let path = result.unwrap();
        assert!(path.ends_with("nested.txt"));
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_resolve_path_with_leading_slash() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.resolve_path("/index.html");
        assert!(result.is_ok());
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_file_exists() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.serve("index.html");
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.status_code, 200);
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_file_not_found() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.serve("nonexistent.txt");
        assert!(result.is_err());
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_file_content_type() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.serve("style.css");
        assert!(result.is_ok());
        let response = result.unwrap();
        
        let ct = response.find_header("content-type");
        assert!(ct.is_some());
        assert_eq!(ct.unwrap().value_str(), "text/css");
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_file_cache_headers() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir).with_cache_max_age(86400));
        let server = StaticFileServer::new(config);

        let result = server.serve("index.html");
        assert!(result.is_ok());
        let response = result.unwrap();
        
        let cc = response.find_header("cache-control");
        assert!(cc.is_some());
        assert!(cc.unwrap().value_str().contains("max-age=86400"));
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_file_etag_and_last_modified() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.serve("index.html");
        assert!(result.is_ok());
        let response = result.unwrap();
        
        assert!(response.find_header("etag").is_some());
        assert!(response.find_header("last-modified").is_some());
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_directory_default_file() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        let result = server.serve("");
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.status_code, 200);
        assert_eq!(response.body(), b"<html>hello</html>");
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_directory_listing_disabled() {
        let dir = create_test_dir();
        let subdir = dir.join("subdir");
        let default_file = subdir.join("index.html");
        if default_file.exists() {
            fs::remove_file(&default_file).ok();
        }
        
        let (config, _) = with_canonical_root(StaticConfig::new(&dir).with_directory_listing(false));
        let server = StaticFileServer::new(config);

        let result = server.serve("subdir/");
        assert!(result.is_err());
        match result.unwrap_err() {
            WebError::Forbidden(_) => {},
            _ => panic!("Expected Forbidden error"),
        }
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_directory_listing_enabled() {
        let dir = create_test_dir();
        let subdir = dir.join("subdir");
        let default_file = subdir.join("index.html");
        if default_file.exists() {
            fs::remove_file(&default_file).ok();
        }
        
        let (config, _) = with_canonical_root(StaticConfig::new(&dir).with_directory_listing(true));
        let server = StaticFileServer::new(config);

        let result = server.serve("subdir/");
        assert!(result.is_ok());
        let response = result.unwrap();
        assert_eq!(response.status_code, 200);
        
        let body = String::from_utf8_lossy(response.body());
        assert!(body.contains("Directory listing"));
        assert!(body.contains("nested.txt"));
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_generate_directory_listing_sorting() {
        let dir = create_test_dir();
        let subdir = dir.join("list_test");
        fs::create_dir_all(&subdir).unwrap();
        fs::write(subdir.join("b.txt"), b"b").unwrap();
        fs::write(subdir.join("a.txt"), b"a").unwrap();
        fs::create_dir_all(subdir.join("cdir")).unwrap();
        
        let (config, _) = with_canonical_root(StaticConfig::new(&dir).with_directory_listing(true));
        let server = StaticFileServer::new(config);
        
        let result = server.serve("list_test/");
        assert!(result.is_ok());
        let response = result.unwrap();
        let body = String::from_utf8_lossy(response.body());
        
        assert!(body.contains("a.txt"));
        assert!(body.contains("b.txt"));
        assert!(body.contains("cdir/"));
        
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_epoch_to_datetime_epoch_start() {
        let (year, month, day, hour, min, sec, _week) =
            StaticFileServer::epoch_to_datetime(0);
        assert_eq!(year, 1970);
        assert_eq!(month, 1);
        assert_eq!(day, 1);
        assert_eq!(hour, 0);
        assert_eq!(min, 0);
        assert_eq!(sec, 0);
    }

    #[test]
    fn test_epoch_to_datetime_known_date() {
        // 2023-12-25 12:30:45 UTC
        // 计算:使用已知时间戳
        let (year, month, day, hour, min, sec, _week) =
            StaticFileServer::epoch_to_datetime(1703507445);
        assert_eq!(year, 2023);
        assert_eq!(month, 12);
        assert_eq!(day, 25);
        assert_eq!(hour, 12);
        assert_eq!(min, 30);
        assert_eq!(sec, 45);
    }

    #[test]
    fn test_is_leap_year_edge_cases() {
        assert!(StaticFileServer::is_leap_year(2000));
        assert!(!StaticFileServer::is_leap_year(1900));
        assert!(StaticFileServer::is_leap_year(2024));
        assert!(!StaticFileServer::is_leap_year(2023));
        assert!(!StaticFileServer::is_leap_year(2022));
        assert!(!StaticFileServer::is_leap_year(2021));
        assert!(StaticFileServer::is_leap_year(2020));
        assert!(StaticFileServer::is_leap_year(2400));
        assert!(!StaticFileServer::is_leap_year(2100));
    }

    #[test]
    fn test_time_to_epoch() {
        let t = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1000);
        assert_eq!(StaticFileServer::time_to_epoch(t), 1000);
    }

    #[test]
    fn test_days_since_epoch() {
        assert_eq!(StaticFileServer::days_since_epoch(1970), 0);
        assert_eq!(StaticFileServer::days_since_epoch(1971), 365);
        assert_eq!(StaticFileServer::days_since_epoch(1972), 730); // 1972 是闰年
    }

    #[test]
    fn test_server_creation() {
        let config = StaticConfig::new("/tmp");
        let server = StaticFileServer::new(config);
        assert_eq!(server.config.cache_max_age, 3600);
    }

    // ------------------------------------------------------------------
    // ISSUE L9:有界读取 / 条件请求 / Range 回归测试
    // ------------------------------------------------------------------

    #[test]
    fn test_static_config_max_file_size_default() {
        let config = StaticConfig::new("/tmp");
        assert_eq!(config.max_file_size, DEFAULT_MAX_FILE_SIZE);
        assert_eq!(config.max_file_size, 16 * 1024 * 1024);
        let config = StaticConfig::new("/tmp").with_max_file_size(1024);
        assert_eq!(config.max_file_size, 1024);
    }

    #[test]
    fn test_serve_large_file_rejected() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir).with_max_file_size(1024));
        let server = StaticFileServer::new(config);
        // 写入超过上限的文件
        fs::write(dir.join("big.bin"), vec![0u8; 2048]).unwrap();
        let result = server.serve("big.bin");
        assert!(result.is_err());
        match result.unwrap_err() {
            WebError::Custom { status, .. } => assert_eq!(status, 413),
            other => panic!("Expected 413 Payload Too Large, got {:?}", other),
        }
        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_if_none_match_304() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        // 先获取 ETag
        let resp = server.serve("index.html").unwrap();
        assert_eq!(resp.status_code, 200);
        let etag = resp.find_header("etag").unwrap().value_str().to_string();

        // 用匹配的 If-None-Match 请求 → 304(空体,保留 ETag)
        let result = server.serve_with_headers("index.html", &[("if-none-match", etag.as_str())]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 304);
        assert!(resp.body().is_empty());
        assert!(resp.find_header("etag").is_some());

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_if_none_match_star_304() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        // If-None-Match: * 匹配任意存在资源 → 304
        let result = server.serve_with_headers("index.html", &[("if-none-match", "*")]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 304);

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_if_none_match_no_match_200() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        // 不匹配的 ETag → 200
        let result =
            server.serve_with_headers("index.html", &[("if-none-match", "\"deadbeef\"")]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 200);

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_if_modified_since_304() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        // 先获取 Last-Modified
        let resp = server.serve("index.html").unwrap();
        let lm = resp.find_header("last-modified").unwrap().value_str().to_string();

        // 用相同的 If-Modified-Since → 304(Last-Modified <= IMS)
        let result =
            server.serve_with_headers("index.html", &[("if-modified-since", lm.as_str())]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 304);
        assert!(resp.body().is_empty());

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_if_modified_since_future_304() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        // 远未来的 If-Modified-Since → 304
        let result = server.serve_with_headers(
            "index.html",
            &[("if-modified-since", "Wed, 01 Jan 2099 00:00:00 GMT")],
        );
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 304);

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_if_modified_since_past_200() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);

        // 远过去的 If-Modified-Since → 文件比该日期新 → 200
        let result = server.serve_with_headers(
            "index.html",
            &[("if-modified-since", "Thu, 01 Jan 1970 00:00:00 GMT")],
        );
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 200);

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_range_206() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);
        fs::write(dir.join("range.txt"), b"0123456789ABCDEF").unwrap(); // 16 字节

        let result = server.serve_with_headers("range.txt", &[("range", "bytes=2-5")]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 206);
        assert_eq!(resp.body(), b"2345");
        let cr = resp.find_header("content-range").unwrap().value_str();
        assert_eq!(cr, "bytes 2-5/16");
        let cl = resp.find_header("content-length").unwrap().value_str();
        assert_eq!(cl, "4");

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_range_open_ended_206() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);
        fs::write(dir.join("range.txt"), b"0123456789ABCDEF").unwrap();

        // bytes=4- → 从第 4 字节到结尾
        let result = server.serve_with_headers("range.txt", &[("range", "bytes=4-")]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 206);
        assert_eq!(resp.body(), b"456789ABCDEF");

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_range_suffix_206() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);
        fs::write(dir.join("range.txt"), b"0123456789ABCDEF").unwrap();

        // bytes=-4 → 最后 4 字节
        let result = server.serve_with_headers("range.txt", &[("range", "bytes=-4")]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 206);
        assert_eq!(resp.body(), b"CDEF");

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_invalid_range_416() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir));
        let server = StaticFileServer::new(config);
        fs::write(dir.join("range.txt"), b"0123456789ABCDEF").unwrap();

        // 起点超出文件大小 → 416
        let result = server.serve_with_headers("range.txt", &[("range", "bytes=100-200")]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 416);
        let cr = resp.find_header("content-range").unwrap().value_str();
        assert_eq!(cr, "bytes */16");

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_range_disabled_ignored() {
        let dir = create_test_dir();
        let (config, _) = with_canonical_root(StaticConfig::new(&dir).with_range(false));
        let server = StaticFileServer::new(config);
        fs::write(dir.join("range.txt"), b"0123456789ABCDEF").unwrap();

        // Range 关闭时忽略 Range 头,返回完整 200
        let result = server.serve_with_headers("range.txt", &[("range", "bytes=2-5")]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 200);
        assert_eq!(resp.body(), b"0123456789ABCDEF");

        cleanup_test_dir(&dir);
    }

    #[test]
    fn test_serve_conditional_disabled_ignored() {
        let dir = create_test_dir();
        let (config, _) =
            with_canonical_root(StaticConfig::new(&dir).with_conditional(false));
        let server = StaticFileServer::new(config);

        // 先获取 ETag
        let resp = server.serve("index.html").unwrap();
        let etag = resp.find_header("etag").unwrap().value_str().to_string();

        // 条件请求关闭时忽略 If-None-Match,返回 200
        let result =
            server.serve_with_headers("index.html", &[("if-none-match", etag.as_str())]);
        assert!(result.is_ok());
        let resp = result.unwrap();
        assert_eq!(resp.status_code, 200);

        cleanup_test_dir(&dir);
    }

    // --- 纯函数单元测试 ---

    #[test]
    fn test_parse_range_basic() {
        assert_eq!(
            StaticFileServer::parse_range("bytes=0-499", 1000),
            Some((0, 499))
        );
        assert_eq!(
            StaticFileServer::parse_range("bytes=500-", 1000),
            Some((500, 999))
        );
        assert_eq!(
            StaticFileServer::parse_range("bytes=-500", 1000),
            Some((500, 999))
        );
        // 后缀超过文件大小 → 从 0 开始
        assert_eq!(
            StaticFileServer::parse_range("bytes=-2000", 1000),
            Some((0, 999))
        );
    }

    #[test]
    fn test_parse_range_invalid() {
        // 起点超出文件大小
        assert_eq!(StaticFileServer::parse_range("bytes=1000-2000", 1000), None);
        // start > end
        assert_eq!(StaticFileServer::parse_range("bytes=500-100", 1000), None);
        // 文件大小为 0
        assert_eq!(StaticFileServer::parse_range("bytes=0-10", 0), None);
        // 后缀为 0
        assert_eq!(StaticFileServer::parse_range("bytes=-0", 1000), None);
        // 非 bytes= 前缀
        assert_eq!(StaticFileServer::parse_range("items=0-10", 1000), None);
    }

    #[test]
    fn test_etag_matches() {
        assert!(StaticFileServer::etag_matches("*", "\"abc\""));
        assert!(StaticFileServer::etag_matches("\"abc\"", "\"abc\""));
        // 大小写不敏感
        assert!(StaticFileServer::etag_matches("\"ABC\"", "\"abc\""));
        // 列表
        assert!(StaticFileServer::etag_matches("\"x\", \"abc\", \"y\"", "\"abc\""));
        // weak 前缀
        assert!(StaticFileServer::etag_matches("W/\"abc\"", "\"abc\""));
        assert!(StaticFileServer::etag_matches("\"abc\"", "W/\"abc\""));
        // 不匹配
        assert!(!StaticFileServer::etag_matches("\"def\"", "\"abc\""));
    }

    #[test]
    fn test_parse_http_date_and_inverse() {
        // IMF-fixdate 解析(经典 HTTP 日期示例)
        let secs = StaticFileServer::parse_http_date("Sun, 06 Nov 1994 08:49:37 GMT");
        assert_eq!(secs, Some(784111777));
        // 逆运算应回到同一日期
        let (y, m, d, h, mi, s, _) = StaticFileServer::epoch_to_datetime(secs.unwrap());
        assert_eq!((y, m, d, h, mi, s), (1994, 11, 6, 8, 49, 37));
    }

    #[test]
    fn test_datetime_to_epoch_known() {
        // 2023-12-25 12:30:45 UTC = 1703507445(与 epoch_to_datetime 测试一致)
        assert_eq!(
            StaticFileServer::datetime_to_epoch(2023, 12, 25, 12, 30, 45),
            1703507445
        );
        // epoch 起点
        assert_eq!(StaticFileServer::datetime_to_epoch(1970, 1, 1, 0, 0, 0), 0);
    }
}