rch-common 2.1.3

Shared types and utilities for Remote Compilation Helper
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
//! Canonical path topology utilities for host/worker project mapping.
//!
//! This module normalizes project roots to a single canonical namespace so
//! equivalent aliases (for example `/dp` and `/data/projects`) map to one
//! deterministic identity. It also emits structured decision traces to aid
//! troubleshooting when path normalization fails.

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

/// Canonical root used for project identity and transfer safety checks.
pub const DEFAULT_CANONICAL_PROJECT_ROOT: &str = "/data/projects";

/// Alias root expected to point at [`DEFAULT_CANONICAL_PROJECT_ROOT`].
pub const DEFAULT_ALIAS_PROJECT_ROOT: &str = "/dp";

/// Policy describing canonical and alias roots used for normalization.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathTopologyPolicy {
    canonical_root: PathBuf,
    alias_root: PathBuf,
}

impl PathTopologyPolicy {
    /// Create a policy with explicit canonical and alias roots.
    pub fn new(canonical_root: PathBuf, alias_root: PathBuf) -> Self {
        Self {
            canonical_root,
            alias_root,
        }
    }

    /// Canonical root path.
    pub fn canonical_root(&self) -> &Path {
        &self.canonical_root
    }

    /// Alias root path.
    pub fn alias_root(&self) -> &Path {
        &self.alias_root
    }
}

impl Default for PathTopologyPolicy {
    fn default() -> Self {
        Self {
            canonical_root: PathBuf::from(DEFAULT_CANONICAL_PROJECT_ROOT),
            alias_root: PathBuf::from(DEFAULT_ALIAS_PROJECT_ROOT),
        }
    }
}

/// Structured trace for normalization decisions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NormalizationDecision {
    ReceivedInput(PathBuf),
    VerifiedAbsoluteInput(PathBuf),
    AliasPrefixDetected(PathBuf),
    AliasSymlinkVerified {
        alias_root: PathBuf,
        alias_target: PathBuf,
    },
    AliasSubtreeSymlinkVerified {
        alias_root: PathBuf,
        alias_target: PathBuf,
        canonical_root: PathBuf,
    },
    AliasDirectoryEntryVerified {
        alias_root: PathBuf,
        canonical_input: PathBuf,
    },
    CanonicalRootResolved(PathBuf),
    CanonicalInputResolved(PathBuf),
    VerifiedWithinCanonicalRoot {
        canonical_path: PathBuf,
        canonical_root: PathBuf,
    },
}

impl fmt::Display for NormalizationDecision {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::ReceivedInput(path) => write!(f, "received_input={}", path.display()),
            Self::VerifiedAbsoluteInput(path) => {
                write!(f, "verified_absolute_input={}", path.display())
            }
            Self::AliasPrefixDetected(alias_root) => {
                write!(f, "alias_prefix_detected={}", alias_root.display())
            }
            Self::AliasSymlinkVerified {
                alias_root,
                alias_target,
            } => write!(
                f,
                "alias_symlink_verified={} -> {}",
                alias_root.display(),
                alias_target.display()
            ),
            Self::AliasSubtreeSymlinkVerified {
                alias_root,
                alias_target,
                canonical_root,
            } => write!(
                f,
                "alias_subtree_symlink_verified={} -> {} root={}",
                alias_root.display(),
                alias_target.display(),
                canonical_root.display()
            ),
            Self::AliasDirectoryEntryVerified {
                alias_root,
                canonical_input,
            } => write!(
                f,
                "alias_directory_entry_verified={} -> {}",
                alias_root.display(),
                canonical_input.display()
            ),
            Self::CanonicalRootResolved(path) => {
                write!(f, "canonical_root_resolved={}", path.display())
            }
            Self::CanonicalInputResolved(path) => {
                write!(f, "canonical_input_resolved={}", path.display())
            }
            Self::VerifiedWithinCanonicalRoot {
                canonical_path,
                canonical_root,
            } => write!(
                f,
                "verified_within_root={} root={}",
                canonical_path.display(),
                canonical_root.display()
            ),
        }
    }
}

/// Successful normalization result with deterministic canonical path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NormalizedProjectPath {
    canonical_path: PathBuf,
    canonical_root: PathBuf,
    used_alias_prefix: bool,
    decisions: Vec<NormalizationDecision>,
}

impl NormalizedProjectPath {
    /// Canonical path for this project root.
    pub fn canonical_path(&self) -> &Path {
        &self.canonical_path
    }

    /// Canonical project root used for containment checks.
    pub fn canonical_root(&self) -> &Path {
        &self.canonical_root
    }

    /// Whether the input path used the alias prefix (for example `/dp`).
    pub fn used_alias_prefix(&self) -> bool {
        self.used_alias_prefix
    }

    /// Structured decision trace for diagnostics.
    pub fn decision_trace(&self) -> &[NormalizationDecision] {
        &self.decisions
    }
}

/// Error class for path normalization failures.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PathNormalizationErrorKind {
    NotAbsoluteInput,
    CanonicalRootMissing,
    CanonicalRootResolveFailed,
    AliasMissing,
    AliasNotSymlink,
    AliasReadLinkFailed,
    AliasTargetResolveFailed,
    AliasWrongTarget,
    InputResolveFailed,
    OutsideCanonicalRoot,
}

impl fmt::Display for PathNormalizationErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NotAbsoluteInput => write!(f, "input path is not absolute"),
            Self::CanonicalRootMissing => write!(f, "canonical root is missing"),
            Self::CanonicalRootResolveFailed => write!(f, "failed to resolve canonical root"),
            Self::AliasMissing => write!(f, "alias root is missing"),
            Self::AliasNotSymlink => write!(f, "alias root is not a symlink"),
            Self::AliasReadLinkFailed => write!(f, "failed to read alias symlink"),
            Self::AliasTargetResolveFailed => write!(f, "failed to resolve alias target"),
            Self::AliasWrongTarget => write!(f, "alias points to unexpected target"),
            Self::InputResolveFailed => write!(f, "failed to resolve input path"),
            Self::OutsideCanonicalRoot => write!(f, "input resolves outside canonical root"),
        }
    }
}

/// Normalization error with structured trace context.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathNormalizationError {
    kind: PathNormalizationErrorKind,
    input_path: PathBuf,
    detail: String,
    decisions: Vec<NormalizationDecision>,
}

impl PathNormalizationError {
    fn new(
        kind: PathNormalizationErrorKind,
        input_path: &Path,
        detail: impl Into<String>,
        decisions: &[NormalizationDecision],
    ) -> Self {
        Self {
            kind,
            input_path: input_path.to_path_buf(),
            detail: detail.into(),
            decisions: decisions.to_vec(),
        }
    }

    /// Error category.
    pub fn kind(&self) -> &PathNormalizationErrorKind {
        &self.kind
    }

    /// Human-readable detail about the failure.
    pub fn detail(&self) -> &str {
        &self.detail
    }

    /// Structured decision trace for diagnostics.
    pub fn decision_trace(&self) -> &[NormalizationDecision] {
        &self.decisions
    }
}

impl fmt::Display for PathNormalizationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} (input: {}, detail: {})",
            self.kind,
            self.input_path.display(),
            self.detail
        )
    }
}

impl std::error::Error for PathNormalizationError {}

/// Normalize a project path using the default `/data/projects` + `/dp` policy.
pub fn normalize_project_path(
    path: &Path,
) -> Result<NormalizedProjectPath, PathNormalizationError> {
    normalize_project_path_with_policy(path, &PathTopologyPolicy::default())
}

/// Normalize a project path with explicit topology policy.
pub fn normalize_project_path_with_policy(
    path: &Path,
    policy: &PathTopologyPolicy,
) -> Result<NormalizedProjectPath, PathNormalizationError> {
    let mut decisions = vec![NormalizationDecision::ReceivedInput(path.to_path_buf())];

    if !path.is_absolute() {
        return Err(PathNormalizationError::new(
            PathNormalizationErrorKind::NotAbsoluteInput,
            path,
            "path must be absolute",
            &decisions,
        ));
    }
    decisions.push(NormalizationDecision::VerifiedAbsoluteInput(
        path.to_path_buf(),
    ));

    let canonical_root = resolve_canonical_root(path, policy, &mut decisions)?;

    // A policy with identical roots has no alias namespace. Resolve its paths
    // normally, including parent components, then enforce canonical containment.
    let used_alias_prefix =
        policy.alias_root() != policy.canonical_root() && path.starts_with(policy.alias_root());
    let alias_mapped_input = if used_alias_prefix {
        decisions.push(NormalizationDecision::AliasPrefixDetected(
            policy.alias_root().to_path_buf(),
        ));
        verify_alias(path, policy.alias_root(), &canonical_root, &mut decisions)?
    } else {
        None
    };

    let canonical_input = if let Some(alias_mapped_input) = alias_mapped_input {
        alias_mapped_input
    } else {
        std::fs::canonicalize(path).map_err(|e| {
            PathNormalizationError::new(
                PathNormalizationErrorKind::InputResolveFailed,
                path,
                e.to_string(),
                &decisions,
            )
        })?
    };
    decisions.push(NormalizationDecision::CanonicalInputResolved(
        canonical_input.clone(),
    ));

    if !canonical_input.starts_with(&canonical_root) {
        return Err(PathNormalizationError::new(
            PathNormalizationErrorKind::OutsideCanonicalRoot,
            path,
            format!(
                "resolved={} root={}",
                canonical_input.display(),
                canonical_root.display()
            ),
            &decisions,
        ));
    }
    decisions.push(NormalizationDecision::VerifiedWithinCanonicalRoot {
        canonical_path: canonical_input.clone(),
        canonical_root: canonical_root.clone(),
    });

    Ok(NormalizedProjectPath {
        canonical_path: canonical_input,
        canonical_root,
        used_alias_prefix,
        decisions,
    })
}

fn resolve_canonical_root(
    input_path: &Path,
    policy: &PathTopologyPolicy,
    decisions: &mut Vec<NormalizationDecision>,
) -> Result<PathBuf, PathNormalizationError> {
    if !policy.canonical_root().exists() {
        if let Some(alias_target) = try_resolve_alias_target(policy.alias_root()) {
            decisions.push(NormalizationDecision::CanonicalRootResolved(
                alias_target.clone(),
            ));
            return Ok(alias_target);
        }

        return Err(PathNormalizationError::new(
            PathNormalizationErrorKind::CanonicalRootMissing,
            input_path,
            format!("missing root {}", policy.canonical_root().display()),
            decisions,
        ));
    }

    let canonical_root = std::fs::canonicalize(policy.canonical_root()).map_err(|e| {
        PathNormalizationError::new(
            PathNormalizationErrorKind::CanonicalRootResolveFailed,
            input_path,
            e.to_string(),
            decisions,
        )
    })?;
    decisions.push(NormalizationDecision::CanonicalRootResolved(
        canonical_root.clone(),
    ));
    Ok(canonical_root)
}

fn try_resolve_alias_target(alias_root: &Path) -> Option<PathBuf> {
    let metadata = std::fs::symlink_metadata(alias_root).ok()?;
    if !metadata.file_type().is_symlink() {
        return None;
    }

    let raw_target = std::fs::read_link(alias_root).ok()?;
    let absolute_target = if raw_target.is_absolute() {
        raw_target
    } else {
        alias_root
            .parent()
            .unwrap_or_else(|| Path::new("/"))
            .join(raw_target)
    };

    std::fs::canonicalize(absolute_target).ok()
}

fn verify_alias(
    input_path: &Path,
    alias_root: &Path,
    canonical_root: &Path,
    decisions: &mut Vec<NormalizationDecision>,
) -> Result<Option<PathBuf>, PathNormalizationError> {
    // With one namespace there is no alias mapping to validate. Resolve the
    // actual path (including parent components and symlinks), then let the
    // caller enforce containment against the canonical root.
    if alias_root == canonical_root {
        return Ok(None);
    }

    let metadata = std::fs::symlink_metadata(alias_root).map_err(|e| {
        let kind = if e.kind() == std::io::ErrorKind::NotFound {
            PathNormalizationErrorKind::AliasMissing
        } else {
            PathNormalizationErrorKind::AliasReadLinkFailed
        };
        PathNormalizationError::new(kind, input_path, e.to_string(), decisions)
    })?;

    if !metadata.file_type().is_symlink() {
        if let Some(canonical_input) =
            try_map_alias_directory_entry(input_path, alias_root, canonical_root, decisions)?
        {
            return Ok(Some(canonical_input));
        }

        return Err(PathNormalizationError::new(
            PathNormalizationErrorKind::AliasNotSymlink,
            input_path,
            format!("alias root is not a symlink: {}", alias_root.display()),
            decisions,
        ));
    }

    let raw_target = std::fs::read_link(alias_root).map_err(|e| {
        PathNormalizationError::new(
            PathNormalizationErrorKind::AliasReadLinkFailed,
            input_path,
            e.to_string(),
            decisions,
        )
    })?;
    let absolute_target = if raw_target.is_absolute() {
        raw_target
    } else {
        alias_root
            .parent()
            .unwrap_or_else(|| Path::new("/"))
            .join(raw_target)
    };
    let resolved_target = std::fs::canonicalize(&absolute_target).map_err(|e| {
        PathNormalizationError::new(
            PathNormalizationErrorKind::AliasTargetResolveFailed,
            input_path,
            e.to_string(),
            decisions,
        )
    })?;

    if resolved_target != canonical_root {
        if resolved_target.starts_with(canonical_root) {
            decisions.push(NormalizationDecision::AliasSubtreeSymlinkVerified {
                alias_root: alias_root.to_path_buf(),
                alias_target: resolved_target,
                canonical_root: canonical_root.to_path_buf(),
            });
            return Ok(None);
        }

        if let Some(canonical_input) =
            try_map_alias_directory_entry(input_path, alias_root, canonical_root, decisions)?
        {
            return Ok(Some(canonical_input));
        }

        return Err(PathNormalizationError::new(
            PathNormalizationErrorKind::AliasWrongTarget,
            input_path,
            format!(
                "expected={} actual={}",
                canonical_root.display(),
                resolved_target.display()
            ),
            decisions,
        ));
    }

    decisions.push(NormalizationDecision::AliasSymlinkVerified {
        alias_root: alias_root.to_path_buf(),
        alias_target: resolved_target,
    });
    Ok(None)
}

fn try_map_alias_directory_entry(
    input_path: &Path,
    alias_root: &Path,
    canonical_root: &Path,
    decisions: &mut Vec<NormalizationDecision>,
) -> Result<Option<PathBuf>, PathNormalizationError> {
    let relative_input = input_path.strip_prefix(alias_root).map_err(|e| {
        PathNormalizationError::new(
            PathNormalizationErrorKind::AliasNotSymlink,
            input_path,
            e.to_string(),
            decisions,
        )
    })?;
    if relative_input.components().any(|component| {
        matches!(
            component,
            std::path::Component::ParentDir
                | std::path::Component::RootDir
                | std::path::Component::Prefix(_)
        )
    }) {
        return Err(PathNormalizationError::new(
            PathNormalizationErrorKind::OutsideCanonicalRoot,
            input_path,
            "alias-relative path must stay within the alias root",
            decisions,
        ));
    }

    let canonical_input = canonical_root.join(relative_input);
    if !canonical_input.exists() {
        return Ok(None);
    }

    decisions.push(NormalizationDecision::AliasDirectoryEntryVerified {
        alias_root: alias_root.to_path_buf(),
        canonical_input: canonical_input.clone(),
    });
    Ok(Some(canonical_input))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::sync::atomic::{AtomicU64, Ordering};
    use tracing::info;

    #[cfg(unix)]
    use std::os::unix::fs::{PermissionsExt, symlink};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    struct TestFixture {
        root: PathBuf,
        canonical_root: PathBuf,
        alias_root: PathBuf,
    }

    impl TestFixture {
        fn new(prefix: &str, create_alias: bool, alias_target: Option<&Path>) -> Self {
            let id = COUNTER.fetch_add(1, Ordering::SeqCst);
            // Canonicalize the temp root (yw6mn): on macOS `/var` is a symlink
            // to `/private/var`, and `temp_dir()` returns the `/var` spelling.
            // Expected values are built by joining onto this root while the
            // code under test canonicalizes, so an un-canonicalized root makes
            // every comparison differ by a prefix that is the same directory.
            let temp_root = std::env::temp_dir();
            let temp_root = temp_root.canonicalize().unwrap_or(temp_root);
            let root = temp_root.join(format!(
                "rch-path-topology-{}-{}-{}",
                prefix,
                std::process::id(),
                id
            ));
            let canonical_root = root.join("data/projects");
            let alias_root = root.join("dp");

            fs::create_dir_all(&canonical_root).expect("create canonical root");

            #[cfg(unix)]
            if create_alias {
                let target = alias_target.unwrap_or(&canonical_root);
                symlink(target, &alias_root).expect("create alias symlink");
            }

            #[cfg(not(unix))]
            {
                let _ = create_alias;
                let _ = alias_target;
            }

            Self {
                root,
                canonical_root,
                alias_root,
            }
        }

        fn policy(&self) -> PathTopologyPolicy {
            PathTopologyPolicy::new(self.canonical_root.clone(), self.alias_root.clone())
        }
    }

    impl Drop for TestFixture {
        fn drop(&mut self) {
            let _ = fs::remove_dir_all(&self.root);
        }
    }

    fn log_normalization_error(test_name: &str, err: &PathNormalizationError) {
        info!(
            test = test_name,
            kind = ?err.kind(),
            detail = %err.detail(),
            decisions = ?err.decision_trace(),
            "topology_normalization_error"
        );
    }

    #[test]
    fn normalize_direct_canonical_path() {
        let fixture = TestFixture::new("direct", false, None);
        let project = fixture.canonical_root.join("demo");
        fs::create_dir_all(&project).expect("create project");

        let normalized = normalize_project_path_with_policy(&project, &fixture.policy())
            .expect("normalize canonical path");

        assert_eq!(
            normalized.canonical_path(),
            project.canonicalize().expect("canonicalize project")
        );
        assert!(!normalized.used_alias_prefix());
        assert!(normalized.decision_trace().len() >= 4);
    }
    #[test]
    fn identical_roots_resolve_contained_parents_and_reject_escape() {
        let fixture = TestFixture::new("identical-roots", false, None);
        let nested = fixture.canonical_root.join("repo/crates/a");
        let dependency = fixture.canonical_root.join("dep");
        let outside = fixture.root.join("data/outside");
        fs::create_dir_all(&nested).unwrap();
        fs::create_dir_all(&dependency).unwrap();
        fs::create_dir_all(&outside).unwrap();
        let policy = PathTopologyPolicy::new(
            fixture.canonical_root.clone(),
            fixture.canonical_root.clone(),
        );
        let normalized =
            normalize_project_path_with_policy(&nested.join("../../../dep"), &policy).unwrap();
        assert_eq!(normalized.canonical_path(), dependency);
        let error =
            normalize_project_path_with_policy(&nested.join("../../../../outside"), &policy)
                .unwrap_err();
        assert_eq!(
            error.kind(),
            &PathNormalizationErrorKind::OutsideCanonicalRoot
        );
    }

    #[test]
    fn identical_roots_resolve_parent_components_within_boundary() {
        let fixture = TestFixture::new("identical-roots", false, None);
        let package = fixture.canonical_root.join("repo/crates/a");
        let dependency = fixture.canonical_root.join("dep");
        fs::create_dir_all(&package).expect("create package");
        fs::create_dir_all(&dependency).expect("create dependency");
        let policy = PathTopologyPolicy::new(
            fixture.canonical_root.clone(),
            fixture.canonical_root.clone(),
        );
        let normalized = normalize_project_path_with_policy(&package.join("../../../dep"), &policy)
            .expect("resolve sibling dependency inside canonical root");
        assert_eq!(normalized.canonical_path(), dependency);
        assert!(!normalized.used_alias_prefix());

        let outside = fixture.root.join("data/outside");
        fs::create_dir_all(&outside).expect("create outside directory");
        let error =
            normalize_project_path_with_policy(&package.join("../../../../outside"), &policy)
                .expect_err("actual root escape must remain rejected");
        assert_eq!(
            error.kind(),
            &PathNormalizationErrorKind::OutsideCanonicalRoot
        );
    }

    #[cfg(unix)]
    #[test]
    fn identical_roots_reject_symlink_escape() {
        let fixture = TestFixture::new("identical-roots-symlink", false, None);
        let outside = fixture.root.join("outside");
        fs::create_dir_all(&outside).expect("create outside directory");
        let link = fixture.canonical_root.join("dep");
        symlink(&outside, &link).expect("create escaping symlink");
        let policy = PathTopologyPolicy::new(
            fixture.canonical_root.clone(),
            fixture.canonical_root.clone(),
        );
        let error = normalize_project_path_with_policy(&link, &policy)
            .expect_err("symlink must not escape equal-root policy");
        assert_eq!(
            error.kind(),
            &PathNormalizationErrorKind::OutsideCanonicalRoot
        );
    }

    #[cfg(unix)]
    #[test]
    fn normalize_alias_path_to_same_canonical_identity() {
        let fixture = TestFixture::new("alias", true, None);
        let project = fixture.canonical_root.join("repo");
        fs::create_dir_all(&project).expect("create project");
        let alias_project = fixture.alias_root.join("repo");

        let from_alias = normalize_project_path_with_policy(&alias_project, &fixture.policy())
            .expect("normalize alias project");
        let from_canonical = normalize_project_path_with_policy(&project, &fixture.policy())
            .expect("normalize canonical project");

        assert!(from_alias.used_alias_prefix());
        assert_eq!(from_alias.canonical_path(), from_canonical.canonical_path());
        assert!(
            from_alias
                .decision_trace()
                .iter()
                .any(|d| matches!(d, NormalizationDecision::AliasSymlinkVerified { .. }))
        );
    }

    #[test]
    fn reject_relative_path_input() {
        let fixture = TestFixture::new("relative", false, None);
        let err = normalize_project_path_with_policy(Path::new("relative/repo"), &fixture.policy())
            .expect_err("relative path must fail");
        assert_eq!(err.kind(), &PathNormalizationErrorKind::NotAbsoluteInput);
    }

    #[test]
    fn reject_path_outside_canonical_root() {
        let fixture = TestFixture::new("outside", false, None);
        let outside = fixture.root.join("outside");
        fs::create_dir_all(&outside).expect("create outside path");

        let err = normalize_project_path_with_policy(&outside, &fixture.policy())
            .expect_err("outside root must fail");
        log_normalization_error("reject_path_outside_canonical_root", &err);
        assert_eq!(
            err.kind(),
            &PathNormalizationErrorKind::OutsideCanonicalRoot
        );
        assert!(
            err.decision_trace()
                .iter()
                .any(|d| matches!(d, NormalizationDecision::CanonicalInputResolved(_)))
        );
    }

    #[cfg(unix)]
    #[test]
    fn reject_missing_alias_for_alias_prefixed_input() {
        let fixture = TestFixture::new("missing-alias", false, None);
        let input = fixture.alias_root.join("repo");
        let err = normalize_project_path_with_policy(&input, &fixture.policy())
            .expect_err("missing alias must fail");
        log_normalization_error("reject_missing_alias_for_alias_prefixed_input", &err);
        assert_eq!(err.kind(), &PathNormalizationErrorKind::AliasMissing);
    }

    #[cfg(unix)]
    #[test]
    fn reject_alias_pointing_to_wrong_target() {
        let fixture = TestFixture::new("wrong-target", false, None);
        let other_target = fixture.root.join("other-projects");
        fs::create_dir_all(&other_target).expect("create alternate target");
        symlink(&other_target, &fixture.alias_root).expect("create wrong alias");
        let alias_input = fixture.alias_root.join("repo");
        fs::create_dir_all(&alias_input).expect("create alias repo path");

        let err = normalize_project_path_with_policy(&alias_input, &fixture.policy())
            .expect_err("alias wrong target must fail");
        log_normalization_error("reject_alias_pointing_to_wrong_target", &err);
        assert_eq!(err.kind(), &PathNormalizationErrorKind::AliasWrongTarget);
    }

    #[cfg(unix)]
    #[test]
    fn reject_alias_path_that_is_not_symlink() {
        let fixture = TestFixture::new("alias-not-symlink", false, None);
        fs::create_dir_all(&fixture.alias_root).expect("create alias directory");
        let alias_input = fixture.alias_root.join("repo");
        fs::create_dir_all(&alias_input).expect("create alias repo path");

        let err = normalize_project_path_with_policy(&alias_input, &fixture.policy())
            .expect_err("non-symlink alias must fail");
        log_normalization_error("reject_alias_path_that_is_not_symlink", &err);
        assert_eq!(err.kind(), &PathNormalizationErrorKind::AliasNotSymlink);
        assert!(err.detail().contains("not a symlink"));
    }

    #[cfg(unix)]
    #[test]
    fn normalize_alias_directory_with_symlinked_repo_entry() {
        let fixture = TestFixture::new("alias-dir-entry", false, None);
        let user_root = fixture.root.join("users/jemanuel");
        let canonical_projects = user_root.join("projects");
        let canonical_project = canonical_projects.join("repo");
        let alias_projects = fixture.root.join("data/projects");
        let alias_input = alias_projects.join("repo");

        fs::create_dir_all(&canonical_project).expect("create canonical project");
        fs::create_dir_all(&alias_projects).expect("create alias directory");
        symlink(&canonical_project, &alias_input).expect("create per-repo alias symlink");

        let policy = PathTopologyPolicy::new(canonical_projects, alias_projects.clone());
        let normalized = normalize_project_path_with_policy(&alias_input, &policy)
            .expect("normalize per-repo alias entry");

        assert!(normalized.used_alias_prefix());
        assert_eq!(
            normalized.canonical_path(),
            canonical_project
                .canonicalize()
                .expect("canonicalize canonical project")
        );
        assert!(normalized.decision_trace().iter().any(|decision| {
            matches!(
                decision,
                NormalizationDecision::AliasDirectoryEntryVerified { .. }
            )
        }));
    }

    #[cfg(unix)]
    #[test]
    fn normalize_alias_directory_entry_to_canonical_symlink_namespace() {
        let fixture = TestFixture::new("alias-dir-entry-canonical-symlink", false, None);
        let user_root = fixture.root.join("users/jemanuel");
        let canonical_projects = user_root.join("projects");
        let outside_projects = user_root.join("dp");
        let outside_project = outside_projects.join("asupersync");
        let canonical_project = canonical_projects.join("asupersync");
        let alias_projects = fixture.root.join("data/projects");
        let alias_input = alias_projects.join("asupersync");

        fs::create_dir_all(&outside_project).expect("create outside project target");
        fs::create_dir_all(&canonical_projects).expect("create canonical projects directory");
        fs::create_dir_all(&alias_projects).expect("create alias directory");
        symlink(&outside_project, &canonical_project).expect("create canonical repo symlink");
        symlink(&canonical_project, &alias_input).expect("create per-repo alias symlink");

        let policy = PathTopologyPolicy::new(canonical_projects, alias_projects);
        let normalized = normalize_project_path_with_policy(&alias_input, &policy)
            .expect("normalize alias entry to canonical namespace");

        assert!(normalized.used_alias_prefix());
        assert_eq!(normalized.canonical_path(), canonical_project);
        assert_ne!(
            normalized.canonical_path(),
            outside_project
                .canonicalize()
                .expect("canonicalize outside project")
        );
        assert!(normalized.decision_trace().iter().any(|decision| {
            matches!(
                decision,
                NormalizationDecision::AliasDirectoryEntryVerified { .. }
            )
        }));
    }

    #[cfg(unix)]
    #[test]
    fn reject_alias_directory_entry_parent_component_escape() {
        let fixture = TestFixture::new("alias-dir-entry-parent", false, None);
        let project = fixture.canonical_root.join("repo");
        let alias_input = fixture.alias_root.join("../projects/repo");

        fs::create_dir_all(&project).expect("create canonical project");
        fs::create_dir_all(&fixture.alias_root).expect("create alias directory");

        let err = normalize_project_path_with_policy(&alias_input, &fixture.policy())
            .expect_err("parent components must not map through alias directory fallback");
        log_normalization_error("reject_alias_directory_entry_parent_component_escape", &err);
        assert_eq!(
            err.kind(),
            &PathNormalizationErrorKind::OutsideCanonicalRoot
        );
    }

    #[cfg(unix)]
    #[test]
    fn normalize_symlink_alias_entry_to_canonical_subtree() {
        let fixture = TestFixture::new("alias-symlink-entry-canonical-subtree", false, None);
        let user_root = fixture.root.join("users/jemanuel");
        let canonical_root = user_root.clone();
        let canonical_project = canonical_root.join("projects/repo");
        let alias_target = fixture.root.join("volumes/data");
        let alias_root = fixture.root.join("alias-data");
        let alias_input = alias_root.join("projects/repo");

        fs::create_dir_all(&canonical_project).expect("create canonical project");
        fs::create_dir_all(&alias_target).expect("create alias target directory");
        symlink(&alias_target, &alias_root).expect("create /data-style alias symlink");

        let policy = PathTopologyPolicy::new(canonical_root, alias_root);
        let normalized = normalize_project_path_with_policy(&alias_input, &policy)
            .expect("normalize /data/projects entry into canonical user subtree");

        assert!(normalized.used_alias_prefix());
        assert_eq!(
            normalized.canonical_path(),
            canonical_project
                .canonicalize()
                .expect("canonicalize canonical project")
        );
        assert!(normalized.decision_trace().iter().any(|decision| {
            matches!(
                decision,
                NormalizationDecision::AliasDirectoryEntryVerified { .. }
            )
        }));
    }

    #[cfg(unix)]
    #[test]
    fn normalize_alias_symlink_target_inside_canonical_root() {
        let fixture = TestFixture::new("alias-subtree-target", false, None);
        let user_root = fixture.root.join("users/jemanuel");
        let alias_target = user_root.join("dp");
        let alias_root = fixture.root.join("dp");
        let alias_project = alias_root.join("frankentui");
        let canonical_project = alias_target.join("frankentui");

        fs::create_dir_all(&canonical_project).expect("create canonical subtree project");
        symlink(&alias_target, &alias_root).expect("create /dp-style subtree alias");

        let policy = PathTopologyPolicy::new(user_root.clone(), alias_root);
        let normalized = normalize_project_path_with_policy(&alias_project, &policy)
            .expect("normalize alias rooted at canonical subtree");

        assert!(normalized.used_alias_prefix());
        assert_eq!(
            normalized.canonical_path(),
            canonical_project
                .canonicalize()
                .expect("canonicalize subtree project")
        );
        assert_eq!(
            normalized.canonical_root(),
            user_root.canonicalize().expect("canonicalize user root")
        );
        assert!(normalized.decision_trace().iter().any(|decision| {
            matches!(
                decision,
                NormalizationDecision::AliasSubtreeSymlinkVerified { .. }
            )
        }));
    }

    #[cfg(unix)]
    #[test]
    fn reject_alias_symlink_loop() {
        let fixture = TestFixture::new("alias-loop", false, None);
        symlink("dp", &fixture.alias_root).expect("create alias symlink loop");
        let alias_input = fixture.alias_root.join("repo");

        let err = normalize_project_path_with_policy(&alias_input, &fixture.policy())
            .expect_err("alias loop must fail");
        log_normalization_error("reject_alias_symlink_loop", &err);
        assert_eq!(
            err.kind(),
            &PathNormalizationErrorKind::AliasTargetResolveFailed
        );
        assert!(
            err.decision_trace()
                .iter()
                .any(|decision| matches!(decision, NormalizationDecision::AliasPrefixDetected(_)))
        );
    }

    #[cfg(unix)]
    #[test]
    fn reject_permission_denied_during_canonical_resolution() {
        let fixture = TestFixture::new("permission-denied", false, None);
        let project = fixture.canonical_root.join("repo");
        fs::create_dir_all(&project).expect("create project path");

        let original_permissions = fs::metadata(&fixture.canonical_root)
            .expect("read canonical root metadata")
            .permissions();
        let mut denied_permissions = original_permissions.clone();
        denied_permissions.set_mode(0o000);
        fs::set_permissions(&fixture.canonical_root, denied_permissions)
            .expect("lock canonical root permissions");

        let result = normalize_project_path_with_policy(&project, &fixture.policy());

        fs::set_permissions(&fixture.canonical_root, original_permissions)
            .expect("restore canonical root permissions");

        let err = match result {
            Ok(_) => {
                // Root users can bypass mode bits; treat as a non-actionable skip.
                return;
            }
            Err(err) => err,
        };
        log_normalization_error("reject_permission_denied_during_canonical_resolution", &err);
        assert!(matches!(
            err.kind(),
            PathNormalizationErrorKind::CanonicalRootResolveFailed
                | PathNormalizationErrorKind::InputResolveFailed
        ));
    }

    #[test]
    fn reject_when_canonical_root_missing() {
        let fixture = TestFixture::new("missing-root", false, None);
        let missing_root = fixture.root.join("does-not-exist");
        let policy = PathTopologyPolicy::new(missing_root.clone(), fixture.alias_root.clone());
        let outside = fixture.root.join("somewhere");
        fs::create_dir_all(&outside).expect("create input");

        let err = normalize_project_path_with_policy(&outside, &policy)
            .expect_err("missing canonical root must fail");
        log_normalization_error("reject_when_canonical_root_missing", &err);
        assert_eq!(
            err.kind(),
            &PathNormalizationErrorKind::CanonicalRootMissing
        );
        assert!(
            err.detail()
                .contains(missing_root.to_string_lossy().as_ref())
        );
    }

    /// Regression test for GitHub #9: when a custom canonical root is
    /// configured and does not exist (and there is no alias symlink to
    /// fall back through), the error must reference the *configured*
    /// root — not the compiled-in `/data/projects` default.
    #[test]
    fn canonical_root_missing_error_cites_configured_root_not_default() {
        let fixture = TestFixture::new("missing-custom-root", false, None);
        let missing_root = fixture.root.join("custom-missing-root");
        let missing_alias = fixture.root.join("custom-missing-alias");
        let policy = PathTopologyPolicy::new(missing_root.clone(), missing_alias);

        // Any absolute path we attempt to normalize under this policy must
        // fail with a message that names the configured canonical root.
        let probe = fixture.root.join("some-project");
        let err = normalize_project_path_with_policy(&probe, &policy)
            .expect_err("normalization must fail when canonical root is missing");

        assert!(
            matches!(err.kind(), PathNormalizationErrorKind::CanonicalRootMissing),
            "expected CanonicalRootMissing, got {:?}",
            err.kind()
        );
        let rendered = err.to_string();
        assert!(
            rendered.contains(&missing_root.display().to_string()),
            "error should mention configured canonical root {}: {}",
            missing_root.display(),
            rendered
        );
        // The fixture itself may live under the default root (e.g. a
        // checkout at /data/projects/...), so a bare substring check
        // would false-fire on the legitimate fixture paths carried by
        // the rendered input/detail. Strip them first; any leftover
        // citation of the compiled-in default is a real leak.
        let stripped = rendered.replace(fixture.root.to_string_lossy().as_ref(), "");
        assert!(
            !stripped.contains(DEFAULT_CANONICAL_PROJECT_ROOT),
            "error must not leak default {} when a custom canonical_root \
             is configured. got: {}",
            DEFAULT_CANONICAL_PROJECT_ROOT,
            rendered
        );
    }

    #[cfg(unix)]
    #[test]
    fn normalize_direct_path_via_alias_target_when_canonical_root_missing() {
        let fixture = TestFixture::new("alias-target-root", true, None);
        let missing_root = fixture.root.join("does-not-exist");
        let policy = PathTopologyPolicy::new(missing_root, fixture.alias_root.clone());
        let project = fixture.canonical_root.join("repo");
        fs::create_dir_all(&project).expect("create project");

        let normalized = normalize_project_path_with_policy(&project, &policy)
            .expect("normalize path using alias target fallback");

        assert_eq!(
            normalized.canonical_root(),
            fixture
                .canonical_root
                .canonicalize()
                .expect("canonicalize alias target root")
        );
        assert_eq!(
            normalized.canonical_path(),
            project.canonicalize().expect("canonicalize project")
        );
        assert!(!normalized.used_alias_prefix());
    }
}