Skip to main content

strands/vended_tools/
paths.rs

1//! Path validation shared by the sandbox-routed file tools.
2
3use crate::error::{Error, Result};
4
5/// Whether `path` starts with a Windows drive letter (`C:\`, `C:/`) or a UNC share (`\\server`).
6fn is_windows_absolute(path: &str) -> bool {
7    let bytes = path.as_bytes();
8    if path.starts_with("\\\\") {
9        return true;
10    }
11    bytes.len() >= 3 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' && matches!(bytes[2], b'\\' | b'/')
12}
13
14/// Rejects a path that is not absolute (POSIX, or a Windows drive letter or UNC share) or that
15/// has a `..` segment. Both `/` and `\` separate segments, so a
16/// backslash cannot hide a traversal.
17///
18/// ```
19/// use strands::vended_tools::paths::validate_absolute_path;
20///
21/// assert!(validate_absolute_path("/tmp/notes.txt").is_ok());
22/// assert!(validate_absolute_path("notes.txt").is_err());
23/// assert!(validate_absolute_path("/tmp/../etc/passwd").is_err());
24/// ```
25///
26/// # Errors
27///
28/// When the path is relative, or contains a `..` segment.
29pub fn validate_absolute_path(path: &str) -> Result<()> {
30    if !(path.starts_with('/') || is_windows_absolute(path)) {
31        return Err(Error::other(format!(
32            "The path {path} is not absolute; it should start with '/' (or a drive letter or UNC share on Windows)."
33        )));
34    }
35    if path.split(['/', '\\']).any(|segment| segment == "..") {
36        return Err(Error::other("Invalid path: path traversal is not allowed."));
37    }
38    Ok(())
39}
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44
45    fn message(path: &str) -> String {
46        validate_absolute_path(path).unwrap_err().to_string()
47    }
48
49    #[test]
50    fn accepts_a_posix_absolute_path() {
51        validate_absolute_path("/tmp/file.txt").unwrap();
52    }
53
54    #[test]
55    fn accepts_a_windows_drive_letter_absolute_path() {
56        validate_absolute_path("C:\\project\\file.txt").unwrap();
57        validate_absolute_path("c:/project/file.txt").unwrap();
58    }
59
60    #[test]
61    fn accepts_a_unc_share() {
62        validate_absolute_path("\\\\server\\share\\file.txt").unwrap();
63    }
64
65    #[test]
66    fn rejects_a_relative_path() {
67        assert!(message("relative.txt").contains("not absolute"));
68        assert!(message("C:relative.txt").contains("not absolute"));
69    }
70
71    #[test]
72    fn rejects_posix_parent_traversal() {
73        assert!(message("/tmp/../etc/passwd").contains("path traversal is not allowed"));
74    }
75
76    #[test]
77    fn rejects_windows_parent_traversal() {
78        assert!(message("C:\\project\\..\\etc\\hosts").contains("path traversal is not allowed"));
79    }
80
81    #[test]
82    fn accepts_a_double_dot_substring_inside_a_segment() {
83        validate_absolute_path("/tmp/file..name.txt").unwrap();
84    }
85}