Skip to main content

tokenectomy_git/
safety.rs

1// safety.rs — Path validation for tokenectomy-git
2//
3// Ensures file operations are restricted to the current working directory.
4// Prevents path traversal attacks via symlinks or ../.. patterns.
5
6/// Validates that a file path resolves to a location within the current working directory.
7/// Rejects paths that:
8/// - Are outside the CWD after canonicalization
9/// - Don't exist (prevents traversal via non-existent intermediate paths)
10pub fn is_path_safe(file_path: &str) -> bool {
11    if let Ok(current_dir) = std::env::current_dir() {
12        let current_dir = current_dir.canonicalize().unwrap_or(current_dir);
13        let path = std::path::Path::new(file_path);
14        let abs_path = if path.is_absolute() {
15            path.to_path_buf()
16        } else {
17            current_dir.join(path)
18        };
19        // Canonicalize to resolve symlinks
20        if let Ok(resolved) = abs_path.canonicalize() {
21            resolved.starts_with(&current_dir)
22        } else {
23            false // File doesn't exist = reject
24        }
25    } else {
26        false
27    }
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn test_path_outside_cwd_rejected() {
36        assert!(!is_path_safe("/etc/passwd"));
37        assert!(!is_path_safe("../../etc/passwd"));
38    }
39
40    #[test]
41    fn test_nonexistent_file_rejected() {
42        assert!(!is_path_safe("nonexistent_file_that_does_not_exist_xyz.rs"));
43    }
44}