Skip to main content

vtcode_commons/paths/
safety.rs

1use anyhow::{Result, bail};
2use std::path::{Component, Path, PathBuf};
3
4/// Check if a path string is a safe relative path (no traversal, no absolute).
5pub fn is_safe_relative_path(path: &str) -> bool {
6    let path = path.trim();
7    if path.is_empty() {
8        return false;
9    }
10
11    // Reject traversal only when `..` is a whole component. A substring check
12    // would drop legal names such as `v1..2.txt` on Unix/macOS.
13    if path.split(['/', '\\']).any(|component| component == "..") {
14        return false;
15    }
16
17    // Both separators are treated as rooted on every host (defense in depth).
18    // ':' only denotes a drive or alternate data stream on Windows; on Unix it
19    // is an ordinary filename character (`@notes:Q1.txt`).
20    if path.starts_with(['/', '\\']) || (cfg!(windows) && path.contains(':')) {
21        return false;
22    }
23
24    true
25}
26
27/// Validates that a path is safe to use.
28/// Preventing traversal, absolute system paths, and dangerous characters.
29///
30/// Optimization: Uses early returns and byte-level checks for common patterns
31pub fn validate_path_safety(path: &str) -> Result<()> {
32    // Optimization: Fast path for empty or very short paths
33    if path.is_empty() {
34        return Ok(());
35    }
36
37    // Reject path traversal attempts
38    // Optimization: Use contains on bytes for simple patterns
39    if path.contains("..") {
40        bail!("Path traversal attempt detected ('..')");
41    }
42
43    // Additional traversal patterns
44    if path.contains("~/../") || path.contains("/.../") {
45        bail!("Advanced path traversal detected");
46    }
47
48    // Optimization: Only check Unix critical paths if path starts with '/'
49    if path.starts_with('/') {
50        // Reject absolute paths outside workspace
51        // Note: We can't strictly block all absolute paths as the agent might need to access
52        // explicitly allowed directories, but we can block obvious system critical paths.
53        static UNIX_CRITICAL: &[&str] = &["/etc", "/usr", "/bin", "/sbin", "/var", "/boot", "/root", "/dev"];
54        for prefix in UNIX_CRITICAL {
55            let is_var_temp_exception = *prefix == "/var"
56                && (path.starts_with("/var/folders/")
57                    || path == "/var/folders"
58                    || path.starts_with("/var/tmp/")
59                    || path == "/var/tmp");
60
61            if !is_var_temp_exception && matches_critical_prefix(path, prefix) {
62                bail!("Access to system directory denied: {prefix}");
63            }
64        }
65    }
66
67    // Windows critical paths
68    #[cfg(windows)]
69    {
70        if is_windows_critical_path(path) {
71            bail!("Access to Windows system directory denied");
72        }
73    }
74
75    // Reject dangerous shell characters in paths (including null byte)
76    // Optimization: Check bytes directly for faster character detection
77    static DANGEROUS_CHARS: &[u8] = b"$`|;&\n\r><\0";
78    for &c in path.as_bytes() {
79        if DANGEROUS_CHARS.contains(&c) {
80            bail!("Path contains dangerous shell characters");
81        }
82    }
83
84    Ok(())
85}
86
87fn matches_critical_prefix(path: &str, prefix: &str) -> bool {
88    path == prefix || path.strip_prefix(prefix).is_some_and(|rest| rest.starts_with('/'))
89}
90
91/// Whether a Windows path points into a critical system directory.
92///
93/// Windows accepts `/` as a separator and these directories exist on every
94/// drive, so compare normalized, drive-prefix-stripped components rather than
95/// a hardcoded `c:\...` string prefix. Kept platform-agnostic so the logic can
96/// be regression-tested on any host.
97fn is_windows_critical_path(path: &str) -> bool {
98    let normalized = path.replace('/', "\\").to_lowercase();
99    let without_extended = normalized.strip_prefix("\\\\?\\").unwrap_or(&normalized);
100    let mut chars = without_extended.chars();
101    let after_drive = match (chars.next(), chars.next()) {
102        (Some(drive), Some(':')) if drive.is_ascii_lowercase() => chars.as_str(),
103        _ => without_extended,
104    };
105    let relative = after_drive.trim_start_matches('\\');
106    // `windows.old` holds a previous system installation (registry hives,
107    // system binaries); the old `c:\windows` string prefix covered it too.
108    const CRITICAL: &[&str] = &[
109        "windows",
110        "windows.old",
111        "program files",
112        "program files (x86)",
113        "system32",
114    ];
115    CRITICAL
116        .iter()
117        .any(|name| relative == *name || relative.strip_prefix(name).is_some_and(|rest| rest.starts_with('\\')))
118}
119
120/// Validate an archive entry name and return it as a destination-relative path.
121///
122/// Lexical only (no filesystem access): rejects absolute paths, Windows
123/// prefixes, and parent components (`..`), and collapses `.` components.
124/// Unlike a substring check for `..`, legitimate names such as
125/// `v1..2/README.md` are accepted. An empty result means the name resolves to
126/// the extraction destination itself (e.g. `.`); callers decide whether to
127/// skip or reject that.
128///
129/// # Errors
130///
131/// Returns an error when the name contains a component that would escape the
132/// extraction destination.
133pub fn safe_archive_relative_path(name: &Path) -> Result<PathBuf> {
134    let mut safe = PathBuf::new();
135    for component in name.components() {
136        match component {
137            Component::Normal(part) => safe.push(part),
138            Component::CurDir => {}
139            Component::ParentDir => {
140                bail!("unsafe archive path ('..' escapes destination): {}", name.display());
141            }
142            Component::RootDir | Component::Prefix(_) => {
143                bail!("unsafe archive path (absolute): {}", name.display());
144            }
145        }
146    }
147    Ok(safe)
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn safe_relative_path_rejects_rooted_windows_paths() {
156        assert!(!is_safe_relative_path(r"\Windows\secret.txt"));
157        assert!(!is_safe_relative_path(r"\\server\share\file.txt"));
158        assert!(!is_safe_relative_path("/etc/passwd"));
159        assert!(is_safe_relative_path(r"src\main.rs"));
160        assert!(is_safe_relative_path("src/main.rs"));
161    }
162
163    #[test]
164    fn accepts_nested_relative_names() {
165        assert_eq!(safe_archive_relative_path(Path::new("a/b/c.txt")).expect("safe"), PathBuf::from("a/b/c.txt"));
166    }
167
168    #[test]
169    fn unix_filenames_may_contain_colons_and_double_dots() {
170        if cfg!(windows) {
171            return;
172        }
173        assert!(is_safe_relative_path("@notes:Q1.txt"));
174        assert!(is_safe_relative_path("v1..2.txt"));
175        assert!(!is_safe_relative_path("a/../secret.txt"));
176        assert!(!is_safe_relative_path("a\\..\\secret.txt"));
177    }
178
179    #[test]
180    fn windows_critical_paths_normalize_separators_and_drives() {
181        for path in [
182            "C:/Windows/System32/drivers/etc/hosts",
183            "c:\\windows\\system32\\drivers\\etc\\hosts",
184            "D:\\Windows\\System32\\foo",
185            "C:/Windows.old/Windows/System32/config/SAM",
186            "\\\\?\\C:\\Windows\\foo",
187            "C:/Program Files/Tools/tool.exe",
188            "C:/Program Files (x86)/Tools/tool.exe",
189            "c:/system32/config/SAM",
190        ] {
191            assert!(is_windows_critical_path(path), "must be critical: {path}");
192        }
193        for path in [
194            "C:/Users/me/Documents/windows-notes.txt",
195            "C:/projects/myapp/src/main.rs",
196            "D:/data/windows_backup.tar",
197        ] {
198            assert!(!is_windows_critical_path(path), "must not be critical: {path}");
199        }
200    }
201
202    #[test]
203    fn collapses_current_dir_components() {
204        assert_eq!(
205            safe_archive_relative_path(Path::new("./nested/./file.txt")).expect("safe"),
206            PathBuf::from("nested/file.txt")
207        );
208    }
209
210    #[test]
211    fn accepts_dot_dot_inside_a_single_component() {
212        // Substring `..` checks reject this legitimate name; component
213        // analysis must accept it.
214        assert_eq!(
215            safe_archive_relative_path(Path::new("v1..2/README.md")).expect("safe"),
216            PathBuf::from("v1..2/README.md")
217        );
218    }
219
220    #[test]
221    fn rejects_parent_components() {
222        let err = safe_archive_relative_path(Path::new("../../etc/passwd")).expect_err("traversal");
223        assert!(err.to_string().contains("unsafe archive path"), "unexpected error: {err}");
224    }
225
226    #[test]
227    fn rejects_absolute_names() {
228        let err = safe_archive_relative_path(Path::new("/abs.txt")).expect_err("absolute");
229        assert!(err.to_string().contains("unsafe archive path"), "unexpected error: {err}");
230    }
231
232    #[test]
233    fn resolves_bare_current_dir_to_empty() {
234        assert!(safe_archive_relative_path(Path::new(".")).expect("safe").as_os_str().is_empty());
235    }
236
237    #[cfg(windows)]
238    #[test]
239    fn rejects_windows_prefixes() {
240        let err = safe_archive_relative_path(Path::new("C:\\evil.txt")).expect_err("prefix");
241        assert!(err.to_string().contains("unsafe archive path"), "unexpected error: {err}");
242    }
243}