Skip to main content

capsid_protocol/
path.rs

1pub const MAX_BYTES: usize = 4096;
2
3pub const MAX_COMPONENT_BYTES: usize = 255;
4
5pub fn is_absolute(path: &[u8]) -> bool {
6    path.starts_with(b"/") && path.len() <= MAX_BYTES && !path.contains(&0)
7}
8
9// One name within a directory: never empty, `.`, or `..`, and free of `/` and
10// NUL bytes.
11pub fn is_component(name: &[u8]) -> bool {
12    !name.is_empty()
13        && name.len() <= MAX_COMPONENT_BYTES
14        && !name.contains(&0)
15        && !name.contains(&b'/')
16        && !matches!(name, b"." | b"..")
17}
18
19// A guest path the host may mount or publish onto: absolute, below the root,
20// made of normal components without control characters, and outside every
21// reserved tree.
22pub fn is_guest_target(target: &str, reserved: &[&str]) -> bool {
23    let Some(relative) = target.strip_prefix('/') else {
24        return false;
25    };
26    is_absolute(target.as_bytes())
27        && !relative.is_empty()
28        && relative
29            .split('/')
30            .all(|component| is_component(component.as_bytes()))
31        && !target.chars().any(char::is_control)
32        && !reserved.iter().any(|reserved| overlap(reserved, target))
33}
34
35pub fn overlap(left: &str, right: &str) -> bool {
36    left == right
37        || left
38            .strip_prefix(right)
39            .is_some_and(|suffix| suffix.starts_with('/'))
40        || right
41            .strip_prefix(left)
42            .is_some_and(|suffix| suffix.starts_with('/'))
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_an_absolute_path_is_bounded_and_free_of_nul_bytes() {
51        assert!(is_absolute(b"/srv/data"));
52        assert!(!is_absolute(b"srv/data"));
53        assert!(!is_absolute(b"/srv\0data"));
54        assert!(is_absolute(&[b'/'; MAX_BYTES]));
55        assert!(!is_absolute(&[b'/'; MAX_BYTES + 1]));
56    }
57
58    #[test]
59    fn test_guest_targets_reject_reserved_trees_traversal_and_the_root() {
60        let reserved = ["/proc", "/run/capsid"];
61        for target in [
62            "/",
63            "relative",
64            "/proc/x",
65            "/run",
66            "/run/capsid/x",
67            "/a/../b",
68            "/a/./b",
69            "/a//b",
70            "/a/\u{7}",
71        ] {
72            assert!(!is_guest_target(target, &reserved), "{target}");
73        }
74        assert!(is_guest_target("/run/other", &reserved));
75        assert!(!is_guest_target(
76            &format!("/{}", "a".repeat(MAX_COMPONENT_BYTES + 1)),
77            &reserved
78        ));
79    }
80
81    #[test]
82    fn test_paths_overlap_only_at_component_boundaries() {
83        assert!(overlap("/data", "/data"));
84        assert!(overlap("/data", "/data/cache"));
85        assert!(overlap("/data/cache", "/data"));
86        assert!(!overlap("/data", "/database"));
87        assert!(!overlap("/data/a", "/data/b"));
88    }
89}