use std::path::{Component, Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnsafePath {
pub given: String,
pub why: &'static str,
}
impl std::fmt::Display for UnsafePath {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?} is not a safe path: {}", self.given, self.why)
}
}
impl std::error::Error for UnsafePath {}
pub const MAX_SEGMENT: usize = 255;
fn refuse(given: &str, why: &'static str) -> UnsafePath {
UnsafePath {
given: given.to_string(),
why,
}
}
pub fn sanitize_segment(s: &str) -> Result<&str, UnsafePath> {
if s.is_empty() {
return Err(refuse(s, "empty"));
}
if s.len() > MAX_SEGMENT {
return Err(refuse(s, "longer than one file name"));
}
if s == "." || s == ".." {
return Err(refuse(s, "`.` and `..` name no file"));
}
if s.bytes().any(|b| b == b'/' || b == b'\\' || b == 0) {
return Err(refuse(s, "a separator or a NUL inside one segment"));
}
Ok(s)
}
pub fn sanitize_under(root: &Path, rel: &str) -> Result<PathBuf, UnsafePath> {
if rel.is_empty() {
return Err(refuse(rel, "empty"));
}
if rel.starts_with('/') || rel.starts_with('\\') || Path::new(rel).is_absolute() {
return Err(refuse(rel, "absolute"));
}
let mut out = root.to_path_buf();
for seg in rel.split('/') {
let seg = sanitize_segment(seg).map_err(|e| refuse(rel, e.why))?;
out.push(seg);
}
if out
.strip_prefix(root)
.map(|p| p.components().any(|c| !matches!(c, Component::Normal(_))))
.unwrap_or(true)
{
return Err(refuse(rel, "not below the root"));
}
Ok(out)
}
pub fn segment_of(s: &str) -> String {
let mut out: String = s
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
c
} else {
'_'
}
})
.collect();
if out.is_empty() || out == "." || out == ".." {
out = "_".to_string();
}
out
}
pub fn segment_of_coord(namespace: Option<&str>, name: &str, version: &str) -> String {
let fold = |s: &str| -> String {
s.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
c
} else {
'_'
}
})
.collect()
};
format!(
"{}__{}__{}",
fold(namespace.unwrap_or("")),
fold(name),
fold(version)
)
}
#[cfg(test)]
mod tests {
use super::*;
const ROOT: &str = "/data/root";
#[test]
fn a_path_that_climbs_or_escapes_is_refused() {
for bad in [
"../x",
"a/../x",
"a/../../x",
"..",
".",
"/etc/passwd",
"\\etc\\passwd",
"a\\..\\x",
"",
"a//b",
"a/",
"/a",
"a/./b",
"a\0b",
] {
assert!(
sanitize_under(Path::new(ROOT), bad).is_err(),
"{bad:?} was joined"
);
}
for bad in ["", ".", "..", "a/b", "a\\b", "a\0b", &"x".repeat(256)] {
assert!(
sanitize_segment(bad).is_err(),
"{bad:?} was taken as a segment"
);
}
}
#[test]
fn a_plain_relative_path_lands_below_the_root() {
let p = sanitize_under(Path::new(ROOT), "a/b/c.txt").unwrap();
assert_eq!(p, Path::new(ROOT).join("a").join("b").join("c.txt"));
assert!(p.starts_with(ROOT));
assert_eq!(sanitize_segment("file.tar.gz").unwrap(), "file.tar.gz");
assert_eq!(sanitize_segment(".hidden").unwrap(), ".hidden");
}
#[test]
fn a_folded_segment_never_names_another_file() {
assert_eq!(segment_of("../x"), ".._x");
assert_eq!(segment_of("a/b"), "a_b");
assert_eq!(segment_of(".."), "_");
assert_eq!(segment_of("."), "_");
assert_eq!(segment_of(""), "_");
assert_eq!(segment_of("a\0b"), "a_b");
assert_eq!(segment_of("@scope/pkg"), "_scope_pkg");
assert_eq!(segment_of("ok-name_1.0"), "ok-name_1.0");
assert_eq!(segment_of(&"y".repeat(300)).len(), 300);
for s in ["../x", "a/b", "..", "", "a\0b"] {
assert!(sanitize_segment(&segment_of(s)).is_ok(), "{s:?}");
}
assert_eq!(
segment_of_coord(Some("org/x"), "n a", "1.0/../2"),
"org_x__n_a__1.0_.._2"
);
assert_eq!(segment_of_coord(None, "n", "v"), "__n__v");
assert!(sanitize_segment(&segment_of_coord(Some("../a"), "..", "/")).is_ok());
}
}