vtcode_commons/paths/
safety.rs1use anyhow::{Result, bail};
2use std::path::{Component, Path, PathBuf};
3
4pub fn is_safe_relative_path(path: &str) -> bool {
6 let path = path.trim();
7 if path.is_empty() {
8 return false;
9 }
10
11 if path.split(['/', '\\']).any(|component| component == "..") {
14 return false;
15 }
16
17 if path.starts_with(['/', '\\']) || (cfg!(windows) && path.contains(':')) {
21 return false;
22 }
23
24 true
25}
26
27pub fn validate_path_safety(path: &str) -> Result<()> {
32 if path.is_empty() {
34 return Ok(());
35 }
36
37 if path.contains("..") {
40 bail!("Path traversal attempt detected ('..')");
41 }
42
43 if path.contains("~/../") || path.contains("/.../") {
45 bail!("Advanced path traversal detected");
46 }
47
48 if path.starts_with('/') {
50 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 #[cfg(windows)]
69 {
70 if is_windows_critical_path(path) {
71 bail!("Access to Windows system directory denied");
72 }
73 }
74
75 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
91fn 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 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
120pub 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 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}