asupersync 0.3.9

Spec-first, cancel-correct, capability-secure async runtime for 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
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
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
//! Static file serving with caching, ETag, and conditional request support.
//!
//! Serves files from a directory with automatic MIME detection, strong ETags,
//! `Cache-Control` headers, and `If-None-Match` / `304 Not Modified` support.
//!
//! # Example
//!
//! ```ignore
//! use asupersync::web::static_files::StaticFiles;
//! use asupersync::web::{Router, get};
//!
//! let statics = StaticFiles::new("./public");
//! let app = Router::new()
//!     .route("/static/*path", get(statics.handler()));
//! ```
//!
//! # Security
//!
//! Path traversal attacks (`../`) are blocked. Symlinks are not followed by
//! default.

use std::collections::HashMap;
use std::fmt;
use std::fmt::Write as _;
use std::io::Read as _;
use std::path::{Path, PathBuf};

use crate::bytes::Bytes;
use sha2::{Digest, Sha256};

use super::handler::Handler;
use super::response::{Response, StatusCode};

/// Default max-age for Cache-Control (1 hour).
const DEFAULT_MAX_AGE: u32 = 3600;

/// Default maximum file size to serve (256 MiB).
const DEFAULT_MAX_FILE_SIZE: u64 = 256 * 1024 * 1024;

const CONTENT_TYPE_OPTIONS_HEADER: &str = "x-content-type-options";
const CONTENT_TYPE_OPTIONS_NOSNIFF: &str = "nosniff";

/// A byte range for partial content requests.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ByteRange {
    start: usize,
    end: usize, // inclusive
}

/// Error types for Range header parsing.
#[derive(Debug, Clone, PartialEq, Eq)]
enum RangeError {
    InvalidSyntax,
    NotSatisfiable,
}

/// Maximum number of comma-separated range specs accepted in one `Range`
/// header. Without a cap, `Range: bytes=0-,0-,0-,…` (thousands of whole-file
/// prefix ranges packed into a header) forces `num_specs × file_size` bytes to
/// be buffered into one multipart body — the classic multi-range
/// memory-amplification DoS (CVE-2011-3192, "Apache Killer"). Real clients ask
/// for a handful of ranges; a request exceeding this cap is rejected.
const MAX_RANGE_SPECS: usize = 64;

/// Returns true if a path component is a hidden (dot-prefixed) name that must
/// not be served. `.well-known` is exempted (RFC 8615 / ACME discovery). Empty
/// components (from `//` or leading/trailing `/`) are not hidden.
fn is_denied_hidden_component(component: &str) -> bool {
    component.starts_with('.') && component != ".well-known"
}

/// Parse Range header and return satisfiable byte ranges.
/// RFC 9110 §14.1.2 Range specification.
///
/// Overlapping or adjacent satisfiable ranges are coalesced (RFC 9110 §14.1.2
/// permits, and §14.2 recommends, coalescing to bound the response), which
/// guarantees the total emitted bytes never exceed `file_size` regardless of
/// how many duplicate/overlapping specs the client sends.
fn parse_ranges(range_header: &str, file_size: u64) -> Result<Vec<ByteRange>, RangeError> {
    let range_header = range_header.trim();
    let Some(ranges_str) = range_header.strip_prefix("bytes=") else {
        return Err(RangeError::InvalidSyntax);
    };

    // Bound parse work and the eventual multipart part count before doing any
    // per-spec work. `bytes=` followed by N commas is N+1 specs.
    if ranges_str.bytes().filter(|&b| b == b',').count() >= MAX_RANGE_SPECS {
        return Err(RangeError::NotSatisfiable);
    }

    let mut ranges = Vec::new();

    for range_spec in ranges_str.split(',') {
        let range_spec = range_spec.trim();

        // Skip empty elements (from `,,` or a leading/trailing comma) rather
        // than rejecting the whole header — RFC 7230 §7's legacy list rule says
        // empty list elements do not contribute and must be ignored. A lenient
        // client sending `bytes=0-100,` should still get its range.
        if range_spec.is_empty() {
            continue;
        }

        if let Some((start_str, end_str)) = range_spec.split_once('-') {
            if start_str.is_empty() && end_str.is_empty() {
                return Err(RangeError::InvalidSyntax);
            }

            let range = if start_str.is_empty() {
                // Suffix range: bytes=-500 (last 500 bytes)
                if let Ok(suffix_length) = end_str.parse::<u64>() {
                    if suffix_length == 0 || file_size == 0 {
                        continue; // Skip invalid suffix ranges
                    }
                    let start = file_size.saturating_sub(suffix_length);
                    ByteRange {
                        start: start as usize,
                        end: (file_size - 1) as usize,
                    }
                } else {
                    return Err(RangeError::InvalidSyntax);
                }
            } else if end_str.is_empty() {
                // Prefix range: bytes=500- (from byte 500 to end)
                if let Ok(start) = start_str.parse::<u64>() {
                    if start >= file_size {
                        continue; // Skip ranges beyond file size
                    }
                    ByteRange {
                        start: start as usize,
                        end: (file_size - 1) as usize,
                    }
                } else {
                    return Err(RangeError::InvalidSyntax);
                }
            } else {
                // Full range: bytes=0-499
                let start = start_str
                    .parse::<u64>()
                    .map_err(|_| RangeError::InvalidSyntax)?;
                let end = end_str
                    .parse::<u64>()
                    .map_err(|_| RangeError::InvalidSyntax)?;

                if start > end || start >= file_size {
                    continue; // Skip invalid or unsatisfiable ranges
                }

                let actual_end = std::cmp::min(end, file_size - 1);
                ByteRange {
                    start: start as usize,
                    end: actual_end as usize,
                }
            };

            ranges.push(range);
        } else {
            return Err(RangeError::InvalidSyntax);
        }
    }

    if ranges.is_empty() {
        return Err(RangeError::NotSatisfiable);
    }

    // Coalesce overlapping/adjacent ranges so the emitted body is bounded by
    // `file_size`. Sorting by start makes a single linear merge sufficient.
    // This defeats amplification via duplicated/overlapping specs (e.g. many
    // `0-`) which would otherwise each re-emit the whole file.
    ranges.sort_by_key(|r| (r.start, r.end));
    let mut coalesced: Vec<ByteRange> = Vec::with_capacity(ranges.len());
    for range in ranges {
        match coalesced.last_mut() {
            // Overlapping or directly adjacent (`prev.end + 1 == range.start`)
            // ranges merge into one contiguous slice.
            Some(prev) if range.start <= prev.end.saturating_add(1) => {
                prev.end = prev.end.max(range.end);
            }
            _ => coalesced.push(range),
        }
    }

    Ok(coalesced)
}

// ─── StaticFiles ────────────────────────────────────────────────────────────

/// Configuration for static file serving.
#[derive(Clone)]
pub struct StaticFiles {
    root: PathBuf,
    max_age: u32,
    max_file_size: u64,
    index_file: Option<String>,
    custom_headers: HashMap<String, String>,
}

impl fmt::Debug for StaticFiles {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("StaticFiles")
            .field("root", &self.root)
            .field("max_age", &self.max_age)
            .field("max_file_size", &self.max_file_size)
            .field("index_file", &self.index_file)
            .field("custom_headers", &self.custom_headers)
            .finish()
    }
}

impl StaticFiles {
    /// Create a new static file server rooted at the given directory.
    #[must_use]
    pub fn new(root: impl Into<PathBuf>) -> Self {
        let mut custom_headers = HashMap::new();
        custom_headers.insert(
            CONTENT_TYPE_OPTIONS_HEADER.to_string(),
            CONTENT_TYPE_OPTIONS_NOSNIFF.to_string(),
        );

        Self {
            root: root.into(),
            max_age: DEFAULT_MAX_AGE,
            max_file_size: DEFAULT_MAX_FILE_SIZE,
            index_file: Some("index.html".to_string()),
            custom_headers,
        }
    }

    /// Set the `Cache-Control: max-age` value in seconds.
    #[must_use]
    pub fn max_age(mut self, seconds: u32) -> Self {
        self.max_age = seconds;
        self
    }

    /// Set the maximum file size to serve in bytes.
    ///
    /// Files larger than this limit receive a 413 Payload Too Large response.
    /// Defaults to 256 MiB.
    #[must_use]
    pub fn max_file_size(mut self, bytes: u64) -> Self {
        self.max_file_size = bytes;
        self
    }

    /// Set the index file name (served for directory requests). Pass `None` to disable.
    #[must_use]
    pub fn index_file(mut self, name: Option<impl Into<String>>) -> Self {
        self.index_file = name.map(Into::into);
        self
    }

    /// Add a custom response header to all served files.
    #[must_use]
    pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.custom_headers
            .insert(name.into().to_ascii_lowercase(), value.into());
        self
    }

    fn apply_custom_headers(&self, mut response: Response) -> Response {
        for (k, v) in &self.custom_headers {
            response = response.header(k, v);
        }
        response
    }

    /// Resolve a request path to a file, applying security checks.
    fn resolve_path(&self, request_path: &str) -> Option<PathBuf> {
        // Strip leading slash and URL decode.
        let cleaned = request_path.trim_start_matches('/');
        let decoded = percent_decode(cleaned);

        // Reject traversal, ambiguous Windows separators, and hidden files.
        // Repeat the same policy after bounded additional decoding so a proxy
        // or downstream hop cannot turn a latent escape into a separator or
        // dotfile. URL paths use `/`; accepting `\` would make path meaning
        // platform-dependent. `.well-known` remains exempt only in canonical
        // slash-separated form for ACME / RFC 8615 discovery.
        if has_denied_static_path(&decoded)
            || has_denied_static_path_after_additional_decoding(&decoded)
        {
            return None;
        }

        let root_canonical = self.root.canonicalize().ok()?;
        let mut relative_path = PathBuf::from(&decoded);
        if path_contains_symlink(&root_canonical, &relative_path) {
            return None;
        }

        let mut full_path = root_canonical.join(&relative_path);

        // If it's a directory and we have an index file, try that.
        if full_path.is_dir() {
            let index = self.index_file.as_ref()?;
            relative_path.push(index);
            if path_contains_symlink(&root_canonical, &relative_path) {
                return None;
            }
            full_path = full_path.join(index);
        }

        // Canonicalize and verify it's under root.
        let canonical = full_path.canonicalize().ok()?;
        if !canonical.starts_with(&root_canonical) {
            return None;
        }

        if canonical.is_file() {
            Some(canonical)
        } else {
            None
        }
    }

    fn validated_current_path(&self, path: &Path) -> Option<PathBuf> {
        let root_canonical = self.root.canonicalize().ok()?;
        let relative_path = path.strip_prefix(&root_canonical).ok()?;
        if path_contains_symlink(&root_canonical, relative_path) {
            return None;
        }

        let canonical = path.canonicalize().ok()?;
        if !canonical.starts_with(&root_canonical) || !canonical.is_file() {
            return None;
        }

        Some(canonical)
    }

    /// Serve a file, handling ETag and conditional requests.
    fn serve_file(&self, path: &Path, if_none_match: Option<&str>) -> Response {
        let Some(path) = self.validated_current_path(path) else {
            return Response::empty(StatusCode::NOT_FOUND);
        };

        let Ok(mut file) = open_static_file(&path) else {
            return Response::empty(StatusCode::NOT_FOUND);
        };

        // Read file metadata from the opened handle so the file we size-check is
        // the same one whose body we later hash and serve.
        let Ok(metadata) = file.metadata() else {
            return Response::empty(StatusCode::INTERNAL_SERVER_ERROR);
        };

        if metadata.len() > self.max_file_size {
            return Response::empty(StatusCode::PAYLOAD_TOO_LARGE);
        }

        // Read file contents before generating the ETag. Strong ETags must be
        // content-derived, not just metadata-derived.
        let mut body = Vec::with_capacity(metadata.len().try_into().unwrap_or(0));
        if file.read_to_end(&mut body).is_err() {
            return Response::empty(StatusCode::INTERNAL_SERVER_ERROR);
        }

        let etag = generate_etag(&body);

        // Check If-None-Match.
        if let Some(client_etag) = if_none_match {
            if etag_matches(client_etag, &etag) {
                return self.apply_custom_headers(
                    Response::empty(StatusCode::NOT_MODIFIED)
                        .header("etag", &etag)
                        .header("accept-ranges", "bytes")
                        .header("cache-control", format!("public, max-age={}", self.max_age)),
                );
            }
        }

        let mime = guess_mime(&path);

        let response = Response::new(StatusCode::OK, body)
            .header("content-type", mime)
            .header("etag", &etag)
            .header("accept-ranges", "bytes")
            .header("cache-control", format!("public, max-age={}", self.max_age));

        self.apply_custom_headers(response)
    }

    /// Serve a file with Range request support (RFC 9110 §15.3.7).
    fn serve_range(
        &self,
        path: &Path,
        range_header: &str,
        if_none_match: Option<&str>,
    ) -> Response {
        let Some(path) = self.validated_current_path(path) else {
            return Response::empty(StatusCode::NOT_FOUND);
        };

        let Ok(mut file) = open_static_file(&path) else {
            return Response::empty(StatusCode::NOT_FOUND);
        };

        let metadata = match file.metadata() {
            Ok(meta) => meta,
            Err(_) => return Response::empty(StatusCode::INTERNAL_SERVER_ERROR),
        };

        let file_size = metadata.len();
        if file_size > self.max_file_size {
            return Response::empty(StatusCode::PAYLOAD_TOO_LARGE);
        }

        // br-asupersync-42wywh: RFC 9110 §13.2.2 — "An origin server
        // that supports Range MUST evaluate the request preconditions
        // before doing so." Read the body and compute the ETag first
        // so a matching If-None-Match returns 304 even when the Range
        // header is malformed or unsatisfiable. Pre-fix the Range
        // parser ran first and short-circuited to 416, forcing
        // already-cached clients into a needless full refetch.
        let mut file_content = Vec::new();
        if file.read_to_end(&mut file_content).is_err() {
            return Response::empty(StatusCode::INTERNAL_SERVER_ERROR);
        }
        // Range math and the reported total MUST use the number of bytes we
        // actually read, not the earlier `metadata.len()`. If the file was
        // truncated between fstat and read (concurrent redeploy/truncate), the
        // stale `file_size` would make `end = file_size - 1` index past
        // `file_content`, panicking the connection task on the range slice.
        let file_size = file_content.len() as u64;
        let etag = generate_etag(&file_content);

        if let Some(client_etag) = if_none_match {
            if etag_matches(client_etag, &etag) {
                return self.apply_custom_headers(
                    Response::empty(StatusCode::NOT_MODIFIED)
                        .header("etag", &etag)
                        .header("cache-control", format!("public, max-age={}", self.max_age))
                        .header("accept-ranges", "bytes"),
                );
            }
        }

        // Parse Range header (after preconditions per RFC 9110 §13.2.2).
        let ranges = match parse_ranges(range_header, file_size) {
            Ok(ranges) if !ranges.is_empty() => ranges,
            Ok(_) | Err(RangeError::InvalidSyntax) => {
                // Invalid or empty ranges - return 416 Range Not Satisfiable
                return self.apply_custom_headers(
                    Response::empty(StatusCode::RANGE_NOT_SATISFIABLE)
                        .header("content-range", format!("bytes */{}", file_size))
                        .header("accept-ranges", "bytes"),
                );
            }
            Err(RangeError::NotSatisfiable) => {
                return self.apply_custom_headers(
                    Response::empty(StatusCode::RANGE_NOT_SATISFIABLE)
                        .header("content-range", format!("bytes */{}", file_size))
                        .header("accept-ranges", "bytes"),
                );
            }
        };

        if let [range] = ranges.as_slice() {
            // Single range - return 206 Partial Content
            let range_data = &file_content[range.start..=range.end];
            let content_type = guess_mime(&path);

            let response = Response::new(
                StatusCode::PARTIAL_CONTENT,
                Bytes::from(range_data.to_vec()),
            )
            .header("content-type", content_type)
            .header("content-length", range_data.len().to_string())
            .header(
                "content-range",
                format!("bytes {}-{}/{}", range.start, range.end, file_size),
            )
            .header("accept-ranges", "bytes")
            .header("etag", &etag)
            .header("cache-control", format!("public, max-age={}", self.max_age));

            self.apply_custom_headers(response)
        } else {
            // Multiple ranges - return multipart/byteranges
            let boundary = "asupersync_range_boundary";
            let content_type = guess_mime(&path);
            let mut multipart_body = Vec::new();

            for range in &ranges {
                multipart_body.extend_from_slice(b"--");
                multipart_body.extend_from_slice(boundary.as_bytes());
                multipart_body.extend_from_slice(b"\r\n");
                multipart_body.extend_from_slice(b"Content-Type: ");
                multipart_body.extend_from_slice(content_type.as_bytes());
                multipart_body.extend_from_slice(b"\r\n");
                multipart_body.extend_from_slice(b"Content-Range: bytes ");
                multipart_body.extend_from_slice(
                    format!("{}-{}/{}", range.start, range.end, file_size).as_bytes(),
                );
                multipart_body.extend_from_slice(b"\r\n\r\n");
                multipart_body.extend_from_slice(&file_content[range.start..=range.end]);
                multipart_body.extend_from_slice(b"\r\n");
            }

            multipart_body.extend_from_slice(b"--");
            multipart_body.extend_from_slice(boundary.as_bytes());
            multipart_body.extend_from_slice(b"--\r\n");

            let body_len = multipart_body.len();
            let response = Response::new(StatusCode::PARTIAL_CONTENT, Bytes::from(multipart_body))
                .header(
                    "content-type",
                    format!("multipart/byteranges; boundary={}", boundary),
                )
                .header("content-length", body_len.to_string())
                .header("accept-ranges", "bytes")
                .header("etag", &etag)
                .header("cache-control", format!("public, max-age={}", self.max_age));

            self.apply_custom_headers(response)
        }
    }

    /// Create a handler that serves static files.
    ///
    /// The handler reads the request path and serves the corresponding file.
    /// It handles `If-None-Match` for conditional requests.
    #[must_use]
    pub fn handler(&self) -> StaticFilesHandler {
        StaticFilesHandler {
            config: self.clone(),
        }
    }
}

#[cfg(unix)]
fn open_static_file(path: &Path) -> std::io::Result<std::fs::File> {
    use std::os::unix::fs::OpenOptionsExt as _;

    std::fs::OpenOptions::new()
        .read(true)
        .custom_flags(libc::O_NOFOLLOW)
        .open(path)
}

#[cfg(not(unix))]
fn open_static_file(path: &Path) -> std::io::Result<std::fs::File> {
    std::fs::OpenOptions::new().read(true).open(path)
}

/// Handler that serves static files from a configured directory.
///
/// Created by [`StaticFiles::handler()`].
#[derive(Clone)]
pub struct StaticFilesHandler {
    config: StaticFiles,
}

impl Handler for StaticFilesHandler {
    fn call(
        &self,
        _cx: &crate::Cx,
        req: super::extract::Request,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Response> + Send + '_>> {
        Box::pin(async move {
            let head_only = req.method.eq_ignore_ascii_case("HEAD");
            let if_none_match = req.header("if-none-match").map(str::to_owned);
            let range_header = req.header("range");
            let request_path = &req.path;

            let mut response = match self.config.resolve_path(request_path) {
                Some(file_path) => {
                    if let Some(range_str) = range_header {
                        self.config
                            .serve_range(&file_path, range_str, if_none_match.as_deref())
                    } else {
                        let mut resp = self.config.serve_file(&file_path, if_none_match.as_deref());
                        // Add Accept-Ranges header to advertise range support
                        resp.set_header("accept-ranges", "bytes");
                        resp
                    }
                }
                None => Response::empty(StatusCode::NOT_FOUND),
            };

            if head_only {
                if !response.body.is_empty() && !response.has_header("content-length") {
                    response.set_header("content-length", response.body.len().to_string());
                }
                response.body = Bytes::new();
            }
            response
        })
    }
}

// ─── ETag ───────────────────────────────────────────────────────────────────

/// Generate a strong ETag from the exact response body bytes.
fn generate_etag(body: &[u8]) -> String {
    let digest = Sha256::digest(body);
    let mut etag = String::with_capacity(2 + digest.len() * 2);
    etag.push('"');
    for &byte in &digest {
        let _ = write!(etag, "{byte:02x}");
    }
    etag.push('"');
    etag
}

/// Check if a client ETag matches the server ETag.
///
/// Handles `*` and comma-separated lists of ETags.
fn etag_matches(client: &str, server: &str) -> bool {
    let client = client.trim();
    if client == "*" {
        return true;
    }
    // Support comma-separated list.
    for candidate in client.split(',') {
        let candidate = candidate.trim();
        // Strip weak prefix if present.
        let candidate = candidate.strip_prefix("W/").unwrap_or(candidate);
        if candidate == server {
            return true;
        }
    }
    false
}

// ─── Test Helper Functions ─────────────────────────────────────────────────

/// Test access function to expose generate_etag for audit tests.
#[cfg(test)]
pub fn generate_etag_test_access(body: &[u8]) -> String {
    generate_etag(body)
}

/// Test access function to expose etag_matches for audit tests.
#[cfg(test)]
pub fn etag_matches_test_access(client: &str, server: &str) -> bool {
    etag_matches(client, server)
}

// ─── MIME Detection ─────────────────────────────────────────────────────────

/// Guess the MIME type from a file extension.
fn guess_mime(path: &Path) -> &'static str {
    match path
        .extension()
        .and_then(|e| e.to_str())
        .map(str::to_ascii_lowercase)
        .as_deref()
    {
        // Text
        Some("html" | "htm") => "text/html; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("js" | "mjs") => "application/javascript; charset=utf-8",
        Some("json") => "application/json; charset=utf-8",
        Some("xml") => "application/xml; charset=utf-8",
        Some("txt") => "text/plain; charset=utf-8",
        Some("csv") => "text/csv; charset=utf-8",
        Some("md") => "text/markdown; charset=utf-8",
        Some("yaml" | "yml") => "application/yaml",
        Some("toml") => "application/toml",

        // Images
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("svg") => "image/svg+xml",
        Some("ico") => "image/x-icon",
        Some("webp") => "image/webp",
        Some("avif") => "image/avif",

        // Fonts
        Some("woff") => "font/woff",
        Some("woff2") => "font/woff2",
        Some("ttf") => "font/ttf",
        Some("otf") => "font/otf",
        Some("eot") => "application/vnd.ms-fontobject",

        // Archives / binary
        Some("pdf") => "application/pdf",
        Some("zip") => "application/zip",
        Some("gz" | "gzip") => "application/gzip",
        Some("tar") => "application/x-tar",
        Some("wasm") => "application/wasm",

        // Media
        Some("mp3") => "audio/mpeg",
        Some("mp4") => "video/mp4",
        Some("webm") => "video/webm",
        Some("ogg") => "audio/ogg",

        // Default
        _ => "application/octet-stream",
    }
}

// ─── Path Security ──────────────────────────────────────────────────────────

/// Check all lexical path policies before constructing a platform-native path.
fn has_denied_static_path(path: &str) -> bool {
    path.contains('\\') || has_traversal(path) || path.split('/').any(is_denied_hidden_component)
}

/// Check for path traversal sequences.
fn has_traversal(path: &str) -> bool {
    // Block ".." components.
    for component in path.split('/') {
        if is_parent_dir_segment(component) {
            return true;
        }
    }
    // Also check backslash separators (Windows paths in URLs).
    for component in path.split('\\') {
        if is_parent_dir_segment(component) {
            return true;
        }
    }
    // Block null bytes.
    if path.contains('\0') {
        return true;
    }
    false
}

fn has_denied_static_path_after_additional_decoding(path: &str) -> bool {
    let mut current = path.to_string();
    for _ in 0..4 {
        let decoded = percent_decode(&current);
        if decoded == current {
            return false;
        }
        if has_denied_static_path(&decoded) {
            return true;
        }
        current = decoded;
    }
    false
}

fn is_parent_dir_segment(component: &str) -> bool {
    let mut chars = component.chars();
    let Some(first) = chars.next() else {
        return false;
    };
    let Some(second) = chars.next() else {
        return false;
    };

    is_path_dot(first) && is_path_dot(second) && chars.next().is_none()
}

fn is_path_dot(ch: char) -> bool {
    matches!(ch, '.' | '\u{2024}' | '\u{FE52}' | '\u{FF0E}')
}

fn path_contains_symlink(root: &Path, relative: &Path) -> bool {
    let mut current = root.to_path_buf();

    for component in relative.components() {
        match component {
            std::path::Component::Normal(segment) => current.push(segment),
            std::path::Component::CurDir => continue,
            _ => return true,
        }

        match std::fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_symlink() => return true,
            Ok(_) | Err(_) => {}
        }
    }

    false
}

/// Simple percent-decoding for URL paths.
///
/// Decodes `%XX` hex pairs into raw bytes, then converts the result to a
/// UTF-8 string (lossy replacement for invalid sequences).
fn percent_decode(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            if let (Some(hi), Some(lo)) = (hex_val(bytes[i + 1]), hex_val(bytes[i + 2])) {
                out.push((hi << 4) | lo);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8(out).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into_owned())
}

fn hex_val(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

// ─── Tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    #![allow(
        clippy::pedantic,
        clippy::nursery,
        clippy::expect_fun_call,
        clippy::map_unwrap_or,
        clippy::cast_possible_wrap,
        clippy::future_not_send
    )]
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    trait SyncHandlerExt {
        fn call_sync(&self, req: super::super::extract::Request) -> Response;
    }

    impl<H: super::super::handler::Handler> SyncHandlerExt for H {
        fn call_sync(&self, req: super::super::extract::Request) -> Response {
            futures_lite::future::block_on(super::super::handler::Handler::call(
                self,
                &crate::Cx::for_testing(),
                req,
            ))
        }
    }

    fn setup_dir() -> TempDir {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("hello.txt"), "Hello, world!").unwrap();
        fs::write(dir.path().join("style.css"), "body { color: red; }").unwrap();
        fs::write(dir.path().join("app.js"), "console.log('hi');").unwrap();
        fs::write(dir.path().join("data.json"), r#"{"key":"val"}"#).unwrap();
        fs::write(dir.path().join("image.png"), [0x89, 0x50, 0x4E, 0x47]).unwrap();
        fs::create_dir(dir.path().join("sub")).unwrap();
        fs::write(dir.path().join("sub/page.html"), "<h1>Sub</h1>").unwrap();
        fs::write(dir.path().join("sub/index.html"), "<h1>Index</h1>").unwrap();
        dir
    }

    // ================================================================
    // Range parsing — amplification defense (CVE-2011-3192 class)
    // ================================================================

    #[test]
    fn parse_ranges_rejects_excessive_specs() {
        // ~thousands of `0-` specs would buffer num_specs × file_size bytes.
        let header = format!("bytes={}", "0-,".repeat(5000));
        let result = parse_ranges(&header, 1_000_000);
        assert!(
            matches!(result, Err(RangeError::NotSatisfiable)),
            "excessive range specs must be rejected, got {result:?}"
        );
    }

    #[test]
    fn parse_ranges_coalesces_overlapping_specs() {
        // Many whole-file prefix ranges must collapse to a single range so the
        // emitted body is bounded by file_size, not num_specs × file_size.
        let header = format!("bytes={}", "0-,".repeat(50));
        let ranges = parse_ranges(&header, 1000).expect("under the spec cap");
        assert_eq!(ranges.len(), 1, "overlapping ranges coalesce to one");
        assert_eq!(ranges[0].start, 0);
        assert_eq!(ranges[0].end, 999);
    }

    #[test]
    fn parse_ranges_merges_adjacent_but_keeps_disjoint() {
        // 0-9 and 10-19 are adjacent → merge; 100-109 is disjoint → separate.
        let ranges = parse_ranges("bytes=0-9,10-19,100-109", 1000).expect("valid ranges");
        assert_eq!(ranges.len(), 2, "adjacent merge, disjoint preserved");
        assert_eq!((ranges[0].start, ranges[0].end), (0, 19));
        assert_eq!((ranges[1].start, ranges[1].end), (100, 109));
    }

    #[test]
    fn parse_ranges_single_range_unchanged() {
        let ranges = parse_ranges("bytes=0-499", 1000).expect("valid range");
        assert_eq!(ranges.len(), 1);
        assert_eq!((ranges[0].start, ranges[0].end), (0, 499));
    }

    #[test]
    fn parse_ranges_tolerates_empty_specs() {
        // Trailing / doubled commas produce empty elements which RFC 7230 §7
        // says to ignore, not reject.
        let ranges = parse_ranges("bytes=0-99,,100-199,", 1000).expect("empty specs ignored");
        assert_eq!(ranges.len(), 1, "adjacent ranges coalesce; empties ignored");
        assert_eq!((ranges[0].start, ranges[0].end), (0, 199));
    }

    // ================================================================
    // Hidden-file (dotfile) serving defense
    // ================================================================

    #[test]
    fn is_denied_hidden_component_logic() {
        assert!(is_denied_hidden_component(".env"));
        assert!(is_denied_hidden_component(".git"));
        assert!(is_denied_hidden_component(".htpasswd"));
        assert!(!is_denied_hidden_component(".well-known"));
        assert!(!is_denied_hidden_component("index.html"));
        assert!(!is_denied_hidden_component("assets"));
        assert!(!is_denied_hidden_component("")); // empty component (from //)
    }

    #[test]
    fn denied_static_path_rejects_backslashes_and_preserves_well_known() {
        assert!(has_denied_static_path(r"public\.env"));
        assert!(has_denied_static_path(r"public\app.js"));
        assert!(has_denied_static_path(r".well-known\acme"));
        assert!(has_denied_static_path("public/.env"));
        assert!(!has_denied_static_path(".well-known/acme-challenge/token"));
        assert!(!has_denied_static_path("public/app.js"));
    }

    #[test]
    fn denied_static_path_rejects_deferred_encoded_components() {
        assert!(has_denied_static_path_after_additional_decoding(
            "public%5c.env"
        ));
        assert!(has_denied_static_path_after_additional_decoding(
            "public%255c%252eenv"
        ));
        assert!(has_denied_static_path_after_additional_decoding(
            "public/%2eenv"
        ));
        assert!(!has_denied_static_path_after_additional_decoding(
            ".well-known%2facme-challenge%2ftoken"
        ));
    }

    #[test]
    fn resolve_path_denies_dotfiles_but_allows_well_known() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join(".env"), "SECRET=1").unwrap();
        fs::create_dir(dir.path().join(".well-known")).unwrap();
        fs::write(dir.path().join(".well-known/acme.txt"), "challenge").unwrap();
        fs::create_dir(dir.path().join(".git")).unwrap();
        fs::write(dir.path().join(".git/config"), "[core]").unwrap();
        fs::write(dir.path().join("index.html"), "<h1>hi</h1>").unwrap();
        let sf = StaticFiles::new(dir.path());

        assert!(sf.resolve_path("/.env").is_none(), ".env must be denied");
        assert!(
            sf.resolve_path("/.git/config").is_none(),
            ".git/config must be denied"
        );
        assert!(
            sf.resolve_path("/.well-known/acme.txt").is_some(),
            ".well-known must be served"
        );
        assert!(
            sf.resolve_path(r"/.well-known\acme.txt").is_none(),
            "backslash spelling of .well-known must be denied"
        );
        assert!(
            sf.resolve_path("/.well-known%5cacme.txt").is_none(),
            "encoded-backslash spelling of .well-known must be denied"
        );
        assert!(
            sf.resolve_path("/index.html").is_some(),
            "normal files still served"
        );
    }

    #[test]
    fn resolve_path_rejects_backslash_and_deferred_encodings() {
        let dir = TempDir::new().unwrap();
        fs::create_dir(dir.path().join("public")).unwrap();
        fs::write(dir.path().join(r"public\.env"), "SECRET=1").unwrap();
        fs::write(dir.path().join("public%5c.env"), "SECRET=2").unwrap();
        let sf = StaticFiles::new(dir.path());

        assert!(sf.resolve_path(r"/public\.env").is_none());
        assert!(sf.resolve_path("/public%5c.env").is_none());
        assert!(sf.resolve_path("/public%255c.env").is_none());
    }

    // ================================================================
    // MIME detection
    // ================================================================

    #[test]
    fn mime_html() {
        assert_eq!(
            guess_mime(Path::new("index.html")),
            "text/html; charset=utf-8"
        );
    }

    #[test]
    fn mime_css() {
        assert_eq!(
            guess_mime(Path::new("style.css")),
            "text/css; charset=utf-8"
        );
    }

    #[test]
    fn mime_js() {
        assert_eq!(
            guess_mime(Path::new("app.js")),
            "application/javascript; charset=utf-8"
        );
    }

    #[test]
    fn mime_json() {
        assert_eq!(
            guess_mime(Path::new("data.json")),
            "application/json; charset=utf-8"
        );
    }

    #[test]
    fn mime_png() {
        assert_eq!(guess_mime(Path::new("image.png")), "image/png");
    }

    #[test]
    fn mime_unknown() {
        assert_eq!(
            guess_mime(Path::new("file.xyz")),
            "application/octet-stream"
        );
    }

    #[test]
    fn mime_case_insensitive() {
        assert_eq!(
            guess_mime(Path::new("FILE.HTML")),
            "text/html; charset=utf-8"
        );
    }

    #[test]
    fn mime_wasm() {
        assert_eq!(guess_mime(Path::new("module.wasm")), "application/wasm");
    }

    // ================================================================
    // Path security
    // ================================================================

    #[test]
    fn traversal_double_dot() {
        assert!(has_traversal("../etc/passwd"));
        assert!(has_traversal("foo/../bar"));
        assert!(has_traversal("foo/.."));
    }

    #[test]
    fn traversal_backslash() {
        assert!(has_traversal("..\\etc\\passwd"));
    }

    #[test]
    fn traversal_null_byte() {
        assert!(has_traversal("file\0.txt"));
    }

    #[test]
    fn traversal_unicode_dot_variants() {
        assert!(has_traversal("\u{2024}\u{2024}/etc/passwd"));
        assert!(has_traversal(".\u{2024}/etc/passwd"));
        assert!(has_traversal("foo/\u{FE52}\u{FE52}/bar"));
        assert!(has_traversal("foo/\u{FF0E}\u{FF0E}/bar"));
    }

    #[test]
    fn traversal_deferred_percent_decoding() {
        assert!(has_denied_static_path_after_additional_decoding(
            "%2e%2e/etc/passwd"
        ));
        assert!(has_denied_static_path_after_additional_decoding(
            "safe/%2e%2e/secret.txt"
        ));
        assert!(has_denied_static_path_after_additional_decoding(
            "safe%2f..%2fsecret.txt"
        ));
        assert!(has_denied_static_path_after_additional_decoding(
            "safe%5c..%5csecret.txt"
        ));
        assert!(has_denied_static_path_after_additional_decoding(
            "%252e%252e/etc/passwd"
        ));
        assert!(!has_denied_static_path_after_additional_decoding(
            "version%2e1/file.txt"
        ));
    }

    #[test]
    fn no_traversal() {
        assert!(!has_traversal("hello.txt"));
        assert!(!has_traversal("sub/page.html"));
        assert!(!has_traversal("deeply/nested/file.js"));
    }

    // ================================================================
    // Percent decoding
    // ================================================================

    #[test]
    fn percent_decode_basic() {
        assert_eq!(percent_decode("hello%20world"), "hello world");
    }

    #[test]
    fn percent_decode_no_encoding() {
        assert_eq!(percent_decode("hello.txt"), "hello.txt");
    }

    #[test]
    fn percent_decode_path_separator() {
        assert_eq!(percent_decode("foo%2Fbar"), "foo/bar");
    }

    #[test]
    fn percent_decode_utf8_path_dot() {
        assert_eq!(percent_decode("%E2%80%A4%E2%80%A4"), "\u{2024}\u{2024}");
        assert!(has_traversal(&percent_decode(
            "%E2%80%A4%E2%80%A4/etc/passwd"
        )));
    }

    #[test]
    fn percent_decode_incomplete() {
        assert_eq!(percent_decode("hello%2"), "hello%2");
    }

    #[test]
    fn percent_decode_invalid_sequence_preserves_bytes() {
        assert_eq!(percent_decode("hello%GGworld"), "hello%GGworld");
        assert_eq!(percent_decode("sub%2/page.html"), "sub%2/page.html");
        assert_eq!(percent_decode("%"), "%");
    }

    // ================================================================
    // ETag
    // ================================================================

    #[test]
    fn etag_matches_exact() {
        assert!(etag_matches("\"abc\"", "\"abc\""));
    }

    #[test]
    fn etag_matches_star() {
        assert!(etag_matches("*", "\"abc\""));
    }

    #[test]
    fn etag_matches_list() {
        assert!(etag_matches("\"x\", \"y\", \"z\"", "\"y\""));
    }

    #[test]
    fn etag_matches_weak() {
        assert!(etag_matches("W/\"abc\"", "\"abc\""));
    }

    #[test]
    fn etag_no_match() {
        assert!(!etag_matches("\"abc\"", "\"def\""));
    }

    #[test]
    fn strong_etag_changes_for_same_length_content() {
        let first = generate_etag(b"abc");
        let second = generate_etag(b"abd");

        assert_ne!(
            first, second,
            "strong ETags must change when same-length content changes"
        );
    }

    // ================================================================
    // Path resolution
    // ================================================================

    #[test]
    fn resolve_simple_file() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/hello.txt");
        assert!(path.is_some());
    }

    #[test]
    fn resolve_nested_file() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/sub/page.html");
        assert!(path.is_some());
    }

    #[test]
    fn resolve_directory_index() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/sub/");
        assert!(path.is_some());
        assert!(path.unwrap().ends_with("index.html"));
    }

    #[test]
    fn resolve_nonexistent() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        assert!(sf.resolve_path("/missing.txt").is_none());
    }

    #[test]
    fn resolve_traversal_blocked() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        assert!(sf.resolve_path("/../../../etc/passwd").is_none());
    }

    #[test]
    fn resolve_percent_encoded() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        assert!(sf.resolve_path("/hello%2Etxt").is_some());
    }

    #[test]
    fn resolve_double_encoded_traversal_blocked() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        assert!(sf.resolve_path("/%252e%252e/etc/passwd").is_none());
        assert!(sf.resolve_path("/sub%252f..%252fhello.txt").is_none());
        assert!(sf.resolve_path("/sub%255c..%255chello.txt").is_none());
    }

    #[test]
    fn resolve_unicode_dot_traversal_blocked_after_percent_decode() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());

        assert!(sf.resolve_path("/%E2%80%A4%E2%80%A4/etc/passwd").is_none());
        assert!(
            sf.resolve_path("/sub/%EF%B9%92%EF%B9%92/hello.txt")
                .is_none()
        );
        assert!(
            sf.resolve_path("/sub/%EF%BC%8E%EF%BC%8E/hello.txt")
                .is_none()
        );
    }

    #[test]
    fn resolve_invalid_percent_encoding_does_not_alias_other_path() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        assert!(
            sf.resolve_path("/sub%2/page.html").is_none(),
            "malformed escapes must be preserved instead of silently dropping bytes"
        );
    }

    #[cfg(unix)]
    #[test]
    fn resolve_symlinked_file_blocked() {
        let dir = setup_dir();
        std::os::unix::fs::symlink("hello.txt", dir.path().join("hello-link.txt")).unwrap();

        let sf = StaticFiles::new(dir.path());
        assert!(
            sf.resolve_path("/hello-link.txt").is_none(),
            "symlinked files must not be served by default"
        );
    }

    #[cfg(unix)]
    #[test]
    fn resolve_symlinked_directory_blocked() {
        let dir = setup_dir();
        std::os::unix::fs::symlink("sub", dir.path().join("sub-link")).unwrap();

        let sf = StaticFiles::new(dir.path());
        assert!(
            sf.resolve_path("/sub-link/page.html").is_none(),
            "symlinked directories must not be traversed"
        );
        assert!(
            sf.resolve_path("/sub-link/").is_none(),
            "directory indexes behind symlinks must not be served"
        );
    }

    #[cfg(unix)]
    #[test]
    fn serve_file_rejects_post_resolution_symlink_swap() {
        let dir = setup_dir();
        let outside = TempDir::new().unwrap();
        let outside_path = outside.path().join("secret.txt");
        fs::write(&outside_path, "top secret").unwrap();

        let sf = StaticFiles::new(dir.path());
        let resolved = sf.resolve_path("/hello.txt").unwrap();
        let backup = dir.path().join("hello.backup.txt");
        fs::rename(&resolved, &backup).unwrap();
        std::os::unix::fs::symlink(&outside_path, &resolved).unwrap();

        let resp = sf.serve_file(&resolved, None);
        assert_eq!(resp.status, StatusCode::NOT_FOUND);
        assert_ne!(resp.body.as_ref(), b"top secret");
    }

    // ================================================================
    // File serving
    // ================================================================

    #[test]
    fn serve_txt_file() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/hello.txt").unwrap();
        let resp = sf.serve_file(&path, None);
        assert_eq!(resp.status, StatusCode::OK);
        assert_eq!(
            resp.headers.get("content-type").unwrap(),
            "text/plain; charset=utf-8"
        );
        assert_eq!(std::str::from_utf8(&resp.body).unwrap(), "Hello, world!");
        assert!(resp.headers.contains_key("etag"));
        assert!(resp.headers.contains_key("cache-control"));
        assert_eq!(
            resp.headers.get("x-content-type-options").unwrap(),
            "nosniff"
        );
    }

    #[test]
    fn serve_css_file() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/style.css").unwrap();
        let resp = sf.serve_file(&path, None);
        assert_eq!(resp.status, StatusCode::OK);
        assert_eq!(
            resp.headers.get("content-type").unwrap(),
            "text/css; charset=utf-8"
        );
    }

    #[test]
    fn serve_304_not_modified() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/hello.txt").unwrap();

        // First request to get the ETag.
        let resp1 = sf.serve_file(&path, None);
        let etag = resp1.headers.get("etag").unwrap().clone();

        // Second request with If-None-Match.
        let resp2 = sf.serve_file(&path, Some(&etag));
        assert_eq!(resp2.status, StatusCode::NOT_MODIFIED);
        assert!(resp2.body.is_empty());
        assert_eq!(
            resp2.headers.get("x-content-type-options").unwrap(),
            "nosniff"
        );
    }

    #[test]
    fn serve_304_not_modified_for_if_none_match_wildcard() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/hello.txt").unwrap();

        let resp = sf.serve_file(&path, Some("*"));
        assert_eq!(resp.status, StatusCode::NOT_MODIFIED);
        assert!(resp.body.is_empty());
        assert!(resp.headers.contains_key("etag"));
        assert_eq!(
            resp.headers.get("x-content-type-options").unwrap(),
            "nosniff"
        );
    }

    /// br-asupersync-42wywh — RFC 9110 §13.2.2 requires preconditions
    /// (If-None-Match in particular) to be evaluated BEFORE Range
    /// processing. Pre-fix: an unsatisfiable / malformed Range header
    /// short-circuited to 416 even when If-None-Match matched the
    /// current ETag, forcing clients into a needless full refetch on
    /// the next request. Post-fix: If-None-Match wins → 304 Not Modified.
    #[test]
    fn serve_range_with_matching_if_none_match_prefers_304_over_416() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/hello.txt").unwrap();

        // Capture the current ETag from a plain GET so we can replay
        // the matching If-None-Match below.
        let etag = sf
            .serve_file(&path, None)
            .headers
            .get("etag")
            .expect("etag must be present")
            .clone();

        // Range that is provably unsatisfiable: file is 13 bytes, the
        // requested range starts well past EOF. parse_ranges returns
        // NotSatisfiable, which the pre-fix path short-circuited to
        // 416 before checking If-None-Match.
        let resp = sf.serve_range(&path, "bytes=99999-100000", Some(&etag));

        assert_eq!(
            resp.status,
            StatusCode::NOT_MODIFIED,
            "If-None-Match must be evaluated before Range (RFC 9110 §13.2.2); \
             matching ETag must yield 304, not 416. Got status={:?}",
            resp.status,
        );
        assert!(resp.body.is_empty(), "304 responses MUST NOT carry a body",);
        assert_eq!(
            resp.headers.get("etag").map(String::as_str),
            Some(etag.as_str()),
            "304 must echo the ETag",
        );
        assert!(
            !resp.headers.contains_key("content-range"),
            "304 must not carry Content-Range; got {:?}",
            resp.headers.get("content-range"),
        );
    }

    /// br-asupersync-42wywh — same precondition-ordering requirement
    /// for the syntactically-malformed Range case (`bytes=abc-def`).
    /// The matching If-None-Match takes precedence; 304, not 416.
    #[test]
    fn serve_range_invalid_syntax_with_matching_if_none_match_returns_304() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/hello.txt").unwrap();

        let etag = sf
            .serve_file(&path, None)
            .headers
            .get("etag")
            .expect("etag must be present")
            .clone();

        let resp = sf.serve_range(&path, "bytes=abc-def", Some(&etag));

        assert_eq!(
            resp.status,
            StatusCode::NOT_MODIFIED,
            "If-None-Match must trump even a malformed Range header per \
             RFC 9110 §13.2.2; got status={:?}",
            resp.status,
        );
    }

    /// br-asupersync-42wywh — counter test: a non-matching If-None-Match
    /// with an unsatisfiable Range still yields 416. The fix must NOT
    /// regress the existing behavior when the precondition is false.
    #[test]
    fn serve_range_unsatisfiable_with_non_matching_if_none_match_still_416() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let path = sf.resolve_path("/hello.txt").unwrap();

        let resp = sf.serve_range(&path, "bytes=99999-100000", Some("\"not-the-etag\""));

        assert_eq!(
            resp.status,
            StatusCode::RANGE_NOT_SATISFIABLE,
            "Non-matching If-None-Match must NOT prevent the 416 path",
        );
    }

    #[test]
    fn serve_custom_max_age() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path()).max_age(86400);
        let path = sf.resolve_path("/hello.txt").unwrap();
        let resp = sf.serve_file(&path, None);
        assert_eq!(
            resp.headers.get("cache-control").unwrap(),
            "public, max-age=86400"
        );
    }

    #[test]
    fn serve_custom_headers() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path()).header("x-custom", "value");
        let path = sf.resolve_path("/hello.txt").unwrap();
        let resp = sf.serve_file(&path, None);
        assert_eq!(resp.headers.get("x-custom").unwrap(), "value");
    }

    #[test]
    fn serve_custom_headers_can_override_nosniff() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path()).header("X-Content-Type-Options", "custom-policy");
        let path = sf.resolve_path("/hello.txt").unwrap();
        let resp = sf.serve_file(&path, None);
        assert_eq!(
            resp.headers.get("x-content-type-options").unwrap(),
            "custom-policy"
        );
    }

    // ================================================================
    // Handler integration
    // ================================================================

    #[test]
    fn handler_serves_file() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let handler = sf.handler();

        let req = super::super::extract::Request::new("GET", "/hello.txt");
        let resp = handler.call_sync(req);
        assert_eq!(resp.status, StatusCode::OK);
        assert_eq!(std::str::from_utf8(&resp.body).unwrap(), "Hello, world!");
    }

    #[test]
    fn handler_head_omits_body_but_preserves_conditional_headers() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let handler = sf.handler();

        let get_resp = handler.call_sync(super::super::extract::Request::new("GET", "/hello.txt"));
        let head_resp =
            handler.call_sync(super::super::extract::Request::new("HEAD", "/hello.txt"));

        assert_eq!(head_resp.status, StatusCode::OK);
        assert!(head_resp.body.is_empty());
        assert_eq!(
            head_resp.headers.get("content-type"),
            get_resp.headers.get("content-type")
        );
        assert_eq!(
            head_resp.headers.get("content-length"),
            Some(&get_resp.body.len().to_string())
        );
        assert_eq!(head_resp.headers.get("etag"), get_resp.headers.get("etag"));
        assert_eq!(
            head_resp.headers.get("cache-control"),
            get_resp.headers.get("cache-control")
        );
        assert_eq!(
            head_resp.headers.get("x-content-type-options"),
            get_resp.headers.get("x-content-type-options")
        );
    }

    #[test]
    fn handler_returns_404() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let handler = sf.handler();

        let req = super::super::extract::Request::new("GET", "/missing.txt");
        let resp = handler.call_sync(req);
        assert_eq!(resp.status, StatusCode::NOT_FOUND);
    }

    #[test]
    fn handler_304_with_etag() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let handler = sf.handler();

        // First request.
        let req1 = super::super::extract::Request::new("GET", "/hello.txt");
        let resp1 = handler.call_sync(req1);
        let etag = resp1.headers.get("etag").unwrap().clone();

        // Second request with If-None-Match.
        let req2 = super::super::extract::Request::new("GET", "/hello.txt")
            .with_header("If-None-Match", etag);
        let resp2 = handler.call_sync(req2);
        assert_eq!(resp2.status, StatusCode::NOT_MODIFIED);
    }

    #[test]
    fn handler_head_304_with_etag_stays_empty() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path());
        let handler = sf.handler();

        let get_resp = handler.call_sync(super::super::extract::Request::new("GET", "/hello.txt"));
        let etag = get_resp.headers.get("etag").unwrap().clone();

        let head_req = super::super::extract::Request::new("HEAD", "/hello.txt")
            .with_header("If-None-Match", etag);
        let head_resp = handler.call_sync(head_req);

        assert_eq!(head_resp.status, StatusCode::NOT_MODIFIED);
        assert!(head_resp.body.is_empty());
        assert!(head_resp.headers.contains_key("etag"));
        assert!(head_resp.headers.contains_key("cache-control"));
        assert_eq!(
            head_resp.headers.get("x-content-type-options").unwrap(),
            "nosniff"
        );
    }

    // ================================================================
    // Builder API
    // ================================================================

    #[test]
    fn builder_no_index() {
        let dir = setup_dir();
        let sf = StaticFiles::new(dir.path()).index_file(None::<String>);
        assert!(sf.resolve_path("/sub/").is_none());
    }

    #[test]
    fn builder_debug() {
        let sf = StaticFiles::new("/tmp/static");
        let dbg = format!("{sf:?}");
        assert!(dbg.contains("StaticFiles"));
        assert!(dbg.contains("/tmp/static"));
    }

    #[test]
    fn builder_clone() {
        let sf = StaticFiles::new("/tmp/static").max_age(300);
        let sf2 = sf.clone();
        assert_eq!(sf2.max_age, sf.max_age);
    }
}