lib

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

safety_qualification.rs (12809B)


      1 use std::collections::BTreeSet;
      2 use std::fs;
      3 use std::path::Path;
      4 use std::process::Command;
      5 
      6 use serde::Deserialize;
      7 
      8 const CONTRACT_PATH: &str = "contracts/releases/safety_matrix.toml";
      9 
     10 #[derive(Debug, Deserialize)]
     11 struct Contract {
     12     schema_version: u16,
     13     toolchain: String,
     14     miri_flags: Vec<String>,
     15     miri: Vec<MiriLane>,
     16     sanitizer: Vec<SanitizerLane>,
     17     exception: Vec<Exception>,
     18 }
     19 
     20 #[derive(Debug, Deserialize)]
     21 struct MiriLane {
     22     package: String,
     23     filter: String,
     24     authority: String,
     25 }
     26 
     27 #[derive(Debug, Deserialize)]
     28 struct SanitizerLane {
     29     kind: String,
     30     targets: Vec<String>,
     31     packages: Vec<String>,
     32     authority: String,
     33 }
     34 
     35 #[derive(Debug, Deserialize)]
     36 struct Exception {
     37     lane: String,
     38     targets: Vec<String>,
     39     owner: String,
     40     expires: String,
     41     reason: String,
     42 }
     43 
     44 #[derive(Debug, Deserialize)]
     45 struct Metadata {
     46     packages: Vec<MetadataPackage>,
     47 }
     48 
     49 #[derive(Debug, Deserialize)]
     50 struct MetadataPackage {
     51     name: String,
     52 }
     53 
     54 pub fn run(root: &Path) -> Result<(), String> {
     55     let contract = load(root)?;
     56     let packages = workspace_packages(root)?;
     57     validate(&contract, &packages)?;
     58     qualify_miri(root, &contract)?;
     59     qualify_sanitizers(root, &contract)?;
     60     Ok(())
     61 }
     62 
     63 fn load(root: &Path) -> Result<Contract, String> {
     64     let path = root.join(CONTRACT_PATH);
     65     let raw = fs::read_to_string(&path)
     66         .map_err(|error| format!("failed to read {}: {error}", path.display()))?;
     67     toml::from_str(&raw).map_err(|error| format!("failed to parse {}: {error}", path.display()))
     68 }
     69 
     70 fn workspace_packages(root: &Path) -> Result<BTreeSet<String>, String> {
     71     let output = Command::new("cargo")
     72         .args(["metadata", "--format-version", "1", "--no-deps", "--locked"])
     73         .current_dir(root)
     74         .output()
     75         .map_err(|error| format!("failed to start cargo metadata: {error}"))?;
     76     if !output.status.success() {
     77         return Err("cargo metadata failed while validating the safety matrix".to_owned());
     78     }
     79     let metadata: Metadata = serde_json::from_slice(&output.stdout)
     80         .map_err(|error| format!("failed to decode cargo metadata: {error}"))?;
     81     Ok(metadata
     82         .packages
     83         .into_iter()
     84         .map(|package| package.name)
     85         .collect())
     86 }
     87 
     88 fn validate(contract: &Contract, packages: &BTreeSet<String>) -> Result<(), String> {
     89     if contract.schema_version != 1
     90         || !contract.toolchain.starts_with("nightly-")
     91         || contract.miri_flags != ["-Zmiri-strict-provenance", "-Zmiri-disable-isolation"]
     92         || contract.miri.len() != 8
     93         || contract.sanitizer.len() != 1
     94     {
     95         return Err("invalid safety qualification contract".to_owned());
     96     }
     97 
     98     let miri = contract
     99         .miri
    100         .iter()
    101         .map(|lane| (&lane.package, &lane.filter))
    102         .collect::<BTreeSet<_>>();
    103     if miri.len() != contract.miri.len() {
    104         return Err("Miri package/filter pairs must be unique".to_owned());
    105     }
    106     for lane in &contract.miri {
    107         validate_identifier("Miri package", &lane.package)?;
    108         validate_test_filter(&lane.filter)?;
    109         validate_authority(&lane.authority)?;
    110         if !packages.contains(&lane.package) {
    111             return Err(format!(
    112                 "Miri package {} is not in the workspace",
    113                 lane.package
    114             ));
    115         }
    116     }
    117 
    118     for lane in &contract.sanitizer {
    119         if lane.kind != "address" || lane.targets.len() != 4 || lane.packages.len() != 4 {
    120             return Err("native sanitizer authority must cover address checks on four hosts and four boundaries".to_owned());
    121         }
    122         validate_authority(&lane.authority)?;
    123         let targets = lane.targets.iter().collect::<BTreeSet<_>>();
    124         let lane_packages = lane.packages.iter().collect::<BTreeSet<_>>();
    125         if targets.len() != lane.targets.len() || lane_packages.len() != lane.packages.len() {
    126             return Err("sanitizer targets and packages must be unique".to_owned());
    127         }
    128         if targets
    129             .into_iter()
    130             .map(String::as_str)
    131             .collect::<BTreeSet<_>>()
    132             != BTreeSet::from([
    133                 "aarch64-apple-darwin",
    134                 "x86_64-apple-darwin",
    135                 "aarch64-unknown-linux-gnu",
    136                 "x86_64-unknown-linux-gnu",
    137             ])
    138             || lane_packages
    139                 .into_iter()
    140                 .map(String::as_str)
    141                 .collect::<BTreeSet<_>>()
    142                 != BTreeSet::from([
    143                     "radroots_ffi",
    144                     "radroots_sdk_ffi",
    145                     "radroots_storage_sqlite",
    146                     "radroots_runtime_manager",
    147                 ])
    148         {
    149             return Err(
    150                 "native sanitizer hosts and boundaries must match the exact governed inventory"
    151                     .to_owned(),
    152             );
    153         }
    154         for package in &lane.packages {
    155             validate_identifier("sanitizer package", package)?;
    156             if !packages.contains(package) {
    157                 return Err(format!(
    158                     "sanitizer package {package} is not in the workspace"
    159                 ));
    160             }
    161         }
    162     }
    163 
    164     if contract.exception.len() != 1 {
    165         return Err(
    166             "the unsupported sanitizer target authority must contain one bounded exception"
    167                 .to_owned(),
    168         );
    169     }
    170     let exception = &contract.exception[0];
    171     if exception.lane != "sanitizer"
    172         || exception.owner != "radroots-security"
    173         || exception.expires != "2026-10-01"
    174         || exception.targets.len() != 3
    175         || exception.reason.trim().is_empty()
    176     {
    177         return Err("invalid sanitizer target exception".to_owned());
    178     }
    179     Ok(())
    180 }
    181 
    182 fn validate_identifier(label: &str, value: &str) -> Result<(), String> {
    183     if value.is_empty()
    184         || !value
    185             .bytes()
    186             .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
    187     {
    188         return Err(format!("{label} must be a lowercase snake_case identifier"));
    189     }
    190     Ok(())
    191 }
    192 
    193 fn validate_test_filter(value: &str) -> Result<(), String> {
    194     let segments = value.split("::").collect::<Vec<_>>();
    195     if segments.len() < 3 {
    196         return Err("Miri filter must be a fully qualified test path".to_owned());
    197     }
    198     for segment in segments {
    199         validate_identifier("Miri test path segment", segment)?;
    200     }
    201     Ok(())
    202 }
    203 
    204 fn validate_authority(value: &str) -> Result<(), String> {
    205     if value.is_empty()
    206         || !value
    207             .bytes()
    208             .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
    209     {
    210         return Err("safety authority must be a lowercase kebab-case identifier".to_owned());
    211     }
    212     Ok(())
    213 }
    214 
    215 fn qualify_miri(root: &Path, contract: &Contract) -> Result<(), String> {
    216     let flags = contract.miri_flags.join(" ");
    217     for lane in &contract.miri {
    218         verify_test_exists(root, lane)?;
    219         let args = [
    220             format!("+{}", contract.toolchain),
    221             "miri".to_owned(),
    222             "test".to_owned(),
    223             "--locked".to_owned(),
    224             "-p".to_owned(),
    225             lane.package.clone(),
    226             "--lib".to_owned(),
    227             lane.filter.clone(),
    228             "--".to_owned(),
    229             "--exact".to_owned(),
    230         ];
    231         run_cargo(root, &args, &[("MIRIFLAGS", flags.as_str())], "Miri")?;
    232     }
    233     Ok(())
    234 }
    235 
    236 fn verify_test_exists(root: &Path, lane: &MiriLane) -> Result<(), String> {
    237     let args = [
    238         "test",
    239         "--locked",
    240         "-p",
    241         lane.package.as_str(),
    242         "--lib",
    243         lane.filter.as_str(),
    244         "--",
    245         "--exact",
    246         "--list",
    247     ];
    248     let output = Command::new("cargo")
    249         .args(args)
    250         .current_dir(root)
    251         .output()
    252         .map_err(|error| format!("failed to enumerate Miri test {}: {error}", lane.filter))?;
    253     if !output.status.success() {
    254         return Err(format!(
    255             "failed to enumerate Miri test {} in {}",
    256             lane.filter, lane.package
    257         ));
    258     }
    259     let stdout = String::from_utf8(output.stdout)
    260         .map_err(|error| format!("test enumeration emitted non-UTF-8 output: {error}"))?;
    261     let expected = format!("{}: test", lane.filter);
    262     if stdout.lines().any(|line| line == expected) {
    263         Ok(())
    264     } else {
    265         Err(format!(
    266             "Miri authority {} does not resolve to exactly one library test in {}",
    267             lane.filter, lane.package
    268         ))
    269     }
    270 }
    271 
    272 fn qualify_sanitizers(root: &Path, contract: &Contract) -> Result<(), String> {
    273     let host = rustc_host(root, &contract.toolchain)?;
    274     let mut matched = false;
    275     for lane in &contract.sanitizer {
    276         if !lane.targets.iter().any(|target| target == &host) {
    277             continue;
    278         }
    279         matched = true;
    280         let mut args = vec![
    281             format!("+{}", contract.toolchain),
    282             "test".to_owned(),
    283             "--locked".to_owned(),
    284             "--target".to_owned(),
    285             host.clone(),
    286         ];
    287         for package in &lane.packages {
    288             args.push("-p".to_owned());
    289             args.push(package.clone());
    290         }
    291         args.push("--lib".to_owned());
    292         let rustflags = format!("-Zsanitizer={}", lane.kind);
    293         run_cargo(
    294             root,
    295             &args,
    296             &[
    297                 ("RUSTFLAGS", rustflags.as_str()),
    298                 ("RUSTDOCFLAGS", rustflags.as_str()),
    299                 ("ASAN_OPTIONS", "detect_leaks=1:halt_on_error=1"),
    300             ],
    301             "sanitizer",
    302         )?;
    303     }
    304     if matched {
    305         return Ok(());
    306     }
    307     if contract
    308         .exception
    309         .iter()
    310         .any(|exception| exception.targets.iter().any(|target| target == &host))
    311     {
    312         eprintln!("sanitizer qualification excluded for governed target {host}");
    313         return Ok(());
    314     }
    315     Err(format!(
    316         "host {host} has neither a sanitizer lane nor a governed exception"
    317     ))
    318 }
    319 
    320 fn rustc_host(root: &Path, toolchain: &str) -> Result<String, String> {
    321     let output = Command::new("rustc")
    322         .args([format!("+{toolchain}"), "-vV".to_owned()])
    323         .current_dir(root)
    324         .output()
    325         .map_err(|error| format!("failed to start rustc: {error}"))?;
    326     if !output.status.success() {
    327         return Err(format!("rustc +{toolchain} -vV failed"));
    328     }
    329     let stdout = String::from_utf8(output.stdout)
    330         .map_err(|error| format!("rustc -vV emitted non-UTF-8 output: {error}"))?;
    331     stdout
    332         .lines()
    333         .find_map(|line| line.strip_prefix("host: ").map(str::to_owned))
    334         .ok_or_else(|| "rustc -vV did not report a host target".to_owned())
    335 }
    336 
    337 fn run_cargo(
    338     root: &Path,
    339     args: &[String],
    340     environment: &[(&str, &str)],
    341     label: &str,
    342 ) -> Result<(), String> {
    343     eprintln!("cargo {}", args.join(" "));
    344     let status = Command::new("cargo")
    345         .args(args)
    346         .envs(environment.iter().copied())
    347         .current_dir(root)
    348         .status()
    349         .map_err(|error| format!("failed to start {label} qualification: {error}"))?;
    350     if status.success() {
    351         Ok(())
    352     } else {
    353         Err(format!(
    354             "{label} qualification failed: cargo {}",
    355             args.join(" ")
    356         ))
    357     }
    358 }
    359 
    360 #[cfg(test)]
    361 mod tests {
    362     use super::{load, validate, workspace_packages};
    363 
    364     #[test]
    365     fn current_contract_covers_governed_safety_boundaries() {
    366         let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
    367             .parent()
    368             .and_then(std::path::Path::parent)
    369             .expect("workspace root");
    370         let packages = workspace_packages(root).expect("workspace packages");
    371         validate(&load(root).expect("contract"), &packages).expect("valid safety matrix");
    372     }
    373 
    374     #[test]
    375     fn sanitizer_inventory_refuses_missing_or_substituted_hosts_and_boundaries() {
    376         let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
    377             .parent()
    378             .and_then(std::path::Path::parent)
    379             .expect("workspace root");
    380         let packages = workspace_packages(root).expect("workspace packages");
    381         for replace in [false, true] {
    382             let mut contract = load(root).expect("contract");
    383             if replace {
    384                 contract.sanitizer[0].packages[0] = "radroots_core".to_owned();
    385             } else {
    386                 contract.sanitizer[0].packages.remove(0);
    387             }
    388             assert!(validate(&contract, &packages).is_err());
    389             let mut contract = load(root).expect("contract");
    390             if replace {
    391                 contract.sanitizer[0].targets[0] = "wasm32-unknown-unknown".to_owned();
    392             } else {
    393                 contract.sanitizer[0].targets.remove(0);
    394             }
    395             assert!(validate(&contract, &packages).is_err());
    396         }
    397     }
    398 }