holger_traits/
safe_path.rs1use std::path::{Component, Path, PathBuf};
19
20#[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
35pub 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
45pub 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
63pub 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 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
90pub 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
110pub 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 #[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}