lib

Core libraries for Radroots
git clone https://radroots.dev/git/lib.git
Log | Files | Refs | README

supply_chain_qualification.rs (34420B)


      1 use std::collections::{BTreeMap, BTreeSet};
      2 use std::fs;
      3 use std::path::{Path, PathBuf};
      4 use std::process::Command;
      5 
      6 use serde::{Deserialize, Serialize};
      7 use serde_json::{Value, json};
      8 use sha2::{Digest, Sha256};
      9 
     10 const CONTRACT_PATH: &str = "contracts/releases/supply_chain.toml";
     11 const DENY_PATH: &str = "deny.toml";
     12 const SBOM_FILENAME: &str = "radroots-release-v1-sbom.json";
     13 
     14 #[derive(Debug, Deserialize)]
     15 struct Contract {
     16     schema_version: u16,
     17     spec_id: String,
     18     package_version: String,
     19     tools: Tools,
     20     sbom: Sbom,
     21     advisory_exception: Vec<AdvisoryException>,
     22     git_source: Vec<GitSource>,
     23     package: Vec<Package>,
     24 }
     25 
     26 #[derive(Debug, Deserialize)]
     27 struct Tools {
     28     cargo_deny: String,
     29     cargo_cyclonedx: String,
     30     cargo_vet: String,
     31 }
     32 
     33 #[derive(Debug, Deserialize)]
     34 struct Sbom {
     35     format: String,
     36     spec_version: String,
     37     target: String,
     38     all_features: bool,
     39     source_date_epoch: u64,
     40 }
     41 
     42 #[derive(Clone, Debug, Deserialize, Serialize)]
     43 struct AdvisoryException {
     44     id: String,
     45     package: String,
     46     affected_version: String,
     47     introduced_by: String,
     48     classification: String,
     49     mitigation: String,
     50     remove_when: String,
     51 }
     52 
     53 #[derive(Debug, Deserialize)]
     54 struct Package {
     55     name: String,
     56     manifest_path: String,
     57 }
     58 
     59 #[derive(Debug, Deserialize)]
     60 struct GitSource {
     61     url: String,
     62     revision: String,
     63     packages: Vec<String>,
     64     removal_when: String,
     65 }
     66 
     67 #[derive(Debug, Deserialize)]
     68 struct Metadata {
     69     packages: Vec<MetadataPackage>,
     70 }
     71 
     72 #[derive(Debug, Deserialize)]
     73 struct MetadataPackage {
     74     name: String,
     75     version: String,
     76     manifest_path: PathBuf,
     77 }
     78 
     79 struct GeneratedSboms(Vec<PathBuf>);
     80 
     81 impl Drop for GeneratedSboms {
     82     fn drop(&mut self) {
     83         for path in &self.0 {
     84             let _ = fs::remove_file(path);
     85         }
     86     }
     87 }
     88 
     89 pub fn run(root: &Path) -> Result<(), String> {
     90     let contract = load(root)?;
     91     let expected = crate::catalog::public_packages(root)?;
     92     validate(root, &contract, expected.len())?;
     93     if contract
     94         .package
     95         .iter()
     96         .map(|p| &p.name)
     97         .collect::<BTreeSet<_>>()
     98         != expected.iter().collect()
     99     {
    100         return Err("supply-chain contract must match the current public allocation".to_owned());
    101     }
    102     verify_tools(&contract)?;
    103     let metadata = load_metadata(root)?;
    104     qualify_git_sources(root, &contract)?;
    105     qualify_dependencies(root, &contract)?;
    106     let sbom_hashes = qualify_sboms(root, &contract, &metadata)?;
    107     let provenance = build_provenance(root, &contract, &sbom_hashes)?;
    108     validate_provenance(&provenance, &contract)?;
    109     eprintln!(
    110         "qualified {} package supply chains; provenance sha256={}",
    111         contract.package.len(),
    112         sha256(&serde_json::to_vec(&provenance).map_err(|error| error.to_string())?)
    113     );
    114     Ok(())
    115 }
    116 
    117 fn load(root: &Path) -> Result<Contract, String> {
    118     let path = root.join(CONTRACT_PATH);
    119     let raw = fs::read_to_string(&path)
    120         .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
    121     toml::from_str(&raw).map_err(|error| format!("failed to parse {}: {error}", path.display()))
    122 }
    123 
    124 fn validate(root: &Path, contract: &Contract, expected_packages: usize) -> Result<(), String> {
    125     if contract.schema_version != 1
    126         || contract.spec_id != "radroots.crates.release.v2"
    127         || contract.package_version != "0.1.0-alpha"
    128         || contract.tools.cargo_deny != "0.19.8"
    129         || contract.tools.cargo_cyclonedx != "0.5.9"
    130         || contract.tools.cargo_vet != "0.10.2"
    131         || contract.sbom.format != "json"
    132         || contract.sbom.spec_version != "1.5"
    133         || contract.sbom.target != "all"
    134         || !contract.sbom.all_features
    135         || contract.sbom.source_date_epoch != 0
    136     {
    137         return Err("invalid supply-chain qualification contract".to_owned());
    138     }
    139 
    140     let mut sources = BTreeSet::new();
    141     for source in &contract.git_source {
    142         let packages = source.packages.iter().collect::<BTreeSet<_>>();
    143         if !source.url.starts_with("https://github.com/")
    144             || source.url.contains(['?', '#', '@'])
    145             || source.revision.len() != 40
    146             || !source.revision.bytes().all(|byte| byte.is_ascii_hexdigit())
    147             || source.removal_when.is_empty()
    148             || packages.is_empty()
    149             || packages.len() != source.packages.len()
    150             || packages.iter().any(|name| name.is_empty())
    151             || !sources.insert(&source.url)
    152         {
    153             return Err(
    154                 "Git source contract requires unique immutable sources and packages".to_owned(),
    155             );
    156         }
    157     }
    158 
    159     let names = contract
    160         .package
    161         .iter()
    162         .map(|package| package.name.as_str())
    163         .collect::<BTreeSet<_>>();
    164     let manifests = contract
    165         .package
    166         .iter()
    167         .map(|package| package.manifest_path.as_str())
    168         .collect::<BTreeSet<_>>();
    169     if names.len() != expected_packages
    170         || names.len() != contract.package.len()
    171         || manifests.len() != contract.package.len()
    172     {
    173         return Err(format!(
    174             "supply-chain contract requires exactly {expected_packages} unique packages and manifests"
    175         ));
    176     }
    177     for package in &contract.package {
    178         let path = root.join(&package.manifest_path);
    179         let raw = fs::read_to_string(&path)
    180             .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
    181         let manifest: toml::Value = toml::from_str(&raw)
    182             .map_err(|error| format!("failed to parse {}: {error}", path.display()))?;
    183         let package_table = manifest
    184             .get("package")
    185             .and_then(toml::Value::as_table)
    186             .ok_or_else(|| format!("{} has no package table", path.display()))?;
    187         let name = package_table.get("name").and_then(toml::Value::as_str);
    188         let version = package_table.get("version").and_then(toml::Value::as_str);
    189         if name != Some(package.name.as_str()) || version != Some(contract.package_version.as_str())
    190         {
    191             return Err(format!(
    192                 "{} does not declare {} {}",
    193                 path.display(),
    194                 package.name,
    195                 contract.package_version
    196             ));
    197         }
    198     }
    199 
    200     validate_exceptions(root, contract)
    201 }
    202 
    203 fn qualify_git_sources(root: &Path, contract: &Contract) -> Result<(), String> {
    204     let approved = contract
    205         .git_source
    206         .iter()
    207         .map(|source| (source.url.clone(), source.revision.clone()))
    208         .collect::<BTreeSet<_>>();
    209     let mut seen = BTreeSet::new();
    210     let manifest = root.join("Cargo.toml");
    211     let raw = fs::read_to_string(&manifest)
    212         .map_err(|error| format!("failed to read {}: {error}", manifest.display()))?;
    213     let value = toml::from_str(&raw)
    214         .map_err(|error| format!("failed to parse {}: {error}", manifest.display()))?;
    215     inspect_git_dependencies(&value, &manifest, &approved, &mut seen)?;
    216     for entry in walkdir::WalkDir::new(root.join("crates")) {
    217         let entry = entry.map_err(|error| format!("failed to walk manifests: {error}"))?;
    218         if entry.file_name() != "Cargo.toml" {
    219             continue;
    220         }
    221         let raw = fs::read_to_string(entry.path())
    222             .map_err(|error| format!("failed to read {}: {error}", entry.path().display()))?;
    223         let manifest: toml::Value = toml::from_str(&raw)
    224             .map_err(|error| format!("failed to parse {}: {error}", entry.path().display()))?;
    225         inspect_git_dependencies(&manifest, entry.path(), &approved, &mut seen)?;
    226     }
    227     let deny_raw = fs::read_to_string(root.join(DENY_PATH))
    228         .map_err(|error| format!("failed to read {DENY_PATH}: {error}"))?;
    229     let deny = toml::from_str::<toml::Value>(&deny_raw)
    230         .map_err(|error| format!("failed to parse {DENY_PATH}: {error}"))?;
    231     let deny_git_sources = deny
    232         .get("sources")
    233         .and_then(|sources| sources.get("allow-git"))
    234         .and_then(toml::Value::as_array)
    235         .ok_or_else(|| "deny.toml sources.allow-git is missing".to_owned())?
    236         .iter()
    237         .filter_map(toml::Value::as_str)
    238         .collect::<BTreeSet<_>>();
    239     let approved_urls = contract
    240         .git_source
    241         .iter()
    242         .map(|source| source.url.as_str())
    243         .collect::<BTreeSet<_>>();
    244     if deny_git_sources != approved_urls {
    245         return Err(
    246             "cargo-deny Git source authority differs from the exact-revision policy".to_owned(),
    247         );
    248     }
    249     let raw = fs::read_to_string(root.join("Cargo.lock"))
    250         .map_err(|error| format!("failed to read Cargo.lock: {error}"))?;
    251     qualify_locked_git_sources(&raw, &contract.git_source)
    252 }
    253 
    254 fn qualify_locked_git_sources(raw: &str, approved: &[GitSource]) -> Result<(), String> {
    255     let lock: toml::Value =
    256         toml::from_str(raw).map_err(|error| format!("failed to parse Cargo.lock: {error}"))?;
    257     let packages = lock
    258         .get("package")
    259         .and_then(toml::Value::as_array)
    260         .ok_or_else(|| "Cargo.lock contains no packages".to_owned())?;
    261     let mut seen = BTreeMap::<&str, BTreeSet<&str>>::new();
    262     for package in packages {
    263         let Some(source) = package
    264             .get("source")
    265             .and_then(toml::Value::as_str)
    266             .filter(|value| value.starts_with("git+"))
    267         else {
    268             continue;
    269         };
    270         let (url_and_query, commit) = source
    271             .rsplit_once('#')
    272             .ok_or_else(|| format!("Git lock source has no commit: {source}"))?;
    273         let (url, revision) = url_and_query
    274             .strip_prefix("git+")
    275             .and_then(|value| value.split_once("?rev="))
    276             .ok_or_else(|| format!("Git lock source is not exact-rev pinned: {source}"))?;
    277         let authority = approved
    278             .iter()
    279             .find(|entry| entry.url == url && entry.revision == revision);
    280         let name = package
    281             .get("name")
    282             .and_then(toml::Value::as_str)
    283             .ok_or_else(|| "locked Git package has no name".to_owned())?;
    284         if commit != revision
    285             || authority.is_none_or(|entry| !entry.packages.iter().any(|p| p == name))
    286         {
    287             return Err(format!(
    288                 "Git lock source is not approved and immutable: {source}"
    289             ));
    290         }
    291         seen.entry(url).or_default().insert(name);
    292     }
    293     for source in approved {
    294         let expected = source
    295             .packages
    296             .iter()
    297             .map(String::as_str)
    298             .collect::<BTreeSet<_>>();
    299         if seen.get(source.url.as_str()) != Some(&expected) {
    300             return Err(format!(
    301                 "approved Git package set is stale or incomplete: {}",
    302                 source.url
    303             ));
    304         }
    305     }
    306     Ok(())
    307 }
    308 
    309 fn inspect_git_dependencies(
    310     value: &toml::Value,
    311     path: &Path,
    312     approved: &BTreeSet<(String, String)>,
    313     seen: &mut BTreeSet<(String, String)>,
    314 ) -> Result<(), String> {
    315     match value {
    316         toml::Value::Table(table) => {
    317             if let Some(url) = table.get("git").and_then(toml::Value::as_str) {
    318                 let revision = table.get("rev").and_then(toml::Value::as_str);
    319                 if table.contains_key("branch")
    320                     || table.contains_key("tag")
    321                     || revision.is_none_or(|revision| {
    322                         revision.len() != 40
    323                             || !revision.bytes().all(|byte| byte.is_ascii_hexdigit())
    324                     })
    325                 {
    326                     return Err(format!(
    327                         "{} contains a branch, tag, or non-full Git revision",
    328                         path.display()
    329                     ));
    330                 }
    331                 let authority = (
    332                     url.to_owned(),
    333                     revision.expect("checked revision").to_owned(),
    334                 );
    335                 if !approved.contains(&authority) {
    336                     return Err(format!(
    337                         "{} contains unapproved Git source {url}",
    338                         path.display()
    339                     ));
    340                 }
    341                 seen.insert(authority);
    342             }
    343             for child in table.values() {
    344                 inspect_git_dependencies(child, path, approved, seen)?;
    345             }
    346         }
    347         toml::Value::Array(values) => {
    348             for child in values {
    349                 inspect_git_dependencies(child, path, approved, seen)?;
    350             }
    351         }
    352         _ => {}
    353     }
    354     Ok(())
    355 }
    356 
    357 fn validate_exceptions(root: &Path, contract: &Contract) -> Result<(), String> {
    358     let expected = BTreeSet::from([
    359         "CARGO-YANKED-SPIN-0.9.8".to_owned(),
    360         "RUSTSEC-2024-0384".to_owned(),
    361         "RUSTSEC-2024-0421".to_owned(),
    362     ]);
    363     let actual = contract
    364         .advisory_exception
    365         .iter()
    366         .map(|exception| exception.id.clone())
    367         .collect::<BTreeSet<_>>();
    368     if actual != expected || actual.len() != contract.advisory_exception.len() {
    369         return Err("supply-chain advisory exceptions are not the exact approved set".to_owned());
    370     }
    371     for exception in &contract.advisory_exception {
    372         if exception.package.is_empty()
    373             || exception.affected_version.is_empty()
    374             || exception.introduced_by.is_empty()
    375             || exception.classification.is_empty()
    376             || exception.mitigation.is_empty()
    377             || exception.remove_when.is_empty()
    378         {
    379             return Err(format!("advisory exception {} is incomplete", exception.id));
    380         }
    381         let exact = match exception.id.as_str() {
    382             "RUSTSEC-2024-0384" => {
    383                 exception.package == "instant"
    384                     && exception.affected_version == "0.1.13"
    385                     && exception.classification == "unmaintained"
    386                     && exception.remove_when == "nostr >=0.45.0 stable"
    387             }
    388             "RUSTSEC-2024-0421" => {
    389                 exception.package == "idna"
    390                     && exception.affected_version == "0.5.0"
    391                     && exception.classification == "vulnerability"
    392                     && exception.remove_when == "nostr >=0.45.0 stable"
    393             }
    394             "CARGO-YANKED-SPIN-0.9.8" => {
    395                 exception.package == "spin"
    396                     && exception.affected_version == "0.9.8"
    397                     && exception.classification == "yanked"
    398                     && exception.remove_when
    399                         == "sqlx no longer resolves flume 0.12.0 with spin 0.9.8"
    400             }
    401             _ => false,
    402         };
    403         if !exact {
    404             return Err(format!(
    405                 "advisory exception {} differs from its exact approved policy",
    406                 exception.id
    407             ));
    408         }
    409     }
    410 
    411     let lock_raw = fs::read_to_string(root.join("Cargo.lock"))
    412         .map_err(|error| format!("failed to read Cargo.lock: {error}"))?;
    413     let lock: toml::Value = toml::from_str(&lock_raw)
    414         .map_err(|error| format!("failed to parse Cargo.lock: {error}"))?;
    415     let locked_packages = lock
    416         .get("package")
    417         .and_then(toml::Value::as_array)
    418         .ok_or_else(|| "Cargo.lock contains no packages".to_owned())?;
    419     for exception in &contract.advisory_exception {
    420         let present = locked_packages.iter().any(|package| {
    421             package.get("name").and_then(toml::Value::as_str) == Some(exception.package.as_str())
    422                 && package.get("version").and_then(toml::Value::as_str)
    423                     == Some(exception.affected_version.as_str())
    424         });
    425         if !present {
    426             return Err(format!(
    427                 "advisory exception {} is stale because {} {} is absent from Cargo.lock",
    428                 exception.id, exception.package, exception.affected_version
    429             ));
    430         }
    431     }
    432     let patched_url_present = locked_packages.iter().any(|package| {
    433         package.get("name").and_then(toml::Value::as_str) == Some("url")
    434             && package
    435                 .get("version")
    436                 .and_then(toml::Value::as_str)
    437                 .and_then(|version| semver::Version::parse(version).ok())
    438                 .is_some_and(|version| version >= semver::Version::new(2, 5, 4))
    439     });
    440     if !patched_url_present {
    441         return Err("the IDNA exception requires url 2.5.4 or newer in Cargo.lock".to_owned());
    442     }
    443 
    444     let deny_raw = fs::read_to_string(root.join(DENY_PATH))
    445         .map_err(|error| format!("failed to read {DENY_PATH}: {error}"))?;
    446     let deny: toml::Value = toml::from_str(&deny_raw)
    447         .map_err(|error| format!("failed to parse {DENY_PATH}: {error}"))?;
    448     let ignored = deny
    449         .get("advisories")
    450         .and_then(|value| value.get("ignore"))
    451         .and_then(toml::Value::as_array)
    452         .ok_or_else(|| "deny.toml advisories.ignore is missing".to_owned())?
    453         .iter()
    454         .filter_map(toml::Value::as_str)
    455         .map(str::to_owned)
    456         .collect::<BTreeSet<_>>();
    457     let expected_ignored = expected
    458         .iter()
    459         .filter(|id| id.starts_with("RUSTSEC-"))
    460         .cloned()
    461         .collect::<BTreeSet<_>>();
    462     if ignored != expected_ignored {
    463         return Err("deny.toml advisory ignores differ from the governed exceptions".to_owned());
    464     }
    465 
    466     let relay_source = root.join("crates/transport_nostr/src/relay.rs");
    467     if relay_source.exists() {
    468         let source = fs::read_to_string(&relay_source)
    469             .map_err(|error| format!("failed to read {}: {error}", relay_source.display()))?;
    470         if !source.contains("Url::parse(canonical)") {
    471             return Err(
    472                 "the IDNA exception requires patched relay URL canonicalization".to_owned(),
    473             );
    474         }
    475     }
    476     Ok(())
    477 }
    478 
    479 fn verify_tools(contract: &Contract) -> Result<(), String> {
    480     verify_tool(
    481         &["deny", "--version"],
    482         "cargo-deny",
    483         &contract.tools.cargo_deny,
    484     )?;
    485     verify_tool(
    486         &["cyclonedx", "--version"],
    487         "cargo-cyclonedx",
    488         &contract.tools.cargo_cyclonedx,
    489     )?;
    490     verify_tool(
    491         &["vet", "--version"],
    492         "cargo-vet",
    493         &contract.tools.cargo_vet,
    494     )
    495 }
    496 
    497 fn verify_tool(args: &[&str], name: &str, expected: &str) -> Result<(), String> {
    498     let output = Command::new("cargo")
    499         .args(args)
    500         .output()
    501         .map_err(|error| format!("failed to start {name}: {error}"))?;
    502     if !output.status.success() {
    503         return Err(format!("{name} {expected} is required"));
    504     }
    505     let stdout = String::from_utf8_lossy(&output.stdout);
    506     let installed = stdout
    507         .split_whitespace()
    508         .find_map(|value| semver::Version::parse(value).ok())
    509         .ok_or_else(|| format!("could not parse {name} version: {stdout}"))?;
    510     let expected = semver::Version::parse(expected)
    511         .map_err(|error| format!("invalid governed {name} version: {error}"))?;
    512     if installed != expected {
    513         return Err(format!("{name} {expected} is required, found {installed}"));
    514     }
    515     Ok(())
    516 }
    517 
    518 fn load_metadata(root: &Path) -> Result<Metadata, String> {
    519     let output = Command::new("cargo")
    520         .args(["metadata", "--format-version", "1", "--locked", "--no-deps"])
    521         .current_dir(root)
    522         .output()
    523         .map_err(|error| format!("failed to start cargo metadata: {error}"))?;
    524     if !output.status.success() {
    525         return Err("locked cargo metadata failed".to_owned());
    526     }
    527     serde_json::from_slice(&output.stdout)
    528         .map_err(|error| format!("failed to parse cargo metadata: {error}"))
    529 }
    530 
    531 fn qualify_dependencies(root: &Path, contract: &Contract) -> Result<(), String> {
    532     run_command(
    533         root,
    534         "cargo",
    535         vec!["vet", "--locked"],
    536         "cargo-vet policy failed",
    537     )?;
    538     let mut saw_governed_yank = false;
    539     for package in &contract.package {
    540         let manifest = root.join(&package.manifest_path);
    541         let common = [
    542             "deny",
    543             "-L",
    544             "error",
    545             "--manifest-path",
    546             manifest
    547                 .to_str()
    548                 .ok_or_else(|| "non-UTF-8 package manifest path".to_owned())?,
    549             "--all-features",
    550             "--locked",
    551             "check",
    552         ];
    553         saw_governed_yank |= qualify_advisories(root, &manifest, &package.name)?;
    554         run_command(
    555             root,
    556             "cargo",
    557             common
    558                 .iter()
    559                 .copied()
    560                 .chain(["bans", "licenses", "sources"])
    561                 .collect::<Vec<_>>(),
    562             &format!("dependency policy failed for {}", package.name),
    563         )?;
    564     }
    565     if !saw_governed_yank {
    566         return Err("the governed spin 0.9.8 yank is stale and must be removed".to_owned());
    567     }
    568     Ok(())
    569 }
    570 
    571 fn qualify_advisories(root: &Path, manifest: &Path, package: &str) -> Result<bool, String> {
    572     let output = Command::new("cargo")
    573         .args([
    574             "deny",
    575             "--format",
    576             "json",
    577             "--log-level",
    578             "warn",
    579             "--manifest-path",
    580             manifest
    581                 .to_str()
    582                 .ok_or_else(|| "non-UTF-8 package manifest path".to_owned())?,
    583             "--all-features",
    584             "--locked",
    585             "check",
    586             "--allow",
    587             "advisory-not-detected",
    588             "advisories",
    589         ])
    590         .current_dir(root)
    591         .output()
    592         .map_err(|error| format!("failed to start cargo-deny: {error}"))?;
    593     let stdout = String::from_utf8_lossy(&output.stdout);
    594     let stderr = String::from_utf8_lossy(&output.stderr);
    595     if !output.status.success() {
    596         return Err(format!(
    597             "advisory qualification failed for {package}: {stdout}{stderr}"
    598         ));
    599     }
    600 
    601     let mut saw_governed_yank = false;
    602     for line in stdout.lines().chain(stderr.lines()) {
    603         let Ok(message) = serde_json::from_str::<Value>(line) else {
    604             continue;
    605         };
    606         if message.get("type").and_then(Value::as_str) != Some("diagnostic") {
    607             continue;
    608         }
    609         let fields = message
    610             .get("fields")
    611             .and_then(Value::as_object)
    612             .ok_or_else(|| "cargo-deny emitted a malformed diagnostic".to_owned())?;
    613         let code = fields
    614             .get("code")
    615             .and_then(Value::as_str)
    616             .unwrap_or_default();
    617         let krate = fields
    618             .get("graphs")
    619             .and_then(Value::as_array)
    620             .and_then(|graphs| graphs.first())
    621             .and_then(|graph| graph.get("Krate"));
    622         let exact_governed_yank = code == "yanked"
    623             && krate
    624                 .and_then(|krate| krate.get("name"))
    625                 .and_then(Value::as_str)
    626                 == Some("spin")
    627             && krate
    628                 .and_then(|krate| krate.get("version"))
    629                 .and_then(Value::as_str)
    630                 == Some("0.9.8");
    631         if exact_governed_yank {
    632             saw_governed_yank = true;
    633         } else {
    634             return Err(format!(
    635                 "unapproved cargo-deny diagnostic for {package}: {line}"
    636             ));
    637         }
    638     }
    639     Ok(saw_governed_yank)
    640 }
    641 
    642 fn qualify_sboms(
    643     root: &Path,
    644     contract: &Contract,
    645     metadata: &Metadata,
    646 ) -> Result<BTreeMap<String, String>, String> {
    647     let mut paths = metadata
    648         .packages
    649         .iter()
    650         .map(|package| {
    651             package
    652                 .manifest_path
    653                 .parent()
    654                 .expect("manifest has parent")
    655                 .join(SBOM_FILENAME)
    656         })
    657         .collect::<Vec<_>>();
    658     paths.sort();
    659     paths.dedup();
    660     if let Some(path) = paths.iter().find(|path| path.exists()) {
    661         return Err(format!(
    662             "refusing to overwrite pre-existing SBOM {}",
    663             path.display()
    664         ));
    665     }
    666     let _generated = GeneratedSboms(paths);
    667 
    668     let status = Command::new("cargo")
    669         .args([
    670             "cyclonedx",
    671             "--quiet",
    672             "--manifest-path",
    673             "Cargo.toml",
    674             "--format",
    675             &contract.sbom.format,
    676             "--all-features",
    677             "--target",
    678             &contract.sbom.target,
    679             "--spec-version",
    680             &contract.sbom.spec_version,
    681             "--license-strict",
    682             "--license-accept-named",
    683             "MIT/Apache-2.0",
    684             "--license-accept-named",
    685             "Apache-2.0/MIT",
    686             "--license-accept-named",
    687             "Apache-2.0 / MIT",
    688             "--override-filename",
    689             "radroots-release-v1-sbom",
    690         ])
    691         .env(
    692             "SOURCE_DATE_EPOCH",
    693             contract.sbom.source_date_epoch.to_string(),
    694         )
    695         .current_dir(root)
    696         .status()
    697         .map_err(|error| format!("failed to start cargo-cyclonedx: {error}"))?;
    698     if !status.success() {
    699         return Err("CycloneDX SBOM generation failed".to_owned());
    700     }
    701 
    702     let by_name = metadata
    703         .packages
    704         .iter()
    705         .map(|package| (package.name.as_str(), package))
    706         .collect::<BTreeMap<_, _>>();
    707     let mut hashes = BTreeMap::new();
    708     for package in &contract.package {
    709         let metadata_package = by_name
    710             .get(package.name.as_str())
    711             .ok_or_else(|| format!("cargo metadata omitted {}", package.name))?;
    712         if metadata_package.version != contract.package_version {
    713             return Err(format!("{} metadata version drifted", package.name));
    714         }
    715         let path = metadata_package
    716             .manifest_path
    717             .parent()
    718             .expect("manifest has parent")
    719             .join(SBOM_FILENAME);
    720         let raw = fs::read(&path)
    721             .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
    722         let mut sbom: Value = serde_json::from_slice(&raw)
    723             .map_err(|error| format!("invalid SBOM {}: {error}", path.display()))?;
    724         validate_sbom(&sbom, &package.name, &contract.package_version)?;
    725         normalize_sbom(&mut sbom, root);
    726         hashes.insert(
    727             package.name.clone(),
    728             sha256(&serde_json::to_vec(&sbom).map_err(|error| error.to_string())?),
    729         );
    730     }
    731     Ok(hashes)
    732 }
    733 
    734 fn validate_sbom(sbom: &Value, name: &str, version: &str) -> Result<(), String> {
    735     let component = sbom
    736         .pointer("/metadata/component")
    737         .and_then(Value::as_object)
    738         .ok_or_else(|| format!("{name} SBOM has no root component"))?;
    739     if sbom.get("bomFormat").and_then(Value::as_str) != Some("CycloneDX")
    740         || sbom.get("specVersion").and_then(Value::as_str) != Some("1.5")
    741         || component.get("name").and_then(Value::as_str) != Some(name)
    742         || component.get("version").and_then(Value::as_str) != Some(version)
    743         || sbom
    744             .get("components")
    745             .and_then(Value::as_array)
    746             .is_none_or(Vec::is_empty)
    747         || sbom
    748             .get("dependencies")
    749             .and_then(Value::as_array)
    750             .is_none_or(Vec::is_empty)
    751     {
    752         return Err(format!(
    753             "{name} SBOM is incomplete or identifies the wrong package"
    754         ));
    755     }
    756     Ok(())
    757 }
    758 
    759 fn normalize_sbom(value: &mut Value, root: &Path) {
    760     normalize_sbom_value(value, root.to_string_lossy().as_ref());
    761 }
    762 
    763 fn normalize_sbom_value(value: &mut Value, root: &str) {
    764     match value {
    765         Value::Object(object) => {
    766             object.remove("serialNumber");
    767             for value in object.values_mut() {
    768                 normalize_sbom_value(value, root);
    769             }
    770         }
    771         Value::Array(values) => {
    772             for value in values {
    773                 normalize_sbom_value(value, root);
    774             }
    775         }
    776         Value::String(string) if string.contains(root) => {
    777             *string = string.replace(root, "$REPOSITORY");
    778         }
    779         _ => {}
    780     }
    781 }
    782 
    783 fn build_provenance(
    784     root: &Path,
    785     contract: &Contract,
    786     sbom_hashes: &BTreeMap<String, String>,
    787 ) -> Result<Value, String> {
    788     let revision = command_stdout(root, "git", &["rev-parse", "HEAD"])?;
    789     if revision.len() != 40 || !revision.bytes().all(|byte| byte.is_ascii_hexdigit()) {
    790         return Err("Git provenance revision is not a full commit ID".to_owned());
    791     }
    792     let lock = fs::read(root.join("Cargo.lock"))
    793         .map_err(|error| format!("failed to read Cargo.lock: {error}"))?;
    794     let packages = contract
    795         .package
    796         .iter()
    797         .map(|package| {
    798             json!({
    799                 "name": package.name,
    800                 "version": contract.package_version,
    801                 "manifestPath": package.manifest_path,
    802                 "sbomSha256": sbom_hashes.get(&package.name),
    803             })
    804         })
    805         .collect::<Vec<_>>();
    806     Ok(json!({
    807         "schemaVersion": 1,
    808         "specId": contract.spec_id,
    809         "source": {
    810             "gitCommit": revision,
    811             "cargoLockSha256": sha256(&lock),
    812         },
    813         "tools": {
    814             "cargoDeny": contract.tools.cargo_deny,
    815             "cargoCyclonedx": contract.tools.cargo_cyclonedx,
    816         },
    817         "packages": packages,
    818         "advisoryExceptions": contract.advisory_exception,
    819     }))
    820 }
    821 
    822 fn validate_provenance(provenance: &Value, contract: &Contract) -> Result<(), String> {
    823     if provenance.get("schemaVersion").and_then(Value::as_u64) != Some(1)
    824         || provenance.get("specId").and_then(Value::as_str) != Some(contract.spec_id.as_str())
    825         || provenance
    826             .get("packages")
    827             .and_then(Value::as_array)
    828             .is_none_or(|packages| packages.len() != contract.package.len())
    829         || provenance
    830             .pointer("/source/cargoLockSha256")
    831             .and_then(Value::as_str)
    832             .is_none_or(|hash| hash.len() != 64)
    833     {
    834         return Err("generated supply-chain provenance is incomplete".to_owned());
    835     }
    836     Ok(())
    837 }
    838 
    839 fn run_command(root: &Path, program: &str, args: Vec<&str>, failure: &str) -> Result<(), String> {
    840     let status = Command::new(program)
    841         .args(args)
    842         .current_dir(root)
    843         .status()
    844         .map_err(|error| format!("failed to start {program}: {error}"))?;
    845     if status.success() {
    846         Ok(())
    847     } else {
    848         Err(failure.to_owned())
    849     }
    850 }
    851 
    852 fn command_stdout(root: &Path, program: &str, args: &[&str]) -> Result<String, String> {
    853     let output = Command::new(program)
    854         .args(args)
    855         .current_dir(root)
    856         .output()
    857         .map_err(|error| format!("failed to start {program}: {error}"))?;
    858     if !output.status.success() {
    859         return Err(format!("{program} {} failed", args.join(" ")));
    860     }
    861     String::from_utf8(output.stdout)
    862         .map(|value| value.trim().to_owned())
    863         .map_err(|error| format!("{program} emitted non-UTF-8 output: {error}"))
    864 }
    865 
    866 fn sha256(bytes: &[u8]) -> String {
    867     format!("{:x}", Sha256::digest(bytes))
    868 }
    869 
    870 #[cfg(test)]
    871 mod tests {
    872     use super::*;
    873 
    874     fn root() -> PathBuf {
    875         Path::new(env!("CARGO_MANIFEST_DIR"))
    876             .parent()
    877             .and_then(Path::parent)
    878             .expect("workspace root")
    879             .to_path_buf()
    880     }
    881 
    882     #[test]
    883     fn current_contract_is_exact_and_exception_bound() {
    884         let root = root();
    885         let contract = load(&root).expect("contract");
    886         let packages = crate::catalog::public_packages(&root).expect("catalog");
    887         validate(&root, &contract, packages.len()).expect("valid contract");
    888         qualify_git_sources(&root, &contract).expect("exact direct and transitive Git sources");
    889     }
    890 
    891     #[test]
    892     fn locked_git_sources_reject_substitution_unpinned_refs_and_missing_packages() {
    893         let root = root();
    894         let contract = load(&root).unwrap();
    895         let raw = fs::read_to_string(root.join("Cargo.lock")).unwrap();
    896         qualify_locked_git_sources(&raw, &contract.git_source).unwrap();
    897         for replacement in [
    898             "git+https://github.com/unapproved/nostr?rev=de3031aa99986eb29b3f34580355f9a099e4c927#de3031aa99986eb29b3f34580355f9a099e4c927",
    899             "git+https://github.com/nostrdevkit/nostr.git?branch=master#de3031aa99986eb29b3f34580355f9a099e4c927",
    900             "git+https://github.com/nostrdevkit/nostr.git?rev=de3031aa99986eb29b3f34580355f9a099e4c927#0000000000000000000000000000000000000000",
    901         ] {
    902             let mut lock: toml::Value = toml::from_str(&raw).unwrap();
    903             let package = lock["package"]
    904                 .as_array_mut()
    905                 .unwrap()
    906                 .iter_mut()
    907                 .find(|p| p["name"].as_str() == Some("nostr-sdk"))
    908                 .unwrap();
    909             package["source"] = replacement.into();
    910             assert!(
    911                 qualify_locked_git_sources(&toml::to_string(&lock).unwrap(), &contract.git_source)
    912                     .is_err()
    913             );
    914         }
    915         for name in ["async-utility", "nostr-sdk"] {
    916             let mut lock: toml::Value = toml::from_str(&raw).unwrap();
    917             lock["package"]
    918                 .as_array_mut()
    919                 .unwrap()
    920                 .retain(|p| p["name"].as_str() != Some(name));
    921             assert!(
    922                 qualify_locked_git_sources(&toml::to_string(&lock).unwrap(), &contract.git_source)
    923                     .is_err()
    924             );
    925         }
    926         let mut lock: toml::Value = toml::from_str(&raw).unwrap();
    927         let package = lock["package"]
    928             .as_array_mut()
    929             .unwrap()
    930             .iter_mut()
    931             .find(|p| p["name"].as_str() == Some("async-utility"))
    932             .unwrap();
    933         package["name"] = "unapproved-package".into();
    934         assert!(
    935             qualify_locked_git_sources(&toml::to_string(&lock).unwrap(), &contract.git_source)
    936                 .is_err()
    937         );
    938     }
    939 
    940     #[test]
    941     fn sbom_validation_rejects_wrong_identity() {
    942         let sbom = json!({
    943             "bomFormat": "CycloneDX",
    944             "specVersion": "1.5",
    945             "metadata": {"component": {"name": "wrong", "version": "0.1.0-alpha"}},
    946             "components": [{}],
    947             "dependencies": [{}],
    948         });
    949         assert!(validate_sbom(&sbom, "radroots_core", "0.1.0-alpha").is_err());
    950     }
    951 
    952     #[test]
    953     fn normalization_removes_random_and_absolute_identity() {
    954         let mut sbom = json!({
    955             "serialNumber": "urn:uuid:random",
    956             "path": "/workspace/crate",
    957         });
    958         normalize_sbom(&mut sbom, Path::new("/workspace"));
    959         assert!(sbom.get("serialNumber").is_none());
    960         assert_eq!(
    961             sbom.get("path").and_then(Value::as_str),
    962             Some("$REPOSITORY/crate")
    963         );
    964     }
    965 }