1use std::collections::BTreeMap;
12
13use serde::{Deserialize, Serialize};
14
15use crate::index_row::IndexRow;
16
17pub mod apk;
18pub mod cargo;
19pub mod composer;
20pub mod deb;
21pub mod generic;
22pub mod golang;
23pub mod helm;
24pub mod maven;
25pub mod npm;
26pub mod oci;
27pub mod pypi;
28pub mod rpm;
29
30pub use apk::APK;
31pub use cargo::CARGO;
32pub use composer::COMPOSER;
33pub use deb::DEB;
34pub use generic::GENERIC;
35pub use golang::GOLANG;
36pub use helm::HELM;
37pub use maven::MAVEN;
38pub use npm::NPM;
39pub use oci::OCI;
40pub use pypi::PYPI;
41pub use rpm::RPM;
42
43pub static FORMATS: &[&dyn Format] = &[
45 &CARGO, &PYPI, &NPM, &MAVEN, &GOLANG, &DEB, &RPM, &APK, &OCI, &HELM, &COMPOSER, &GENERIC,
46];
47
48pub fn of(fmt: &crate::ArtifactFormat) -> Option<&'static dyn Format> {
51 FORMATS
52 .iter()
53 .copied()
54 .find(|f| f.repository().as_ref() == Some(fmt))
55}
56
57pub trait Format: Send + Sync {
60 fn name(&self) -> &'static str;
62
63 fn repository(&self) -> Option<crate::ArtifactFormat> {
66 None
67 }
68
69 fn ecosystem(&self, distro: Option<&'static str>) -> &'static str;
72
73 fn claims(&self, path: &str) -> bool;
76
77 fn reads_row(&self) -> bool {
79 false
80 }
81
82 fn client_setup(&self, _at: &ClientAt<'_>) -> Vec<ClientSetup> {
85 Vec::new()
86 }
87
88 fn identify(&self, at: &Located<'_>) -> Result<Named, String>;
91}
92
93#[derive(Debug, Clone, Copy)]
97pub struct ClientAt<'a> {
98 pub name: &'a str,
99 pub base: &'a str,
100 pub host: &'a str,
101 pub token: &'a str,
102 pub key_path: &'a str,
103 pub trust: &'a str,
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
108pub struct ClientSetup {
109 pub client: &'static str,
110 pub file: String,
111 pub snippet: String,
112}
113
114impl ClientSetup {
115 pub fn new(client: &'static str, file: impl Into<String>, snippet: String) -> Self {
116 Self {
117 client,
118 file: file.into(),
119 snippet,
120 }
121 }
122}
123
124#[derive(Debug, Clone, Copy)]
126pub struct Located<'a> {
127 pub path: &'a str,
130 pub sha256: &'a str,
132 pub distro: Option<&'static str>,
134 pub declared: Option<(&'a str, &'a str)>,
136 pub row: Option<&'a IndexRow>,
138}
139
140impl Located<'_> {
141 pub fn file(&self) -> &str {
143 self.path.rsplit('/').next().unwrap_or(self.path)
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct Named {
152 pub purl: Purl,
153 pub coords: Option<(String, String)>,
154}
155
156pub fn same_name(a: &str, b: &str) -> bool {
158 let n = |s: &str| s.to_ascii_lowercase().replace('_', "-");
159 n(a) == n(b)
160}
161
162pub fn mismatch(format: &str, said: (&str, &str), own: (&str, &str), what: &str) -> String {
165 format!(
166 "the {format} package at {}@{} names itself {}@{} in its {what}; it is refused, never served under a name it does not carry",
167 said.0, said.1, own.0, own.1
168 )
169}
170
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
173pub struct Purl {
174 #[serde(rename = "type")]
177 pub ty: String,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub namespace: Option<String>,
180 pub name: String,
181 #[serde(default, skip_serializing_if = "String::is_empty")]
182 pub version: String,
183 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
184 pub qualifiers: BTreeMap<String, String>,
185}
186
187fn enc(s: &str, keep_slash: bool) -> String {
188 let mut out = String::with_capacity(s.len());
189 for b in s.bytes() {
190 let c = b as char;
191 if c.is_ascii_alphanumeric()
192 || matches!(c, '.' | '-' | '_' | '~' | ':')
193 || (keep_slash && c == '/')
194 {
195 out.push(c);
196 } else {
197 out.push_str(&format!("%{b:02X}"));
198 }
199 }
200 out
201}
202
203impl Purl {
204 pub fn new(ty: &str, namespace: Option<&str>, name: &str, version: &str) -> Self {
205 Self {
206 ty: ty.to_string(),
207 namespace: namespace.filter(|n| !n.is_empty()).map(str::to_string),
208 name: name.to_string(),
209 version: version.to_string(),
210 qualifiers: BTreeMap::new(),
211 }
212 }
213
214 pub fn with(mut self, key: &str, value: &str) -> Self {
216 if !value.is_empty() {
217 self.qualifiers.insert(key.to_string(), value.to_string());
218 }
219 self
220 }
221}
222
223impl std::fmt::Display for Purl {
224 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225 write!(f, "pkg:{}/", self.ty)?;
226 if let Some(ns) = &self.namespace {
227 let segs: Vec<String> = ns.split('/').map(|s| enc(s, false)).collect();
228 write!(f, "{}/", segs.join("/"))?;
229 }
230 f.write_str(&enc(&self.name, false))?;
231 if !self.version.is_empty() {
232 write!(f, "@{}", enc(&self.version, false))?;
233 }
234 let q: Vec<String> = self
235 .qualifiers
236 .iter()
237 .map(|(k, v)| format!("{k}={}", enc(v, true)))
238 .collect();
239 if !q.is_empty() {
240 write!(f, "?{}", q.join("&"))?;
241 }
242 Ok(())
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 #[cfg(feature = "test-support")]
249 use super::*;
250
251 #[cfg(feature = "test-support")]
252 const OCI_GOOD: &str =
253 "chainguard/static/sha256-17367e4d3ae2b46c3290858e483fac09be085c92b372360fe3bf6a6150848fde.oci.tar";
254
255 #[cfg(feature = "test-support")]
257 #[test]
258 fn every_format_here_conforms() {
259 for f in FORMATS {
260 let (good, bad) = match f.name() {
261 "cargo" => ("smallvec/smallvec-1.6.0.crate", "smallvec/README.md"),
262 "pypi" => ("PyYAML-5.3.tar.gz", "notes/README"),
263 "maven" => ("g/a/1.0/a-1.0.jar", "notes/README"),
264 "npm" => ("@scope/pkg/-/pkg-1.2.3.tgz", "notes/README"),
265 "golang" => ("golang.org/x/text/@v/v0.3.7.zip", "notes/README"),
266 "deb" => (
267 "pool/main/o/openssl/libssl3_3.0.11-1_amd64.deb",
268 "notes/README",
269 ),
270 "rpm" => ("openssl-3.0.1-41.el9_0.x86_64.rpm", "notes/README"),
271 "apk" => ("x86_64/openssl-3.2.0-r0.apk", "notes/README"),
272 "oci" => (OCI_GOOD, "notes/README"),
273 "helm" => ("charts/demo-1.0.0.tgz", "notes/README"),
274 "composer" => (
275 "guzzlehttp/guzzle/guzzlehttp-guzzle-7.4.4.zip",
276 "notes/README",
277 ),
278 "generic" => ("files/notes.txt", "x/a-1.crate"),
279 other => panic!("{other}: no conformance case"),
280 };
281 let deb = IndexRow::Deb {
282 control: "Package: libssl3\nVersion: 3.0.11-1\nArchitecture: amd64\n".into(),
283 };
284 let composer = IndexRow::Composer {
285 name: "guzzlehttp/guzzle".into(),
286 version: None,
287 };
288 let row = match f.name() {
289 "deb" => Some(&deb),
290 "composer" => Some(&composer),
291 _ => None,
292 };
293 crate::test_support::format_conforms(*f, good, row, bad);
294 }
295 }
296}
297
298#[cfg(test)]
300pub(crate) fn test_at<'a>(path: &'a str, row: Option<&'a IndexRow>) -> Located<'a> {
301 Located {
302 path,
303 sha256: "ab",
304 distro: None,
305 declared: None,
306 row,
307 }
308}
309
310#[cfg(test)]
311mod purl_tests {
312 use super::*;
313
314 #[test]
315 fn every_client_setup_names_the_repository_its_address_and_the_token() {
316 let at = ClientAt {
317 name: "acme",
318 base: "https://repo.example.org",
319 host: "repo.example.org",
320 token: "<TOKEN>",
321 key_path: "/-/repo-key.asc",
322 trust: "# trust\n",
323 };
324 let mut with_setup = Vec::new();
325 for f in FORMATS {
326 let setup = f.client_setup(&at);
327 if setup.is_empty() {
328 continue;
329 }
330 with_setup.push(f.name());
331 let all: String = setup.iter().map(|s| s.snippet.as_str()).collect();
332 assert!(
333 all.contains("acme") && all.contains("repo.example.org"),
334 "{}",
335 f.name()
336 );
337 assert!(all.contains("<TOKEN>"), "{}: no token", f.name());
338 }
339 assert_eq!(
340 with_setup,
341 ["cargo", "pypi", "npm", "maven", "deb", "rpm", "oci"]
342 );
343 let deb: String = DEB
344 .client_setup(&at)
345 .iter()
346 .map(|s| s.snippet.clone())
347 .collect();
348 assert!(
349 deb.contains("# trust\n") && deb.contains("https://repo.example.org/-/repo-key.asc")
350 );
351 }
352
353 #[test]
354 fn a_repository_format_finds_its_one_descriptor() {
355 for fmt in crate::ALL_ARTIFACT_FORMATS {
356 let n = FORMATS
357 .iter()
358 .filter(|f| f.repository().as_ref() == Some(fmt))
359 .count();
360 assert!(n <= 1, "{fmt:?} has {n} descriptors");
361 }
362 assert_eq!(
363 of(&crate::ArtifactFormat::Rust).map(|f| f.name()),
364 Some("cargo")
365 );
366 assert_eq!(
367 of(&crate::ArtifactFormat::Raw).map(|f| f.name()),
368 Some("generic")
369 );
370 assert!(of(&crate::ArtifactFormat::Nuget).is_none());
371 }
372
373 #[test]
374 fn a_purl_escapes_its_parts_and_sorts_its_qualifiers() {
375 let p = Purl::new("npm", Some("@scope"), "pkg", "1.0")
376 .with("b", "x/y")
377 .with("a", "1")
378 .with("empty", "");
379 assert_eq!(p.to_string(), "pkg:npm/%40scope/pkg@1.0?a=1&b=x/y");
380 assert_eq!(
381 Purl::new("generic", Some(""), "a b", "").to_string(),
382 "pkg:generic/a%20b"
383 );
384 }
385
386 #[test]
387 fn names_compare_as_cargo_and_pep_503_compare_them() {
388 assert!(same_name("Serde_Json", "serde-json"));
389 assert!(!same_name("serde", "serde-json"));
390 assert!(
391 mismatch("cargo", ("a", "1"), ("b", "2"), "Cargo.toml").contains("names itself b@2")
392 );
393 }
394
395 #[test]
396 fn a_purl_round_trips_as_json() {
397 let p = Purl::new("maven", Some("org.x"), "y", "1").with("type", "jar");
398 let j = serde_json::to_string(&p).unwrap();
399 assert!(j.contains(r#""type":"maven""#), "{j}");
400 assert_eq!(serde_json::from_str::<Purl>(&j).unwrap(), p);
401 }
402}