Skip to main content

holger_traits/
safe_path.rs

1//! **One rule for a path a request names** (R1 follow-up, the taint lens): every place that
2//! joins a string the other end sent (an artifact coordinate, a material name, a bundle
3//! member, an estate file, a repository name) under a directory of this box goes through
4//! this module, so the rule lives once and a path can never climb out of its root.
5//!
6//! Two shapes, both the whole rule:
7//! * [`sanitize_segment`] / [`sanitize_under`] REFUSE: the string is used as it is or not at
8//!   all (an estate file, a raw artifact path, a job input name);
9//! * [`segment_of`] / [`segment_of_coord`] FOLD: the string is mapped to one safe segment
10//!   (`/`, `\`, NUL and every other byte outside `[A-Za-z0-9._-]` becomes `_`; `.` and `..`
11//!   and the empty string become `_`), for a key that only has to be stable and unique
12//!   enough (a material file, a sync ack, a coordinate's ref).
13//!
14//! The names carry `sanitize` on purpose: the taint lens counts a call whose callee matches
15//! `sanitiz` as a sanitizer, so a join of request data behind this module is a clean one and
16//! a join without it is the finding.
17
18use std::path::{Component, Path, PathBuf};
19
20/// Why a string is not a path segment, or not a relative path, under a root of this box.
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct UnsafePath {
23    pub given: String,
24    pub why: &'static str,
25}
26
27impl std::fmt::Display for UnsafePath {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        write!(f, "{:?} is not a safe path: {}", self.given, self.why)
30    }
31}
32
33impl std::error::Error for UnsafePath {}
34
35/// The longest single segment this box files under a name (a file system's 255 bytes).
36pub const MAX_SEGMENT: usize = 255;
37
38fn refuse(given: &str, why: &'static str) -> UnsafePath {
39    UnsafePath {
40        given: given.to_string(),
41        why,
42    }
43}
44
45/// **One path segment, as given or refused**: not empty, at most [`MAX_SEGMENT`] bytes, no
46/// `/`, `\` or NUL, not `.` and not `..`.
47pub fn sanitize_segment(s: &str) -> Result<&str, UnsafePath> {
48    if s.is_empty() {
49        return Err(refuse(s, "empty"));
50    }
51    if s.len() > MAX_SEGMENT {
52        return Err(refuse(s, "longer than one file name"));
53    }
54    if s == "." || s == ".." {
55        return Err(refuse(s, "`.` and `..` name no file"));
56    }
57    if s.bytes().any(|b| b == b'/' || b == b'\\' || b == 0) {
58        return Err(refuse(s, "a separator or a NUL inside one segment"));
59    }
60    Ok(s)
61}
62
63/// **A `/`-separated relative path joined under `root`, or refused**: at least one segment,
64/// every segment [`sanitize_segment`], never absolute, never `..`, no empty segment (`a//b`),
65/// so the answer is always below `root`.
66pub fn sanitize_under(root: &Path, rel: &str) -> Result<PathBuf, UnsafePath> {
67    if rel.is_empty() {
68        return Err(refuse(rel, "empty"));
69    }
70    if rel.starts_with('/') || rel.starts_with('\\') || Path::new(rel).is_absolute() {
71        return Err(refuse(rel, "absolute"));
72    }
73    let mut out = root.to_path_buf();
74    for seg in rel.split('/') {
75        let seg = sanitize_segment(seg).map_err(|e| refuse(rel, e.why))?;
76        out.push(seg);
77    }
78    // The joined path's own components say the same (a `\` cannot have slipped through on
79    // Windows-style parsing either).
80    if out
81        .strip_prefix(root)
82        .map(|p| p.components().any(|c| !matches!(c, Component::Normal(_))))
83        .unwrap_or(true)
84    {
85        return Err(refuse(rel, "not below the root"));
86    }
87    Ok(out)
88}
89
90/// **A string folded to one safe segment** (never refused): every byte outside
91/// `[A-Za-z0-9._-]` becomes `_`; the empty string, `.` and `..` become `_`. Never cut: a key
92/// is the whole string, and a file system that refuses a long name refuses it by name.
93pub fn segment_of(s: &str) -> String {
94    let mut out: String = s
95        .chars()
96        .map(|c| {
97            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
98                c
99            } else {
100                '_'
101            }
102        })
103        .collect();
104    if out.is_empty() || out == "." || out == ".." {
105        out = "_".to_string();
106    }
107    out
108}
109
110/// **A coordinate folded to one segment**: `namespace__name__version`, each part with the
111/// char fold of [`segment_of`] (an empty part stays empty: the `__` make the whole one
112/// segment), so a coordinate keys one file in one directory and cannot name another. The
113/// on-disk key of every ref and SBOM: it does not change.
114pub fn segment_of_coord(namespace: Option<&str>, name: &str, version: &str) -> String {
115    let fold = |s: &str| -> String {
116        s.chars()
117            .map(|c| {
118                if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
119                    c
120                } else {
121                    '_'
122                }
123            })
124            .collect()
125    };
126    format!(
127        "{}__{}__{}",
128        fold(namespace.unwrap_or("")),
129        fold(name),
130        fold(version)
131    )
132}
133
134#[cfg(test)]
135mod tests {
136    use super::*;
137
138    const ROOT: &str = "/data/root";
139
140    /// The RED test of the follow-up: every way a request could climb out of its root.
141    #[test]
142    fn a_path_that_climbs_or_escapes_is_refused() {
143        for bad in [
144            "../x",
145            "a/../x",
146            "a/../../x",
147            "..",
148            ".",
149            "/etc/passwd",
150            "\\etc\\passwd",
151            "a\\..\\x",
152            "",
153            "a//b",
154            "a/",
155            "/a",
156            "a/./b",
157            "a\0b",
158        ] {
159            assert!(
160                sanitize_under(Path::new(ROOT), bad).is_err(),
161                "{bad:?} was joined"
162            );
163        }
164        for bad in ["", ".", "..", "a/b", "a\\b", "a\0b", &"x".repeat(256)] {
165            assert!(
166                sanitize_segment(bad).is_err(),
167                "{bad:?} was taken as a segment"
168            );
169        }
170    }
171
172    #[test]
173    fn a_plain_relative_path_lands_below_the_root() {
174        let p = sanitize_under(Path::new(ROOT), "a/b/c.txt").unwrap();
175        assert_eq!(p, Path::new(ROOT).join("a").join("b").join("c.txt"));
176        assert!(p.starts_with(ROOT));
177        assert_eq!(sanitize_segment("file.tar.gz").unwrap(), "file.tar.gz");
178        assert_eq!(sanitize_segment(".hidden").unwrap(), ".hidden");
179    }
180
181    #[test]
182    fn a_folded_segment_never_names_another_file() {
183        assert_eq!(segment_of("../x"), ".._x");
184        assert_eq!(segment_of("a/b"), "a_b");
185        assert_eq!(segment_of(".."), "_");
186        assert_eq!(segment_of("."), "_");
187        assert_eq!(segment_of(""), "_");
188        assert_eq!(segment_of("a\0b"), "a_b");
189        assert_eq!(segment_of("@scope/pkg"), "_scope_pkg");
190        assert_eq!(segment_of("ok-name_1.0"), "ok-name_1.0");
191        assert_eq!(segment_of(&"y".repeat(300)).len(), 300);
192        for s in ["../x", "a/b", "..", "", "a\0b"] {
193            assert!(sanitize_segment(&segment_of(s)).is_ok(), "{s:?}");
194        }
195        assert_eq!(
196            segment_of_coord(Some("org/x"), "n a", "1.0/../2"),
197            "org_x__n_a__1.0_.._2"
198        );
199        assert_eq!(segment_of_coord(None, "n", "v"), "__n__v");
200        assert!(sanitize_segment(&segment_of_coord(Some("../a"), "..", "/")).is_ok());
201    }
202}