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 descriptor per package format** ([`Format`]).
//!
//! Everything Holger knows about a package format beside serving its bytes is one
//! [`Format`] impl: the name it goes by, the ecosystem its advisories are filed under,
//! which paths are its packages, and how a package of it is named ([`Format::identify`],
//! a purl). The intake chain, the scanners and the console ask the descriptor; they never
//! match on the format themselves.
//!
//! [`FORMATS`] lists every descriptor.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

use crate::index_row::IndexRow;

pub mod apk;
pub mod cargo;
pub mod composer;
pub mod deb;
pub mod generic;
pub mod golang;
pub mod helm;
pub mod maven;
pub mod npm;
pub mod oci;
pub mod pypi;
pub mod rpm;

pub use apk::APK;
pub use cargo::CARGO;
pub use composer::COMPOSER;
pub use deb::DEB;
pub use generic::GENERIC;
pub use golang::GOLANG;
pub use helm::HELM;
pub use maven::MAVEN;
pub use npm::NPM;
pub use oci::OCI;
pub use pypi::PYPI;
pub use rpm::RPM;

/// The descriptors that live in this crate.
pub static FORMATS: &[&dyn Format] = &[
    &CARGO, &PYPI, &NPM, &MAVEN, &GOLANG, &DEB, &RPM, &APK, &OCI, &HELM, &COMPOSER, &GENERIC,
];

/// **The descriptor of the packages a repository of `fmt` holds**, `None` for a format no
/// descriptor names yet (its packages are refused at intake, by name).
pub fn of(fmt: &crate::ArtifactFormat) -> Option<&'static dyn Format> {
    FORMATS
        .iter()
        .copied()
        .find(|f| f.repository().as_ref() == Some(fmt))
}

/// **One package format.** `identify` is the one way a package of the format is named;
/// `Err` says why it cannot be, and the chain refuses the package with it.
pub trait Format: Send + Sync {
    /// The name the format goes by (its purl type, and the word in a refusal).
    fn name(&self) -> &'static str;

    /// The repository format whose packages this descriptor names (`None` for a format no
    /// repository type holds, an APK).
    fn repository(&self) -> Option<crate::ArtifactFormat> {
        None
    }

    /// The advisory ecosystem label its packages are matched in (modgunn's spelling); an
    /// APK's is its distribution's (`distro`).
    fn ecosystem(&self, distro: Option<&'static str>) -> &'static str;

    /// **Is `path` a package of this format**, or a file beside its packages (an apt view's
    /// `Release`, a Maven `maven-metadata.xml`)? A file that is no package is a generic file.
    fn claims(&self, path: &str) -> bool;

    /// Does this format's identity come from the package itself (its index row)?
    fn reads_row(&self) -> bool {
        false
    }

    /// **How a package client is set up for a repository of this format** ([`ClientAt`]):
    /// its config files and commands. Empty: the generic HTTP setup (`curl`).
    fn client_setup(&self, _at: &ClientAt<'_>) -> Vec<ClientSetup> {
        Vec::new()
    }

    /// The package's purl and its advisory coordinates, from where it came in and from its
    /// index row.
    fn identify(&self, at: &Located<'_>) -> Result<Named, String>;
}

/// **The repository a client is set up for**: `name` at `base` (no trailing `/`) on `host`,
/// with `token` in place of the secret; `key_path` is the door of the box's repository key and
/// `trust` the comment that names which key a client trusts (the deb and rpm setup).
#[derive(Debug, Clone, Copy)]
pub struct ClientAt<'a> {
    pub name: &'a str,
    pub base: &'a str,
    pub host: &'a str,
    pub token: &'a str,
    pub key_path: &'a str,
    pub trust: &'a str,
}

/// One client's setup: the client, the file it goes in (or `shell`), what to write there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ClientSetup {
    pub client: &'static str,
    pub file: String,
    pub snippet: String,
}

impl ClientSetup {
    pub fn new(client: &'static str, file: impl Into<String>, snippet: String) -> Self {
        Self {
            client,
            file: file.into(),
            snippet,
        }
    }
}

/// Where a package came in, and what the worker read out of it: what a format identifies from.
#[derive(Debug, Clone, Copy)]
pub struct Located<'a> {
    /// The coordinate below its door (`smallvec/smallvec-1.6.0.crate`, `pool/main/o/openssl/
    /// libssl3_3.0.11-1~deb12u2_amd64.deb`).
    pub path: &'a str,
    /// The SHA-256 of the bytes, lowercase hex.
    pub sha256: &'a str,
    /// An APK's distribution (`wolfi`, `chainguard`, `alpine`), from its repository.
    pub distro: Option<&'static str>,
    /// The coordinates the caller declared (an `ArtifactId` with a version).
    pub declared: Option<(&'a str, &'a str)>,
    /// The index row the scan worker read out of the package, when it read one.
    pub row: Option<&'a IndexRow>,
}

impl Located<'_> {
    /// The file name: the last segment of [`Located::path`].
    pub fn file(&self) -> &str {
        self.path.rsplit('/').next().unwrap_or(self.path)
    }
}

/// **What a format names a package**: its purl, and `(name, version)` as the advisories
/// name it (`org.apache.logging.log4j:log4j-core`, `@scope/pkg`, a `.deb`'s SOURCE
/// package); `None` where the scan reads the packages itself (an image, a generic file).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Named {
    pub purl: Purl,
    pub coords: Option<(String, String)>,
}

/// Cargo's (and Python's) name equality: case-insensitive, `-` and `_` the same.
pub fn same_name(a: &str, b: &str) -> bool {
    let n = |s: &str| s.to_ascii_lowercase().replace('_', "-");
    n(a) == n(b)
}

/// The refusal for a package whose own manifest (`what`) names another package than the
/// coordinate it came in under.
pub fn mismatch(format: &str, said: (&str, &str), own: (&str, &str), what: &str) -> String {
    format!(
        "the {format} package at {}@{} names itself {}@{} in its {what}; it is refused, never served under a name it does not carry",
        said.0, said.1, own.0, own.1
    )
}

/// A package URL (<https://github.com/package-url/purl-spec>).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Purl {
    /// The purl type (`cargo`, `pypi`, `npm`, `maven`, `golang`, `deb`, `rpm`, `apk`, `oci`,
    /// `helm`, `generic`).
    #[serde(rename = "type")]
    pub ty: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub namespace: Option<String>,
    pub name: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub version: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub qualifiers: BTreeMap<String, String>,
}

fn enc(s: &str, keep_slash: bool) -> String {
    let mut out = String::with_capacity(s.len());
    for b in s.bytes() {
        let c = b as char;
        if c.is_ascii_alphanumeric()
            || matches!(c, '.' | '-' | '_' | '~' | ':')
            || (keep_slash && c == '/')
        {
            out.push(c);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    out
}

impl Purl {
    pub fn new(ty: &str, namespace: Option<&str>, name: &str, version: &str) -> Self {
        Self {
            ty: ty.to_string(),
            namespace: namespace.filter(|n| !n.is_empty()).map(str::to_string),
            name: name.to_string(),
            version: version.to_string(),
            qualifiers: BTreeMap::new(),
        }
    }

    /// The same purl with the qualifier `key=value` (an empty value is left out).
    pub fn with(mut self, key: &str, value: &str) -> Self {
        if !value.is_empty() {
            self.qualifiers.insert(key.to_string(), value.to_string());
        }
        self
    }
}

impl std::fmt::Display for Purl {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "pkg:{}/", self.ty)?;
        if let Some(ns) = &self.namespace {
            let segs: Vec<String> = ns.split('/').map(|s| enc(s, false)).collect();
            write!(f, "{}/", segs.join("/"))?;
        }
        f.write_str(&enc(&self.name, false))?;
        if !self.version.is_empty() {
            write!(f, "@{}", enc(&self.version, false))?;
        }
        let q: Vec<String> = self
            .qualifiers
            .iter()
            .map(|(k, v)| format!("{k}={}", enc(v, true)))
            .collect();
        if !q.is_empty() {
            write!(f, "?{}", q.join("&"))?;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "test-support")]
    use super::*;

    #[cfg(feature = "test-support")]
    const OCI_GOOD: &str =
        "chainguard/static/sha256-17367e4d3ae2b46c3290858e483fac09be085c92b372360fe3bf6a6150848fde.oci.tar";

    /// Every descriptor here holds to the contract every format holds to.
    #[cfg(feature = "test-support")]
    #[test]
    fn every_format_here_conforms() {
        for f in FORMATS {
            let (good, bad) = match f.name() {
                "cargo" => ("smallvec/smallvec-1.6.0.crate", "smallvec/README.md"),
                "pypi" => ("PyYAML-5.3.tar.gz", "notes/README"),
                "maven" => ("g/a/1.0/a-1.0.jar", "notes/README"),
                "npm" => ("@scope/pkg/-/pkg-1.2.3.tgz", "notes/README"),
                "golang" => ("golang.org/x/text/@v/v0.3.7.zip", "notes/README"),
                "deb" => (
                    "pool/main/o/openssl/libssl3_3.0.11-1_amd64.deb",
                    "notes/README",
                ),
                "rpm" => ("openssl-3.0.1-41.el9_0.x86_64.rpm", "notes/README"),
                "apk" => ("x86_64/openssl-3.2.0-r0.apk", "notes/README"),
                "oci" => (OCI_GOOD, "notes/README"),
                "helm" => ("charts/demo-1.0.0.tgz", "notes/README"),
                "composer" => (
                    "guzzlehttp/guzzle/guzzlehttp-guzzle-7.4.4.zip",
                    "notes/README",
                ),
                "generic" => ("files/notes.txt", "x/a-1.crate"),
                other => panic!("{other}: no conformance case"),
            };
            let deb = IndexRow::Deb {
                control: "Package: libssl3\nVersion: 3.0.11-1\nArchitecture: amd64\n".into(),
            };
            let composer = IndexRow::Composer {
                name: "guzzlehttp/guzzle".into(),
                version: None,
            };
            let row = match f.name() {
                "deb" => Some(&deb),
                "composer" => Some(&composer),
                _ => None,
            };
            crate::test_support::format_conforms(*f, good, row, bad);
        }
    }
}

/// A package at `path` with `row`, nothing declared: the unit tests' [`Located`].
#[cfg(test)]
pub(crate) fn test_at<'a>(path: &'a str, row: Option<&'a IndexRow>) -> Located<'a> {
    Located {
        path,
        sha256: "ab",
        distro: None,
        declared: None,
        row,
    }
}

#[cfg(test)]
mod purl_tests {
    use super::*;

    #[test]
    fn every_client_setup_names_the_repository_its_address_and_the_token() {
        let at = ClientAt {
            name: "acme",
            base: "https://repo.example.org",
            host: "repo.example.org",
            token: "<TOKEN>",
            key_path: "/-/repo-key.asc",
            trust: "# trust\n",
        };
        let mut with_setup = Vec::new();
        for f in FORMATS {
            let setup = f.client_setup(&at);
            if setup.is_empty() {
                continue;
            }
            with_setup.push(f.name());
            let all: String = setup.iter().map(|s| s.snippet.as_str()).collect();
            assert!(
                all.contains("acme") && all.contains("repo.example.org"),
                "{}",
                f.name()
            );
            assert!(all.contains("<TOKEN>"), "{}: no token", f.name());
        }
        assert_eq!(
            with_setup,
            ["cargo", "pypi", "npm", "maven", "deb", "rpm", "oci"]
        );
        let deb: String = DEB
            .client_setup(&at)
            .iter()
            .map(|s| s.snippet.clone())
            .collect();
        assert!(
            deb.contains("# trust\n") && deb.contains("https://repo.example.org/-/repo-key.asc")
        );
    }

    #[test]
    fn a_repository_format_finds_its_one_descriptor() {
        for fmt in crate::ALL_ARTIFACT_FORMATS {
            let n = FORMATS
                .iter()
                .filter(|f| f.repository().as_ref() == Some(fmt))
                .count();
            assert!(n <= 1, "{fmt:?} has {n} descriptors");
        }
        assert_eq!(
            of(&crate::ArtifactFormat::Rust).map(|f| f.name()),
            Some("cargo")
        );
        assert_eq!(
            of(&crate::ArtifactFormat::Raw).map(|f| f.name()),
            Some("generic")
        );
        assert!(of(&crate::ArtifactFormat::Nuget).is_none());
    }

    #[test]
    fn a_purl_escapes_its_parts_and_sorts_its_qualifiers() {
        let p = Purl::new("npm", Some("@scope"), "pkg", "1.0")
            .with("b", "x/y")
            .with("a", "1")
            .with("empty", "");
        assert_eq!(p.to_string(), "pkg:npm/%40scope/pkg@1.0?a=1&b=x/y");
        assert_eq!(
            Purl::new("generic", Some(""), "a b", "").to_string(),
            "pkg:generic/a%20b"
        );
    }

    #[test]
    fn names_compare_as_cargo_and_pep_503_compare_them() {
        assert!(same_name("Serde_Json", "serde-json"));
        assert!(!same_name("serde", "serde-json"));
        assert!(
            mismatch("cargo", ("a", "1"), ("b", "2"), "Cargo.toml").contains("names itself b@2")
        );
    }

    #[test]
    fn a_purl_round_trips_as_json() {
        let p = Purl::new("maven", Some("org.x"), "y", "1").with("type", "jar");
        let j = serde_json::to_string(&p).unwrap();
        assert!(j.contains(r#""type":"maven""#), "{j}");
        assert_eq!(serde_json::from_str::<Purl>(&j).unwrap(), p);
    }
}