Skip to main content

hyperframes/core/
safe_path.rs

1use std::path::{Path, PathBuf};
2
3/// Reject paths that escape the `base` directory, including via symlinks.
4///
5/// Ported from `@hyperframes/core/src/safePath.ts`.
6pub fn is_safe_path(base: impl AsRef<Path>, target: impl AsRef<Path>) -> bool {
7    let base_path = base.as_ref();
8    let target_path = target.as_ref();
9
10    let Ok(base_canonical) = std::fs::canonicalize(base_path) else {
11        return false;
12    };
13
14    let resolved_target = if target_path.is_absolute() {
15        target_path.to_path_buf()
16    } else {
17        base_canonical.join(target_path)
18    };
19
20    // If target exists, canonicalize directly
21    if let Ok(target_canonical) = std::fs::canonicalize(&resolved_target) {
22        return target_canonical.starts_with(&base_canonical);
23    }
24
25    // Target does not exist yet (e.g. pending write target).
26    // Walk ancestors to find the deepest existing ancestor and verify containment.
27    let mut probe = resolved_target.clone();
28    let mut trailing = Vec::new();
29
30    loop {
31        if let Ok(ancestor_canonical) = std::fs::canonicalize(&probe) {
32            // Reconstruct projected target
33            let mut final_path = ancestor_canonical;
34            for seg in trailing.iter().rev() {
35                final_path.push(seg);
36            }
37            return final_path.starts_with(&base_canonical);
38        }
39
40        match probe.file_name() {
41            Some(name) => {
42                trailing.push(name.to_os_string());
43                if !probe.pop() {
44                    return false;
45                }
46            }
47            None => return false,
48        }
49    }
50}
51
52/// Resolve `relative_path` against `base` and return absolute PathBuf only if safe.
53pub fn resolve_within_project(
54    base: impl AsRef<Path>,
55    relative_path: impl AsRef<Path>,
56) -> Option<PathBuf> {
57    let base_path = base.as_ref();
58    let target = base_path.join(relative_path);
59    if is_safe_path(base_path, &target) {
60        Some(target)
61    } else {
62        None
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use tempfile::tempdir;
70
71    #[test]
72    fn test_allows_base_directory() {
73        let dir = tempdir().unwrap();
74        assert!(is_safe_path(dir.path(), dir.path()));
75    }
76
77    #[test]
78    fn test_allows_nested_existing_path() {
79        let dir = tempdir().unwrap();
80        let sub = dir.path().join("assets");
81        std::fs::create_dir(&sub).unwrap();
82        let file = sub.join("logo.png");
83        std::fs::write(&file, b"test").unwrap();
84        assert!(is_safe_path(dir.path(), &file));
85    }
86
87    #[test]
88    fn test_allows_not_yet_existing_target() {
89        let dir = tempdir().unwrap();
90        let target = dir.path().join("new").join("deep").join("file.txt");
91        assert!(is_safe_path(dir.path(), &target));
92    }
93
94    #[test]
95    fn test_rejects_parent_traversal() {
96        let dir = tempdir().unwrap();
97        let target = dir.path().join("..").join("..").join("etc").join("passwd");
98        assert!(!is_safe_path(dir.path(), &target));
99    }
100
101    #[cfg(unix)]
102    #[test]
103    fn test_rejects_symlink_escape() {
104        use std::os::unix::fs::symlink;
105
106        let base = tempdir().unwrap();
107        let external = tempdir().unwrap();
108        let secret = external.path().join("secret.txt");
109        std::fs::write(&secret, b"secret").unwrap();
110
111        let link = base.path().join("link");
112        if symlink(external.path(), &link).is_ok() {
113            assert!(!is_safe_path(base.path(), link.join("secret.txt")));
114        }
115    }
116}