mbr-markdown-browser 0.5.1-rc2

A fast, featureful markdown viewer, browser, and (optional) static site generator
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
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
//! Path resolution logic for the mbr server.
//!
//! This module contains pure functions for determining what resource to serve
//! based on a URL path. By keeping this logic separate from I/O, it becomes
//! easily testable.

use std::path::{Path, PathBuf};

/// Safely joins a base directory with a request path, preventing path traversal.
///
/// Returns `None` if the resulting path would escape the base directory.
/// The path is canonicalized to resolve symlinks and `..` components.
///
/// # Security
///
/// This function guards against path traversal attacks by:
/// 1. Canonicalizing both the base directory and the joined path
/// 2. Verifying the resolved path starts with the base directory
fn safe_join(
    base_dir: &Path,
    canonical_base_dir: Option<&Path>,
    request_path: &str,
) -> Option<PathBuf> {
    // Use pre-computed canonical base if available, otherwise canonicalize per-call
    let owned_canonical;
    let canonical_base = match canonical_base_dir {
        Some(cached) => cached,
        None => {
            owned_canonical = base_dir.canonicalize().ok()?;
            &owned_canonical
        }
    };

    // Build candidate from canonical_base (not base_dir) to ensure all path
    // construction happens in canonical space. This prevents subtle issues
    // if base_dir itself contains symlinks.
    let candidate = canonical_base.join(request_path);

    // Canonicalizing resolves ".." and symlinks, so its *result* is the only
    // trustworthy answer for a path that exists.
    match candidate.canonicalize() {
        // The path exists. It is safe only if it resolves inside the base.
        // Returning `None` here is load-bearing: falling through to the
        // "doesn't exist yet" branch below would validate only the parent and
        // then hand back the *unresolved* path, so a final component that is a
        // symlink out of the repo (`passwd -> /etc/passwd`) would be served.
        Ok(canonical) => canonical.starts_with(canonical_base).then_some(canonical),

        // The path does not exist yet (e.g. probing markdown extensions for
        // `/foo/` -> `foo.md`). Verify the parent is inside the base and
        // rebuild the full path from the canonical parent.
        Err(_) => {
            let canonical_parent = candidate.parent()?.canonicalize().ok()?;
            if !canonical_parent.starts_with(canonical_base) {
                return None;
            }
            Some(canonical_parent.join(candidate.file_name()?))
        }
    }
}

/// The result of resolving a URL path to a resource.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolvedPath {
    /// Serve a static file directly (non-markdown)
    StaticFile(PathBuf),
    /// Render a markdown file
    MarkdownFile(PathBuf),
    /// Generate a directory listing
    DirectoryListing(PathBuf),
    /// Render a tag page listing all pages with this tag
    TagPage {
        /// The tag source (e.g., "tags", "performers", "taxonomy.tags")
        source: String,
        /// The normalized tag value (e.g., "rust", "joshua_jay")
        value: String,
    },
    /// Render a tag source index listing all tags from this source
    TagSourceIndex {
        /// The tag source (e.g., "tags", "performers")
        source: String,
    },
    /// Resource not found
    NotFound,
    /// Redirect to canonical URL (e.g., /x/index/ → /x/)
    Redirect(String),
}

/// Configuration for path resolution.
#[derive(Debug, Clone)]
pub struct PathResolverConfig<'a> {
    pub base_dir: &'a Path,
    /// Pre-computed canonical base directory. Avoids calling `canonicalize()` on every request.
    /// If `None`, `safe_join` will canonicalize on each call (backward-compatible fallback).
    pub canonical_base_dir: Option<&'a Path>,
    pub static_folder: &'a str,
    pub markdown_extensions: &'a [String],
    pub index_file: &'a str,
    /// Valid tag source URL identifiers (e.g., ["tags", "performers", "taxonomy.tags"])
    /// Used to detect tag page URLs like /tags/rust/
    pub tag_sources: &'a [String],
}

/// Normalizes an authored link target (href) into the request-path form that
/// [`resolve_request_path`] expects.
///
/// Live requests reach the server through axum's `extract::Path`, which
/// percent-decodes the URL path before `resolve_request_path` ever sees it.
/// Any code that feeds *authored* hrefs (still percent-encoded, possibly
/// carrying fragments or query strings) into the resolver must apply this
/// identical normalization, or its results diverge from what the server
/// actually serves. That divergence previously caused bogus "broken internal
/// link" 404 reports in the GUI error panel for links like
/// `/IronCore%20Swag%20T-shirts%20Gifts/` pointing at
/// `IronCore Swag T-shirts Gifts.md`.
///
/// Mirrors exactly what a real HTTP request undergoes:
/// 1. Strip the fragment (`#...`), then the query string (`?...`).
/// 2. Percent-decode (lossy UTF-8, matching axum's decoding).
/// 3. Trim leading and trailing `/`.
///
/// Note: valid percent escapes are always decoded, so a literal `%` must be
/// authored as `%25` (e.g. `100%25` normalizes to `100%`).
pub fn normalize_link_target(href: &str) -> String {
    let base = href.split('#').next().unwrap_or(href);
    let base = base.split('?').next().unwrap_or(base);
    let decoded = percent_encoding::percent_decode_str(base).decode_utf8_lossy();
    decoded.trim_matches('/').to_string()
}

/// Resolves a URL path to determine what resource should be served.
///
/// This is a pure function that performs filesystem checks but no I/O operations
/// like reading file contents. It determines the type of resource to serve.
///
/// # Resolution Order
///
/// 1. Direct file match in base_dir → StaticFile
/// 2. Directory with configured index file (e.g., index.md) → MarkdownFile
/// 3. Path with trailing slash matching a markdown file (e.g., /foo/ → foo.md) → MarkdownFile
/// 4. File in static folder → StaticFile
/// 5. Directory with index.{markdown_ext} → MarkdownFile
/// 6. Directory without index → DirectoryListing
/// 7. Tag source index (e.g., /tags/) → TagSourceIndex (if source matches config)
/// 8. Tag page (e.g., /tags/rust/) → TagPage (if source matches config)
/// 9. Nothing matches → NotFound
///
/// Note: Filesystem paths (steps 1-6) always take precedence over tag URLs (steps 7-8).
/// If a file or directory named "tags" exists, it will be served instead of the tag index.
///
/// # Security
///
/// Path traversal attacks (e.g., `../../../etc/passwd`) are blocked by validating
/// that all resolved paths remain within the configured base directory.
pub fn resolve_request_path(config: &PathResolverConfig, request_path: &str) -> ResolvedPath {
    // Use safe_join to prevent path traversal attacks
    // If the path would escape base_dir, skip to tag resolution or NotFound
    if let Some(candidate_path) =
        safe_join(config.base_dir, config.canonical_base_dir, request_path)
    {
        // 1. Direct file match
        if candidate_path.is_file() {
            return if is_markdown_file(&candidate_path, config.markdown_extensions) {
                ResolvedPath::MarkdownFile(candidate_path)
            } else {
                ResolvedPath::StaticFile(candidate_path)
            };
        }

        // 2. Directory with configured index file
        if candidate_path.is_dir() {
            let index_path = candidate_path.join(config.index_file);
            if index_path.is_file() {
                return ResolvedPath::MarkdownFile(index_path);
            }
        }

        // 3. Try markdown extensions on base path (for /foo/ → foo.md)
        let candidate_base = strip_trailing_separator(&candidate_path);

        // 3a. Check for non-canonical index URL (e.g., /x/index/ should redirect to /x/)
        // This must come before step 3 to catch URLs like /docs/index/ before they resolve
        let index_stem = Path::new(config.index_file)
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("index");

        if let Some(file_name) = candidate_base.file_name().and_then(|f| f.to_str())
            && file_name == index_stem
        {
            // Check if parent directory contains the actual index file
            if let Some(parent) = candidate_base.parent() {
                let index_path = parent.join(config.index_file);
                if index_path.is_file() {
                    // Build canonical URL: /x/index/ → /x/
                    // Use pre-computed canonical base if available
                    let owned_base;
                    let canonical_base = match config.canonical_base_dir {
                        Some(cached) => Some(cached),
                        None => {
                            owned_base = config.base_dir.canonicalize().ok();
                            owned_base.as_deref()
                        }
                    };
                    let canonical = canonical_base
                        .and_then(|base| pathdiff::diff_paths(parent, base))
                        .map(|p| {
                            // `path_to_url`, not `to_string_lossy`: this value is
                            // a redirect target, so it must stay `/`-separated
                            // rather than becoming `/a\b\c/` on Windows.
                            let s = crate::url_path::path_to_url(&p);
                            if s.is_empty() {
                                "/".to_string()
                            } else {
                                format!("/{}/", s)
                            }
                        })
                        .unwrap_or_else(|| "/".to_string());
                    return ResolvedPath::Redirect(canonical);
                }
            }
        }

        if let Some(md_path) = find_markdown_file(&candidate_base, config.markdown_extensions) {
            return ResolvedPath::MarkdownFile(md_path);
        }

        // 4. Check static folder (has its own path traversal protection)
        if let Some(static_path) = find_in_static_folder(config, request_path) {
            return ResolvedPath::StaticFile(static_path);
        }

        // 5. Directory with index.{markdown_ext}
        if candidate_base.is_dir() {
            let index_base = candidate_base.join("index");
            if let Some(md_path) = find_markdown_file(&index_base, config.markdown_extensions) {
                return ResolvedPath::MarkdownFile(md_path);
            }

            // 6. Directory without index → listing
            return ResolvedPath::DirectoryListing(candidate_base);
        }
    }

    // 4b. Static folder check - ALSO check here for paths not in base_dir
    // This handles the case where the path doesn't exist in base_dir but exists in static folder
    // (e.g., /images/blog/photo.png where images/ only exists under static/)
    if let Some(static_path) = find_in_static_folder(config, request_path) {
        return ResolvedPath::StaticFile(static_path);
    }

    // 7-8. Check for tag URLs (only if nothing matched in filesystem)
    // This is also reached if safe_join returned None (path traversal blocked)
    if let Some(tag_result) = try_resolve_tag_url(request_path, config.tag_sources) {
        return tag_result;
    }

    // 9. Nothing found
    ResolvedPath::NotFound
}

/// Checks if a path is a markdown file based on configured extensions.
fn is_markdown_file(path: &Path, extensions: &[String]) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .map(|ext| extensions.iter().any(|md_ext| md_ext == ext))
        .unwrap_or(false)
}

/// Strips trailing path separator(s) from a path.
///
/// Both `/` and the platform separator are trimmed. The input here is derived
/// from a request URL, where the separator is *always* `/` regardless of
/// platform — trimming only `std::path::MAIN_SEPARATOR` silently did nothing on
/// Windows, leaving a trailing slash on the candidate path.
fn strip_trailing_separator(path: &Path) -> PathBuf {
    let s = path.to_string_lossy();
    let trimmed = s.trim_end_matches(['/', std::path::MAIN_SEPARATOR]);
    PathBuf::from(trimmed)
}

/// Finds a markdown file by trying each configured extension.
///
/// The URL for a markdown file strips only its final extension (see
/// `build_markdown_url_path`), so a file named `a.b.c.md` is served at `/a.b.c/`.
/// We therefore reverse that by *appending* the extension to the full stem;
/// `Path::set_extension` would instead replace the trailing dotted segment
/// (`a.b.c` -> `a.b.md`) and 404 on any file whose name contains a dot.
fn find_markdown_file(base_path: &Path, extensions: &[String]) -> Option<PathBuf> {
    let file_name = base_path.file_name()?.to_str()?;
    extensions
        .iter()
        .map(|ext| base_path.with_file_name(format!("{file_name}.{ext}")))
        .find(|path| path.is_file())
}

/// Finds a file in the static folder.
///
/// # Security
///
/// Containment is enforced against the **static root** — the canonicalized
/// static directory itself — not against the repository root. The overlay is
/// allowed to live outside the repository root (`static_folder = "../static"`
/// for the common `repo/content` + `repo/static` layout), so requiring every
/// served file to sit under the repository root would 404 the entire overlay.
///
/// *How far* the overlay may reach is decided once, at load time, by
/// `Config::validate_static_folder`: inside the root, or a peer of it, and never
/// via a parent that is `$HOME` or the filesystem root. What this function must
/// still guarantee — and does — is that a *request path* cannot walk out of
/// whatever directory that policy settled on, including through a symlink inside
/// the overlay pointing at, say, `/etc/passwd`: the candidate is canonicalized
/// before the `starts_with` check, so the symlink's target is what gets judged.
fn find_in_static_folder(config: &PathResolverConfig, request_path: &str) -> Option<PathBuf> {
    // Use the pre-computed canonical base if available, otherwise canonicalize.
    let owned_root;
    let canonical_root = match config.canonical_base_dir {
        Some(cached) => cached,
        None => {
            owned_root = config.base_dir.canonicalize().ok()?;
            &owned_root
        }
    };

    // `join` handles a rooted `static_folder` (absolute paths replace the base),
    // and `canonicalize` both resolves `..`/symlinks and verifies existence.
    let static_dir = canonical_root
        .join(config.static_folder)
        .canonicalize()
        .ok()?;

    let candidate = static_dir.join(request_path);

    // Canonicalize to resolve any ".." or symlinks, then verify containment
    let canonical = candidate.canonicalize().ok()?;
    if canonical.starts_with(&static_dir) && canonical.is_file() {
        Some(canonical)
    } else {
        None
    }
}

/// Attempts to resolve a URL path as a tag URL.
///
/// Matches patterns like:
/// - `{source}/` → TagSourceIndex (e.g., "tags/" → list all tags)
/// - `{source}/{value}/` → TagPage (e.g., "tags/rust/" → pages tagged "rust")
///
/// The source must match one of the configured tag sources (case-insensitive).
/// Returns `None` if the path doesn't match a tag URL pattern.
fn try_resolve_tag_url(request_path: &str, tag_sources: &[String]) -> Option<ResolvedPath> {
    // Skip if no tag sources configured
    if tag_sources.is_empty() {
        return None;
    }

    // Normalize path: strip leading and trailing slashes
    let path = request_path.trim_matches('/');

    // Empty path is not a tag URL
    if path.is_empty() {
        return None;
    }

    // Split path into segments
    let segments: Vec<&str> = path.split('/').collect();

    match segments.len() {
        // Single segment: might be a tag source index (e.g., "tags")
        1 => {
            let source = segments[0].to_lowercase();
            if tag_sources.iter().any(|s| s.to_lowercase() == source) {
                Some(ResolvedPath::TagSourceIndex { source })
            } else {
                None
            }
        }
        // Two segments: might be a tag page (e.g., "tags/rust")
        2 => {
            let source = segments[0].to_lowercase();
            let value = segments[1].to_lowercase();

            // Don't match empty values
            if value.is_empty() {
                return None;
            }

            if tag_sources.iter().any(|s| s.to_lowercase() == source) {
                Some(ResolvedPath::TagPage { source, value })
            } else {
                None
            }
        }
        // More than 2 segments: not a tag URL
        _ => None,
    }
}

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

    /// Test fixture that owns the extensions and tag_sources vectors
    struct TestFixture {
        dir: TempDir,
        canonical: PathBuf,
        extensions: Vec<String>,
        tag_sources: Vec<String>,
    }

    impl TestFixture {
        fn new() -> Self {
            let dir = TempDir::new().unwrap();
            fs::create_dir(dir.path().join("static")).unwrap();
            let canonical = dir.path().canonicalize().unwrap();
            Self {
                dir,
                canonical,
                extensions: vec![String::from("md")],
                tag_sources: vec![],
            }
        }

        fn with_extensions(extensions: Vec<String>) -> Self {
            let dir = TempDir::new().unwrap();
            fs::create_dir(dir.path().join("static")).unwrap();
            let canonical = dir.path().canonicalize().unwrap();
            Self {
                dir,
                canonical,
                extensions,
                tag_sources: vec![],
            }
        }

        fn with_tag_sources(tag_sources: Vec<String>) -> Self {
            let dir = TempDir::new().unwrap();
            fs::create_dir(dir.path().join("static")).unwrap();
            let canonical = dir.path().canonicalize().unwrap();
            Self {
                dir,
                canonical,
                extensions: vec![String::from("md")],
                tag_sources,
            }
        }

        fn config(&self) -> PathResolverConfig<'_> {
            PathResolverConfig {
                base_dir: self.dir.path(),
                canonical_base_dir: Some(&self.canonical),
                static_folder: "static",
                markdown_extensions: &self.extensions,
                index_file: "index.md",
                tag_sources: &self.tag_sources,
            }
        }

        fn path(&self) -> &Path {
            self.dir.path()
        }

        /// Returns the canonicalized base path (resolves symlinks like /var -> /private/var on macOS)
        fn canonical_path(&self) -> PathBuf {
            self.dir.path().canonicalize().unwrap()
        }
    }

    #[test]
    fn test_direct_markdown_file() {
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("readme.md"), "# Test").unwrap();

        let result = resolve_request_path(&fixture.config(), "readme.md");

        // safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(fixture.canonical_path().join("readme.md"))
        );
    }

    #[test]
    fn test_direct_static_file() {
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("image.png"), "fake image").unwrap();

        let result = resolve_request_path(&fixture.config(), "image.png");

        // safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::StaticFile(fixture.canonical_path().join("image.png"))
        );
    }

    #[test]
    fn test_directory_with_index() {
        let fixture = TestFixture::new();
        let subdir = fixture.path().join("docs");
        fs::create_dir(&subdir).unwrap();
        fs::write(subdir.join("index.md"), "# Docs").unwrap();

        let result = resolve_request_path(&fixture.config(), "docs");

        // safe_join returns canonicalized paths
        let expected = fixture.canonical_path().join("docs/index.md");
        assert_eq!(result, ResolvedPath::MarkdownFile(expected));
    }

    #[test]
    fn test_trailing_slash_to_markdown() {
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("about.md"), "# About").unwrap();

        let result = resolve_request_path(&fixture.config(), "about/");

        // safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(fixture.canonical_path().join("about.md"))
        );
    }

    #[test]
    fn test_dotted_filename_trailing_slash_to_markdown() {
        // Regression: a file whose name contains a period is served at a URL that
        // strips only the final extension (see build_markdown_url_path). The resolver
        // must reverse that by appending the extension, not replacing the trailing
        // dotted segment, otherwise `patrick-walsh-b.2010-03-03.md` 404s at
        // `/patrick-walsh-b.2010-03-03/`.
        let fixture = TestFixture::new();
        fs::write(
            fixture.path().join("patrick-walsh-b.2010-03-03.md"),
            "# Patrick",
        )
        .unwrap();

        let result = resolve_request_path(&fixture.config(), "patrick-walsh-b.2010-03-03/");

        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(
                fixture
                    .canonical_path()
                    .join("patrick-walsh-b.2010-03-03.md")
            )
        );
    }

    #[test]
    fn test_dotted_filename_without_trailing_slash_to_markdown() {
        // Mirrors test_trailing_slash_to_markdown semantics: a dotted filename must
        // also resolve when requested WITHOUT the trailing slash.
        let fixture = TestFixture::new();
        fs::write(
            fixture.path().join("patrick-walsh-b.2010-03-03.md"),
            "# Patrick",
        )
        .unwrap();

        let result = resolve_request_path(&fixture.config(), "patrick-walsh-b.2010-03-03");

        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(
                fixture
                    .canonical_path()
                    .join("patrick-walsh-b.2010-03-03.md")
            )
        );
    }

    #[test]
    fn test_multi_dot_filename_trailing_slash_to_markdown() {
        // A filename with multiple interior dots must resolve at its canonical URL
        // (`report.2024.final.md` -> `/report.2024.final/`).
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("report.2024.final.md"), "# Report").unwrap();

        let result = resolve_request_path(&fixture.config(), "report.2024.final/");

        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(fixture.canonical_path().join("report.2024.final.md"))
        );
    }

    #[test]
    fn test_static_folder_file() {
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("static/style.css"), "body {}").unwrap();

        let result = resolve_request_path(&fixture.config(), "style.css");

        // The static file path is canonicalized
        let expected = fixture
            .path()
            .join("static/style.css")
            .canonicalize()
            .unwrap();
        assert_eq!(result, ResolvedPath::StaticFile(expected));
    }

    #[test]
    fn test_static_folder_nested_path() {
        let fixture = TestFixture::new();
        fs::create_dir_all(fixture.path().join("static/images/blog")).unwrap();
        fs::write(
            fixture.path().join("static/images/blog/photo.png"),
            "fake image",
        )
        .unwrap();

        // Request for /images/blog/photo.png should find static/images/blog/photo.png
        let result = resolve_request_path(&fixture.config(), "images/blog/photo.png");

        let expected = fixture
            .path()
            .join("static/images/blog/photo.png")
            .canonicalize()
            .unwrap();
        assert_eq!(result, ResolvedPath::StaticFile(expected));
    }

    #[test]
    fn test_directory_listing() {
        let fixture = TestFixture::new();
        let subdir = fixture.path().join("posts");
        fs::create_dir(&subdir).unwrap();
        // No index file

        let result = resolve_request_path(&fixture.config(), "posts/");

        // safe_join returns canonicalized paths
        let expected = fixture.canonical_path().join("posts");
        assert_eq!(result, ResolvedPath::DirectoryListing(expected));
    }

    #[test]
    fn test_not_found() {
        let fixture = TestFixture::new();

        let result = resolve_request_path(&fixture.config(), "nonexistent");

        assert_eq!(result, ResolvedPath::NotFound);
    }

    #[test]
    fn test_nested_directory_with_index() {
        let fixture = TestFixture::new();
        let nested = fixture.path().join("blog/2024");
        fs::create_dir_all(&nested).unwrap();
        fs::write(nested.join("index.md"), "# Blog 2024").unwrap();

        let result = resolve_request_path(&fixture.config(), "blog/2024");

        // safe_join returns canonicalized paths
        let expected = fixture.canonical_path().join("blog/2024/index.md");
        assert_eq!(result, ResolvedPath::MarkdownFile(expected));
    }

    #[test]
    fn test_multiple_markdown_extensions() {
        let fixture =
            TestFixture::with_extensions(vec![String::from("md"), String::from("markdown")]);
        fs::write(fixture.path().join("notes.markdown"), "# Notes").unwrap();

        let result = resolve_request_path(&fixture.config(), "notes/");

        // safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(fixture.canonical_path().join("notes.markdown"))
        );
    }

    #[test]
    fn test_prefers_first_extension() {
        let fixture =
            TestFixture::with_extensions(vec![String::from("md"), String::from("markdown")]);
        // Create both .md and .markdown files
        fs::write(fixture.path().join("test.md"), "# MD").unwrap();
        fs::write(fixture.path().join("test.markdown"), "# Markdown").unwrap();

        let result = resolve_request_path(&fixture.config(), "test/");

        // Should prefer .md (first in list), safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(fixture.canonical_path().join("test.md"))
        );
    }

    #[test]
    fn test_root_path_empty_string() {
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("index.md"), "# Home").unwrap();

        let result = resolve_request_path(&fixture.config(), "");

        // Empty path resolves to base_dir, which is a directory with index.md
        // safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(fixture.canonical_path().join("index.md"))
        );
    }

    #[test]
    fn test_is_markdown_file() {
        let extensions = vec![String::from("md"), String::from("markdown")];

        assert!(is_markdown_file(Path::new("test.md"), &extensions));
        assert!(is_markdown_file(Path::new("test.markdown"), &extensions));
        assert!(!is_markdown_file(Path::new("test.txt"), &extensions));
        assert!(!is_markdown_file(Path::new("test"), &extensions));
    }

    #[test]
    fn test_strip_trailing_separator() {
        // A forward slash must be stripped on every platform: this function's
        // input comes from a request URL, so `/` is the separator even where
        // `std::path::MAIN_SEPARATOR` is `\`.
        assert_eq!(
            strip_trailing_separator(Path::new("/foo/bar/")),
            PathBuf::from("/foo/bar")
        );
        assert_eq!(
            strip_trailing_separator(Path::new("/foo/bar")),
            PathBuf::from("/foo/bar")
        );
        assert_eq!(
            strip_trailing_separator(Path::new("relative/")),
            PathBuf::from("relative")
        );
        // Repeated separators are all removed.
        assert_eq!(
            strip_trailing_separator(Path::new("/foo/bar//")),
            PathBuf::from("/foo/bar")
        );
    }

    /// The platform separator is stripped too, so a natively-joined path with a
    /// trailing separator is handled the same way as a URL-derived one.
    #[cfg(windows)]
    #[test]
    fn test_strip_trailing_separator_windows_backslash() {
        assert_eq!(
            strip_trailing_separator(Path::new(r"\foo\bar\")),
            PathBuf::from(r"\foo\bar")
        );
        // Mixed separators, which Windows accepts in real request handling.
        assert_eq!(
            strip_trailing_separator(Path::new(r"\foo\bar/")),
            PathBuf::from(r"\foo\bar")
        );
    }

    // ==================== normalize_link_target Tests ====================

    #[test]
    fn test_normalize_link_target_plain_path() {
        assert_eq!(normalize_link_target("docs/guide"), "docs/guide");
    }

    #[test]
    fn test_normalize_link_target_decodes_encoded_spaces() {
        assert_eq!(
            normalize_link_target("/IronCore%20Swag%20T-shirts%20Gifts"),
            "IronCore Swag T-shirts Gifts"
        );
    }

    #[test]
    fn test_normalize_link_target_strips_fragment() {
        assert_eq!(normalize_link_target("/docs/guide/#section"), "docs/guide");
    }

    #[test]
    fn test_normalize_link_target_strips_query() {
        assert_eq!(normalize_link_target("/docs/guide/?x=1&y=2"), "docs/guide");
    }

    #[test]
    fn test_normalize_link_target_strips_query_and_fragment_with_decoding() {
        assert_eq!(
            normalize_link_target("/My%20Page/?x=1#top"),
            "My Page",
            "fragment and query must be stripped before decoding/trimming"
        );
    }

    #[test]
    fn test_normalize_link_target_trims_leading_and_trailing_slashes() {
        assert_eq!(normalize_link_target("/docs/guide/"), "docs/guide");
        assert_eq!(normalize_link_target("docs/guide"), "docs/guide");
        assert_eq!(normalize_link_target("/"), "");
    }

    #[test]
    fn test_normalize_link_target_decodes_literal_percent_escape() {
        // A literal `%` must be authored as `%25`; valid escapes always decode.
        assert_eq!(normalize_link_target("/100%25"), "100%");
    }

    // ==================== Tag URL Resolution Tests ====================

    #[test]
    fn test_tag_source_index() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);
        let result = resolve_request_path(&fixture.config(), "tags/");

        assert_eq!(
            result,
            ResolvedPath::TagSourceIndex {
                source: "tags".to_string()
            }
        );
    }

    #[test]
    fn test_tag_source_index_without_trailing_slash() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);
        let result = resolve_request_path(&fixture.config(), "tags");

        assert_eq!(
            result,
            ResolvedPath::TagSourceIndex {
                source: "tags".to_string()
            }
        );
    }

    #[test]
    fn test_tag_page() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);
        let result = resolve_request_path(&fixture.config(), "tags/rust/");

        assert_eq!(
            result,
            ResolvedPath::TagPage {
                source: "tags".to_string(),
                value: "rust".to_string()
            }
        );
    }

    #[test]
    fn test_tag_page_without_trailing_slash() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);
        let result = resolve_request_path(&fixture.config(), "tags/rust");

        assert_eq!(
            result,
            ResolvedPath::TagPage {
                source: "tags".to_string(),
                value: "rust".to_string()
            }
        );
    }

    #[test]
    fn test_tag_url_case_insensitive_source() {
        let fixture = TestFixture::with_tag_sources(vec!["Tags".to_string()]);

        // Uppercase in URL should match lowercase config
        let result = resolve_request_path(&fixture.config(), "TAGS/rust/");

        assert_eq!(
            result,
            ResolvedPath::TagPage {
                source: "tags".to_string(),
                value: "rust".to_string()
            }
        );
    }

    #[test]
    fn test_tag_url_unknown_source_not_matched() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);

        // "categories" is not a configured tag source
        let result = resolve_request_path(&fixture.config(), "categories/rust/");

        assert_eq!(result, ResolvedPath::NotFound);
    }

    #[test]
    fn test_tag_url_no_sources_configured() {
        let fixture = TestFixture::new(); // Empty tag_sources
        let result = resolve_request_path(&fixture.config(), "tags/rust/");

        assert_eq!(result, ResolvedPath::NotFound);
    }

    #[test]
    fn test_tag_url_multiple_sources() {
        let fixture = TestFixture::with_tag_sources(vec![
            "tags".to_string(),
            "performers".to_string(),
            "taxonomy.categories".to_string(),
        ]);

        // All sources should be recognized
        assert_eq!(
            resolve_request_path(&fixture.config(), "tags/rust/"),
            ResolvedPath::TagPage {
                source: "tags".to_string(),
                value: "rust".to_string()
            }
        );
        assert_eq!(
            resolve_request_path(&fixture.config(), "performers/joshua_jay/"),
            ResolvedPath::TagPage {
                source: "performers".to_string(),
                value: "joshua_jay".to_string()
            }
        );
        assert_eq!(
            resolve_request_path(&fixture.config(), "taxonomy.categories/"),
            ResolvedPath::TagSourceIndex {
                source: "taxonomy.categories".to_string()
            }
        );
    }

    #[test]
    fn test_file_takes_precedence_over_tag_url() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);
        // Create a real markdown file at "tags.md"
        fs::write(fixture.path().join("tags.md"), "# Real Tags Page").unwrap();

        // File should take precedence over tag source index
        let result = resolve_request_path(&fixture.config(), "tags/");

        // safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::MarkdownFile(fixture.canonical_path().join("tags.md"))
        );
    }

    #[test]
    fn test_directory_takes_precedence_over_tag_url() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);
        // Create a real directory "tags/"
        fs::create_dir(fixture.path().join("tags")).unwrap();

        // Directory listing should take precedence
        let result = resolve_request_path(&fixture.config(), "tags/");

        // safe_join returns canonicalized paths
        assert_eq!(
            result,
            ResolvedPath::DirectoryListing(fixture.canonical_path().join("tags"))
        );
    }

    #[test]
    fn test_nested_tag_value_not_matched() {
        let fixture = TestFixture::with_tag_sources(vec!["tags".to_string()]);

        // More than 2 segments is not a valid tag URL
        let result = resolve_request_path(&fixture.config(), "tags/rust/advanced/");

        assert_eq!(result, ResolvedPath::NotFound);
    }

    #[test]
    fn test_try_resolve_tag_url_directly() {
        let sources = vec!["tags".to_string(), "performers".to_string()];

        // Tag source index
        assert_eq!(
            try_resolve_tag_url("tags/", &sources),
            Some(ResolvedPath::TagSourceIndex {
                source: "tags".to_string()
            })
        );

        // Tag page
        assert_eq!(
            try_resolve_tag_url("tags/rust", &sources),
            Some(ResolvedPath::TagPage {
                source: "tags".to_string(),
                value: "rust".to_string()
            })
        );

        // Unknown source
        assert_eq!(try_resolve_tag_url("unknown/value", &sources), None);

        // Empty path
        assert_eq!(try_resolve_tag_url("", &sources), None);

        // Empty sources
        assert_eq!(try_resolve_tag_url("tags/rust", &[]), None);
    }

    // ==================== Non-Canonical Index URL Redirect Tests ====================

    #[test]
    fn test_non_canonical_index_redirects() {
        let fixture = TestFixture::new();
        let docs = fixture.path().join("docs");
        fs::create_dir(&docs).unwrap();
        fs::write(docs.join("index.md"), "# Docs Index").unwrap();

        // /docs/index/ should redirect to /docs/
        let result = resolve_request_path(&fixture.config(), "docs/index/");
        assert_eq!(result, ResolvedPath::Redirect("/docs/".to_string()));
    }

    #[test]
    fn test_root_index_redirects() {
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("index.md"), "# Home").unwrap();

        // /index/ should redirect to /
        let result = resolve_request_path(&fixture.config(), "index/");
        assert_eq!(result, ResolvedPath::Redirect("/".to_string()));
    }

    #[test]
    fn test_nested_index_redirects() {
        let fixture = TestFixture::new();
        let nested = fixture.path().join("a/b/c");
        fs::create_dir_all(&nested).unwrap();
        fs::write(nested.join("index.md"), "# Nested").unwrap();

        // /a/b/c/index/ should redirect to /a/b/c/
        let result = resolve_request_path(&fixture.config(), "a/b/c/index/");
        assert_eq!(result, ResolvedPath::Redirect("/a/b/c/".to_string()));

        // A redirect target is a URL, so it must never carry a platform
        // separator. Asserted explicitly because the equality above only fails
        // on platforms where `\` is the separator.
        let ResolvedPath::Redirect(target) = result else {
            panic!("expected a redirect");
        };
        assert!(
            !target.contains('\\'),
            "redirect target must not contain a backslash, got {target}"
        );
    }

    #[test]
    fn test_regular_file_named_index_no_redirect() {
        let fixture = TestFixture::new();
        // Create a regular file that happens to be named index.md (not in a directory with index)
        fs::write(fixture.path().join("index.md"), "# Regular Index").unwrap();

        // But also create docs/readme.md as a standalone file (no parent index)
        let docs = fixture.path().join("docs");
        fs::create_dir(&docs).unwrap();
        fs::write(docs.join("readme.md"), "# Readme").unwrap();

        // /docs/readme/ should NOT redirect (readme is not the index file)
        let result = resolve_request_path(&fixture.config(), "docs/readme/");
        assert!(matches!(result, ResolvedPath::MarkdownFile(_)));
    }

    #[test]
    fn test_index_without_trailing_slash_redirects() {
        let fixture = TestFixture::new();
        let docs = fixture.path().join("docs");
        fs::create_dir(&docs).unwrap();
        fs::write(docs.join("index.md"), "# Docs Index").unwrap();

        // /docs/index (without trailing slash) should also redirect to /docs/
        let result = resolve_request_path(&fixture.config(), "docs/index");
        assert_eq!(result, ResolvedPath::Redirect("/docs/".to_string()));
    }

    // ==================== Path Traversal Security Tests ====================

    #[test]
    fn test_path_traversal_blocked_with_dotdot() {
        let fixture = TestFixture::new();
        // Create a file outside the temp directory (simulating /etc/passwd)
        // We can't actually create /etc/passwd, so we test that path traversal returns NotFound

        // Various path traversal attempts should all return NotFound
        let attacks = vec![
            "../../../etc/passwd",
            "..%2F..%2F..%2Fetc/passwd",
            "foo/../../../etc/passwd",
            "foo/bar/../../../etc/passwd",
            "....//....//etc/passwd",
        ];

        for attack in attacks {
            let result = resolve_request_path(&fixture.config(), attack);
            assert_eq!(
                result,
                ResolvedPath::NotFound,
                "Path traversal should be blocked for: {}",
                attack
            );
        }
    }

    #[test]
    fn test_path_traversal_blocked_in_static_folder() {
        let fixture = TestFixture::new();
        // Create a file in static folder
        fs::write(fixture.path().join("static/safe.txt"), "safe content").unwrap();

        // Path traversal within static folder should be blocked
        let attacks = vec![
            "../readme.md",     // Try to escape static to base_dir
            "../../etc/passwd", // Try to escape completely
            "foo/../../../etc/passwd",
        ];

        for attack in &attacks {
            let result = find_in_static_folder(&fixture.config(), attack);
            assert!(
                result.is_none(),
                "Static folder path traversal should be blocked for: {}",
                attack
            );
        }

        // But valid file should still work
        let valid = find_in_static_folder(&fixture.config(), "safe.txt");
        assert!(valid.is_some(), "Valid static file should be found");
    }

    #[test]
    fn test_safe_join_blocks_traversal() {
        let dir = TempDir::new().unwrap();
        let base = dir.path();

        // Create a file inside
        fs::write(base.join("inside.txt"), "inside").unwrap();

        // Valid path should work
        let valid = safe_join(base, None, "inside.txt");
        assert!(valid.is_some(), "Valid path should work");
        assert!(valid.unwrap().ends_with("inside.txt"));

        // Path traversal should be blocked
        let attack = safe_join(base, None, "../../../etc/passwd");
        assert!(attack.is_none(), "Path traversal should be blocked");

        // Complex traversal should be blocked
        let attack2 = safe_join(base, None, "foo/../../../etc/passwd");
        assert!(
            attack2.is_none(),
            "Complex path traversal should be blocked"
        );
    }

    #[test]
    fn test_safe_join_allows_internal_dotdot() {
        let dir = TempDir::new().unwrap();
        let base = dir.path();

        // Create nested structure
        fs::create_dir_all(base.join("foo/bar")).unwrap();
        fs::write(base.join("foo/sibling.txt"), "sibling").unwrap();

        // Going up and back down within base_dir should work
        let valid = safe_join(base, None, "foo/bar/../sibling.txt");
        assert!(valid.is_some(), "Internal navigation should work");
        let resolved = valid.unwrap();
        assert!(
            resolved.ends_with("sibling.txt"),
            "Should resolve to sibling.txt, got: {:?}",
            resolved
        );
    }

    #[test]
    fn test_path_traversal_returns_not_found_not_error() {
        let fixture = TestFixture::new();

        // Path traversal should cleanly return NotFound, not panic or error
        let result = resolve_request_path(&fixture.config(), "../../../../etc/passwd");

        // Should be NotFound, not a panic or file access
        assert_eq!(result, ResolvedPath::NotFound);
    }

    #[test]
    fn test_symlink_escape_blocked() {
        // This test verifies that symlinks pointing outside base_dir are blocked
        let dir = TempDir::new().unwrap();
        let base = dir.path();
        fs::create_dir(base.join("static")).unwrap();

        // Create a symlink in static folder pointing outside
        // (This is OS-dependent and may not work on all systems)
        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;
            let link_path = base.join("static/escape");
            // Try to create symlink to /tmp (which exists on most Unix systems)
            if symlink("/tmp", &link_path).is_ok() {
                let extensions = vec![String::from("md")];
                let tag_sources: Vec<String> = vec![];
                let config = PathResolverConfig {
                    base_dir: base,
                    canonical_base_dir: None,
                    static_folder: "static",
                    markdown_extensions: &extensions,
                    index_file: "index.md",
                    tag_sources: &tag_sources,
                };

                // Following the symlink should be blocked
                let result = find_in_static_folder(&config, "escape/some_file");
                assert!(result.is_none(), "Symlink escape should be blocked");
            }
        }
    }

    /// Regression: `safe_join` used to fall through to its "path doesn't exist
    /// yet" branch when `canonicalize()` *succeeded* but resolved outside the
    /// base. That branch validates only the parent, so it handed back the
    /// unresolved symlink and the server served the out-of-repo target
    /// (`GET /passwd` -> `/etc/passwd`).
    #[cfg(unix)]
    #[test]
    fn test_safe_join_blocks_symlink_to_absolute_path_outside_base() {
        use std::os::unix::fs::symlink;

        let outside = TempDir::new().unwrap();
        let secret = outside.path().join("secret.txt");
        fs::write(&secret, "top secret").unwrap();

        let dir = TempDir::new().unwrap();
        let base = dir.path();
        symlink(&secret, base.join("passwd")).unwrap();

        assert_eq!(
            safe_join(base, None, "passwd"),
            None,
            "a symlink resolving outside the base must not be joined"
        );
    }

    /// The relative form of the same escape: an attacker needs no knowledge of
    /// the victim's absolute paths.
    #[cfg(unix)]
    #[test]
    fn test_safe_join_blocks_relative_symlink_outside_base() {
        use std::os::unix::fs::symlink;

        let outer = TempDir::new().unwrap();
        fs::write(outer.path().join("outside.txt"), "top secret").unwrap();
        let base = outer.path().join("repo/nested");
        fs::create_dir_all(&base).unwrap();
        symlink("../../outside.txt", base.join("escape.txt")).unwrap();

        assert_eq!(
            safe_join(&base, None, "escape.txt"),
            None,
            "a relative symlink resolving outside the base must not be joined"
        );
    }

    /// A symlink that stays inside the base is still followed.
    #[cfg(unix)]
    #[test]
    fn test_safe_join_allows_symlink_inside_base() {
        use std::os::unix::fs::symlink;

        let dir = TempDir::new().unwrap();
        let base = dir.path();
        fs::write(base.join("real.txt"), "inside").unwrap();
        symlink("real.txt", base.join("alias.txt")).unwrap();

        let joined = safe_join(base, None, "alias.txt").expect("in-base symlink should resolve");
        assert_eq!(joined, base.canonicalize().unwrap().join("real.txt"));
    }

    /// The escape fix must not break the two branches that legitimately return
    /// `Some`: an existing in-base file, and a not-yet-existing sibling whose
    /// parent is in-base (how `/foo/` probes for `foo.md`).
    #[test]
    fn test_safe_join_existing_file_and_missing_sibling() {
        let dir = TempDir::new().unwrap();
        let base = dir.path();
        let canonical = base.canonicalize().unwrap();
        fs::create_dir(base.join("docs")).unwrap();
        fs::write(base.join("docs/guide.md"), "# Guide").unwrap();

        assert_eq!(
            safe_join(base, None, "docs/guide.md"),
            Some(canonical.join("docs/guide.md")),
            "an existing in-base file must resolve"
        );
        assert_eq!(
            safe_join(base, None, "docs/guide"),
            Some(canonical.join("docs/guide")),
            "a not-yet-existing name under an in-base parent must resolve"
        );
    }

    /// Retargeted. This layer used to insist that the overlay itself sit under
    /// the repository root, which 404'd the whole `repo/content` +
    /// `repo/static` layout. Deciding *how far* `static_folder` may reach is
    /// `Config::validate_static_folder`'s job now (peers only, never via `$HOME`
    /// or `/`); what this layer owes is that an out-of-root overlay actually
    /// resolves — the regression — while a request path still cannot walk out
    /// of it.
    #[test]
    fn test_find_in_static_folder_serves_peer_overlay_but_contains_requests() {
        let outer = TempDir::new().unwrap();
        let peer = outer.path().join("static");
        fs::create_dir(&peer).unwrap();
        fs::write(peer.join("logo.png"), "PNG").unwrap();
        fs::write(outer.path().join("id_rsa"), "PRIVATE KEY").unwrap();

        let base = outer.path().join("content");
        fs::create_dir(&base).unwrap();
        let canonical = base.canonicalize().unwrap();

        let extensions = vec![String::from("md")];
        let tag_sources: Vec<String> = vec![];

        let peer_overlay = PathResolverConfig {
            base_dir: &base,
            canonical_base_dir: Some(&canonical),
            static_folder: "../static",
            markdown_extensions: &extensions,
            index_file: "index.md",
            tag_sources: &tag_sources,
        };
        assert_eq!(
            find_in_static_folder(&peer_overlay, "logo.png"),
            Some(peer.canonicalize().unwrap().join("logo.png")),
            "a peer static folder must serve its own files"
        );
        assert!(
            matches!(
                resolve_request_path(&peer_overlay, "logo.png"),
                ResolvedPath::StaticFile(_)
            ),
            "the resolver must route the peer overlay's files as static files"
        );

        // Containment is measured against the overlay, so climbing out of it
        // fails even though the target is readable and nearby.
        for attack in ["../id_rsa", "../../etc/passwd", "sub/../../id_rsa"] {
            assert_eq!(
                find_in_static_folder(&peer_overlay, attack),
                None,
                "a request path must not climb out of the static overlay: {attack}"
            );
        }

        // An absolute overlay (only reachable via MBR_STATIC_FOLDER) behaves the
        // same way: it serves its own contents and contains request paths.
        let absolute = peer.to_string_lossy().into_owned();
        let absolute_overlay = PathResolverConfig {
            static_folder: &absolute,
            ..peer_overlay
        };
        assert_eq!(
            find_in_static_folder(&absolute_overlay, "logo.png"),
            Some(peer.canonicalize().unwrap().join("logo.png")),
            "an absolute static folder must serve its own files"
        );
        assert_eq!(
            find_in_static_folder(&absolute_overlay, "../id_rsa"),
            None,
            "an absolute static folder must still contain request paths"
        );
    }

    /// A symlink *inside* the overlay is the traversal route that survives the
    /// policy change: the value of `static_folder` is innocent, and only
    /// canonicalizing the request target reveals that it lands on `/etc/passwd`.
    #[cfg(unix)]
    #[test]
    fn test_find_in_static_folder_blocks_symlink_out_of_overlay() {
        use std::os::unix::fs::symlink;

        let outer = TempDir::new().unwrap();
        let secrets = outer.path().join("secrets");
        fs::create_dir(&secrets).unwrap();
        fs::write(secrets.join("passwd"), "root:x:0:0").unwrap();

        let base = outer.path().join("content");
        fs::create_dir(&base).unwrap();
        let canonical = base.canonicalize().unwrap();
        let peer = outer.path().join("static");
        fs::create_dir(&peer).unwrap();

        // A file and a whole directory, each symlinked out of the overlay.
        symlink(secrets.join("passwd"), peer.join("passwd")).unwrap();
        symlink(&secrets, peer.join("leak")).unwrap();

        let extensions = vec![String::from("md")];
        let tag_sources: Vec<String> = vec![];
        let config = PathResolverConfig {
            base_dir: &base,
            canonical_base_dir: Some(&canonical),
            static_folder: "../static",
            markdown_extensions: &extensions,
            index_file: "index.md",
            tag_sources: &tag_sources,
        };

        for attack in ["passwd", "leak/passwd"] {
            assert_eq!(
                find_in_static_folder(&config, attack),
                None,
                "a symlink out of the static overlay must not be served: {attack}"
            );
            assert_eq!(
                resolve_request_path(&config, attack),
                ResolvedPath::NotFound,
                "the resolver must 404 a symlink out of the static overlay: {attack}"
            );
        }
    }

    // ==================== Static Folder Tests ====================

    #[test]
    fn test_precedence_base_dir_over_static() {
        // Request /image.png with file in BOTH locations
        // Should prefer base_dir (step 1 wins over step 4b)
        let fixture = TestFixture::new();
        fs::write(fixture.path().join("image.png"), "direct").unwrap();
        fs::write(fixture.path().join("static/image.png"), "static").unwrap();

        let result = resolve_request_path(&fixture.config(), "image.png");

        // Should return base_dir file, not static folder
        assert_eq!(
            result,
            ResolvedPath::StaticFile(fixture.canonical_path().join("image.png"))
        );

        // Verify the correct file would be served by checking content
        let resolved_path = match result {
            ResolvedPath::StaticFile(p) => p,
            _ => panic!("Expected StaticFile"),
        };
        let content = fs::read_to_string(resolved_path).unwrap();
        assert_eq!(
            content, "direct",
            "Should serve file from base_dir, not static folder"
        );
    }

    #[test]
    fn test_safe_join_failure_static_fallback() {
        // Request /images/blog/photo.png where:
        // - base_dir/images/ does NOT exist (safe_join fails)
        // - static/images/blog/photo.png DOES exist
        // This is the exact regression case
        let fixture = TestFixture::new();
        fs::create_dir_all(fixture.path().join("static/images/blog")).unwrap();
        fs::write(fixture.path().join("static/images/blog/photo.png"), "image").unwrap();
        // Note: base_dir/images/ does NOT exist

        let result = resolve_request_path(&fixture.config(), "images/blog/photo.png");

        let expected = fixture
            .path()
            .join("static/images/blog/photo.png")
            .canonicalize()
            .unwrap();
        assert_eq!(result, ResolvedPath::StaticFile(expected));
    }

    #[test]
    fn test_empty_static_folder_config() {
        // Config with static_folder = ""
        // Static folder lookup should be skipped
        let dir = TempDir::new().unwrap();
        fs::create_dir(dir.path().join("static")).unwrap();
        fs::write(dir.path().join("static/file.txt"), "content").unwrap();

        let extensions = vec![String::from("md")];
        let tag_sources: Vec<String> = vec![];
        let config = PathResolverConfig {
            base_dir: dir.path(),
            canonical_base_dir: None,
            static_folder: "", // Empty!
            markdown_extensions: &extensions,
            index_file: "index.md",
            tag_sources: &tag_sources,
        };

        let result = resolve_request_path(&config, "file.txt");
        assert_eq!(result, ResolvedPath::NotFound);
    }

    #[test]
    fn test_deeply_nested_static_path() {
        // Test 5+ levels of nesting
        let fixture = TestFixture::new();
        fs::create_dir_all(fixture.path().join("static/a/b/c/d/e")).unwrap();
        fs::write(fixture.path().join("static/a/b/c/d/e/deep.png"), "deep").unwrap();

        let result = resolve_request_path(&fixture.config(), "a/b/c/d/e/deep.png");

        let expected = fixture
            .path()
            .join("static/a/b/c/d/e/deep.png")
            .canonicalize()
            .unwrap();
        assert_eq!(result, ResolvedPath::StaticFile(expected));
    }

    // Only the macOS and Linux canonicalize() behaviors are asserted below, so
    // the test is gated to those platforms rather than silently passing
    // elsewhere.
    #[cfg(any(target_os = "macos", target_os = "linux"))]
    #[test]
    fn test_static_folder_with_trailing_slash_request() {
        // Request "images/photo.png/" with trailing slash
        // Behavior is platform-dependent:
        // - macOS: canonicalize() tolerates trailing slashes on file paths
        // - Linux: canonicalize() rejects trailing slashes on file paths
        let fixture = TestFixture::new();
        fs::create_dir_all(fixture.path().join("static/images")).unwrap();
        fs::write(fixture.path().join("static/images/photo.png"), "img").unwrap();

        let result = resolve_request_path(&fixture.config(), "images/photo.png/");

        #[cfg(target_os = "macos")]
        {
            // macOS tolerates trailing slash on file paths
            let expected = fixture
                .path()
                .join("static/images/photo.png")
                .canonicalize()
                .unwrap();
            assert_eq!(result, ResolvedPath::StaticFile(expected));
        }

        #[cfg(target_os = "linux")]
        {
            // Linux rejects trailing slash on file paths (stricter behavior)
            assert_eq!(result, ResolvedPath::NotFound);
        }
    }

    #[test]
    fn test_static_folder_url_encoded_spaces() {
        // Test that paths with spaces work through static folder
        let fixture = TestFixture::new();
        fs::create_dir_all(fixture.path().join("static/my images")).unwrap();
        fs::write(
            fixture.path().join("static/my images/photo file.jpg"),
            "img",
        )
        .unwrap();

        // URL-decoded path (as server would provide after decoding)
        let result = resolve_request_path(&fixture.config(), "my images/photo file.jpg");

        let expected = fixture
            .path()
            .join("static/my images/photo file.jpg")
            .canonicalize()
            .unwrap();
        assert_eq!(result, ResolvedPath::StaticFile(expected));
    }
}

#[cfg(test)]
mod proptests {
    use super::*;
    use proptest::prelude::*;
    use std::fs;
    use tempfile::TempDir;

    // Strategy for valid path component names
    fn path_component_strategy() -> impl Strategy<Value = String> {
        "[a-zA-Z0-9_-]{1,12}"
    }

    // Strategy for valid extensions
    fn extension_strategy() -> impl Strategy<Value = String> {
        "[a-z]{1,5}"
    }

    proptest! {
        /// is_markdown_file is deterministic
        #[test]
        fn prop_is_markdown_file_deterministic(
            filename in path_component_strategy(),
            ext in extension_strategy(),
            extensions in proptest::collection::vec(extension_strategy(), 1..4)
        ) {
            let path = PathBuf::from(format!("{}.{}", filename, ext));
            let result1 = is_markdown_file(&path, &extensions);
            let result2 = is_markdown_file(&path, &extensions);
            prop_assert_eq!(result1, result2);
        }

        /// is_markdown_file returns true when extension matches
        #[test]
        fn prop_is_markdown_file_matches_extension(
            filename in path_component_strategy(),
            extensions in proptest::collection::vec(extension_strategy(), 1..4)
        ) {
            // Use the first extension from the list
            if let Some(ext) = extensions.first() {
                let path = PathBuf::from(format!("{}.{}", filename, ext));
                prop_assert!(is_markdown_file(&path, &extensions));
            }
        }

        /// strip_trailing_separator is idempotent
        #[test]
        fn prop_strip_trailing_separator_idempotent(
            components in proptest::collection::vec(path_component_strategy(), 1..5)
        ) {
            let path_str = format!("/{}/", components.join("/"));
            let path = Path::new(&path_str);

            let once = strip_trailing_separator(path);
            let twice = strip_trailing_separator(&once);

            prop_assert_eq!(once, twice);
        }

        /// strip_trailing_separator never ends with a separator (except for root).
        ///
        /// Asserts on `/` (the URL contract this function actually operates
        /// under) *and* on the platform separator, so neither assumption can
        /// regress independently.
        #[test]
        fn prop_strip_trailing_separator_no_trailing(
            components in proptest::collection::vec(path_component_strategy(), 1..5)
        ) {
            let path_str = format!("/{}/", components.join("/"));
            let path = Path::new(&path_str);
            let result = strip_trailing_separator(path);
            let result_str = result.to_string_lossy();

            prop_assert!(
                !result_str.ends_with('/'),
                "Result {:?} should not end with /",
                result_str
            );
            prop_assert!(
                !result_str.ends_with(std::path::MAIN_SEPARATOR),
                "Result {:?} should not end with the platform separator",
                result_str
            );
        }

        /// Path resolution is deterministic for the same filesystem state
        #[test]
        fn prop_path_resolution_deterministic(
            request_path in proptest::collection::vec(path_component_strategy(), 0..3)
        ) {
            let dir = TempDir::new().unwrap();
            fs::create_dir(dir.path().join("static")).unwrap();

            // Create a markdown file
            fs::write(dir.path().join("test.md"), "# Test").unwrap();

            let extensions = vec![String::from("md")];
            let tag_sources: Vec<String> = vec![];
            let config = PathResolverConfig {
                base_dir: dir.path(),
                canonical_base_dir: None,
                static_folder: "static",
                markdown_extensions: &extensions,
                index_file: "index.md",
                tag_sources: &tag_sources,
            };

            let path_str = request_path.join("/");

            let result1 = resolve_request_path(&config, &path_str);
            let result2 = resolve_request_path(&config, &path_str);

            prop_assert_eq!(result1, result2);
        }

        /// Path traversal with ".." in paths doesn't cause panics
        /// and returns deterministic results
        #[test]
        fn prop_path_traversal_no_panic(
            prefix in proptest::collection::vec(path_component_strategy(), 0..2),
            suffix in proptest::collection::vec(path_component_strategy(), 0..2)
        ) {
            let dir = TempDir::new().unwrap();
            let base_dir = dir.path();
            fs::create_dir(base_dir.join("static")).unwrap();

            let extensions = vec![String::from("md")];
            let tag_sources: Vec<String> = vec![];
            let config = PathResolverConfig {
                base_dir,
                canonical_base_dir: None,
                static_folder: "static",
                markdown_extensions: &extensions,
                index_file: "index.md",
                tag_sources: &tag_sources,
            };

            // Try various path traversal patterns
            let attack_paths = vec![
                format!("{}/../{}", prefix.join("/"), suffix.join("/")),
                format!("../{}", suffix.join("/")),
                format!("{}/../../{}", prefix.join("/"), suffix.join("/")),
            ];

            for attack_path in attack_paths {
                // Should not panic and should return consistent results
                let result1 = resolve_request_path(&config, &attack_path);
                let result2 = resolve_request_path(&config, &attack_path);
                prop_assert_eq!(result1, result2, "Results should be deterministic for {:?}", attack_path);
            }
        }
    }
}