holger-traits 3.3.2

holger's shared vocabulary: ArtifactId, RepositoryBackendTrait, ZnippyPlugin discriminants, and ArtifactFormat — including `ArtifactFormat::home()`, the format→crate map that answers which crate serves PyPI when grepping cannot.
Documentation
//! **One rule for a path a request names** (R1 follow-up, the taint lens): every place that
//! joins a string the other end sent (an artifact coordinate, a material name, a bundle
//! member, an estate file, a repository name) under a directory of this box goes through
//! this module, so the rule lives once and a path can never climb out of its root.
//!
//! Two shapes, both the whole rule:
//! * [`sanitize_segment`] / [`sanitize_under`] REFUSE: the string is used as it is or not at
//!   all (an estate file, a raw artifact path, a job input name);
//! * [`segment_of`] / [`segment_of_coord`] FOLD: the string is mapped to one safe segment
//!   (`/`, `\`, NUL and every other byte outside `[A-Za-z0-9._-]` becomes `_`; `.` and `..`
//!   and the empty string become `_`), for a key that only has to be stable and unique
//!   enough (a material file, a sync ack, a coordinate's ref).
//!
//! The names carry `sanitize` on purpose: the taint lens counts a call whose callee matches
//! `sanitiz` as a sanitizer, so a join of request data behind this module is a clean one and
//! a join without it is the finding.

use std::path::{Component, Path, PathBuf};

/// Why a string is not a path segment, or not a relative path, under a root of this box.
#[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 {}

/// The longest single segment this box files under a name (a file system's 255 bytes).
pub const MAX_SEGMENT: usize = 255;

fn refuse(given: &str, why: &'static str) -> UnsafePath {
    UnsafePath {
        given: given.to_string(),
        why,
    }
}

/// **One path segment, as given or refused**: not empty, at most [`MAX_SEGMENT`] bytes, no
/// `/`, `\` or NUL, not `.` and not `..`.
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)
}

/// **A `/`-separated relative path joined under `root`, or refused**: at least one segment,
/// every segment [`sanitize_segment`], never absolute, never `..`, no empty segment (`a//b`),
/// so the answer is always below `root`.
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);
    }
    // The joined path's own components say the same (a `\` cannot have slipped through on
    // Windows-style parsing either).
    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)
}

/// **A string folded to one safe segment** (never refused): every byte outside
/// `[A-Za-z0-9._-]` becomes `_`; the empty string, `.` and `..` become `_`. Never cut: a key
/// is the whole string, and a file system that refuses a long name refuses it by name.
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
}

/// **A coordinate folded to one segment**: `namespace__name__version`, each part with the
/// char fold of [`segment_of`] (an empty part stays empty: the `__` make the whole one
/// segment), so a coordinate keys one file in one directory and cannot name another. The
/// on-disk key of every ref and SBOM: it does not change.
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";

    /// The RED test of the follow-up: every way a request could climb out of its 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());
    }
}