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;
pub static FORMATS: &[&dyn Format] = &[
&CARGO, &PYPI, &NPM, &MAVEN, &GOLANG, &DEB, &RPM, &APK, &OCI, &HELM, &COMPOSER, &GENERIC,
];
pub fn of(fmt: &crate::ArtifactFormat) -> Option<&'static dyn Format> {
FORMATS
.iter()
.copied()
.find(|f| f.repository().as_ref() == Some(fmt))
}
pub trait Format: Send + Sync {
fn name(&self) -> &'static str;
fn repository(&self) -> Option<crate::ArtifactFormat> {
None
}
fn ecosystem(&self, distro: Option<&'static str>) -> &'static str;
fn claims(&self, path: &str) -> bool;
fn reads_row(&self) -> bool {
false
}
fn client_setup(&self, _at: &ClientAt<'_>) -> Vec<ClientSetup> {
Vec::new()
}
fn identify(&self, at: &Located<'_>) -> Result<Named, String>;
}
#[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,
}
#[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,
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct Located<'a> {
pub path: &'a str,
pub sha256: &'a str,
pub distro: Option<&'static str>,
pub declared: Option<(&'a str, &'a str)>,
pub row: Option<&'a IndexRow>,
}
impl Located<'_> {
pub fn file(&self) -> &str {
self.path.rsplit('/').next().unwrap_or(self.path)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Named {
pub purl: Purl,
pub coords: Option<(String, String)>,
}
pub fn same_name(a: &str, b: &str) -> bool {
let n = |s: &str| s.to_ascii_lowercase().replace('_', "-");
n(a) == n(b)
}
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
)
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Purl {
#[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(),
}
}
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";
#[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);
}
}
}
#[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);
}
}