lib

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

package_boundary.rs (6267B)


      1 use std::collections::BTreeSet;
      2 use std::fs;
      3 use std::path::{Path, PathBuf};
      4 
      5 const MANIFEST: &str = include_str!("../Cargo.toml");
      6 const ROOT: &str = include_str!("../src/lib.rs");
      7 const README: &str = include_str!("../README.md");
      8 const EXAMPLE: &str = include_str!("../examples/explicit_memory_provider.rs");
      9 
     10 #[test]
     11 fn manifest_has_final_identity_features_and_no_radroots_dependencies() {
     12     for required in [
     13         "name = \"radroots_secrets\"",
     14         "version = \"0.1.0-alpha\"",
     15         "publish = [\"crates-io\"]",
     16         "documentation = \"https://docs.rs/radroots_secrets\"",
     17         "[lib]\nname = \"radroots_secrets\"",
     18         "default = [\"std\", \"serde\"]",
     19         "memory = [\"std\"]",
     20         "file = [\"std\", \"dep:tempfile\"]",
     21         "keyring = [\"std\", \"dep:keyring\"]",
     22     ] {
     23         assert!(
     24             MANIFEST.contains(required),
     25             "manifest is missing `{required}`"
     26         );
     27     }
     28 
     29     assert_eq!(
     30         table_keys(MANIFEST, "[features]"),
     31         BTreeSet::from([
     32             "browser", "default", "file", "keyring", "memory", "serde", "std"
     33         ])
     34     );
     35     assert!(
     36         table_keys(MANIFEST, "[dependencies]")
     37             .into_iter()
     38             .all(|dependency| !dependency.starts_with("radroots_")),
     39         "security SPI must not depend on another Radroots package"
     40     );
     41     assert_eq!(
     42         table_keys(MANIFEST, "[dependencies]"),
     43         BTreeSet::from([
     44             "chacha20poly1305",
     45             "keyring",
     46             "serde",
     47             "sha2",
     48             "subtle",
     49             "tempfile",
     50             "zeroize"
     51         ])
     52     );
     53     assert_eq!(
     54         table_keys(MANIFEST, "[dev-dependencies]"),
     55         BTreeSet::from(["futures-executor", "hex", "serde_json"])
     56     );
     57     assert_eq!(
     58         table_keys(
     59             MANIFEST,
     60             "[target.'cfg(target_arch = \"wasm32\")'.dependencies]"
     61         ),
     62         BTreeSet::from([
     63             "futures",
     64             "js-sys",
     65             "wasm-bindgen",
     66             "wasm-bindgen-futures",
     67             "web-sys"
     68         ])
     69     );
     70     assert!(ROOT.contains(
     71         "#[cfg(all(feature = \"browser\", target_arch = \"wasm32\"))]\npub mod browser;"
     72     ));
     73 }
     74 
     75 #[test]
     76 fn production_sources_publish_only_the_approved_traits() {
     77     let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
     78     let mut paths = Vec::new();
     79     collect_rust_sources(&source_root, &mut paths);
     80     let mut public_traits = BTreeSet::new();
     81 
     82     for path in paths {
     83         let source = fs::read_to_string(&path).expect("read secrets source");
     84         let production = source.split("\n#[cfg(test)]").next().unwrap_or(&source);
     85         for line in production.lines() {
     86             if let Some(name) = line
     87                 .trim_start()
     88                 .strip_prefix("pub trait ")
     89                 .and_then(|rest| rest.split([':', '<', ' ']).next())
     90             {
     91                 public_traits.insert(name.to_owned());
     92             }
     93         }
     94     }
     95 
     96     assert_eq!(
     97         public_traits,
     98         ["HostBound", "KeyWrapping", "SecretProvider"]
     99             .into_iter()
    100             .map(str::to_owned)
    101             .collect()
    102     );
    103 }
    104 
    105 #[test]
    106 fn crate_root_contains_only_the_approved_module_skeleton() {
    107     assert!(ROOT.contains("#![cfg_attr(not(feature = \"std\"), no_std)]"));
    108     assert_eq!(
    109         declarations(ROOT, "pub mod "),
    110         BTreeSet::from([
    111             "browser", "context", "envelope", "error", "file", "id", "keyring", "memory",
    112             "provider", "wrapping",
    113         ])
    114     );
    115     assert_eq!(
    116         ROOT.lines()
    117             .map(str::trim)
    118             .filter(|line| line.starts_with("pub use "))
    119             .collect::<BTreeSet<_>>(),
    120         BTreeSet::from([
    121             "pub use envelope::EncryptedEnvelope;",
    122             "pub use error::Error;",
    123             "pub use id::{SecretId, SecretRef};",
    124             "pub use provider::SecretProvider;",
    125             "pub use wrapping::KeyWrapping;"
    126         ])
    127     );
    128 }
    129 
    130 #[test]
    131 fn package_documentation_covers_the_security_and_host_contract() {
    132     for required in [
    133         "## Canonical surface",
    134         "## Explicit provider and envelope flow",
    135         "## Features and supported targets",
    136         "## Security and serialization contract",
    137         "## Side effects, cancellation, and commit points",
    138         "## Intended consumers",
    139         "public API baseline",
    140         "implicit retry or fallback",
    141     ] {
    142         assert!(README.contains(required), "README is missing `{required}`");
    143     }
    144     assert!(ROOT.contains("#![doc = include_str!(\"../README.md\")]"));
    145     assert!(MANIFEST.contains("name = \"explicit_memory_provider\""));
    146     assert!(MANIFEST.contains("required-features = [\"memory\"]"));
    147     for required in [
    148         "MemoryProvider::new()",
    149         "provider.provision(",
    150         "EncryptedEnvelope::seal",
    151         "EncryptedEnvelope::decode",
    152         "decoded.open(&provider, &context)",
    153     ] {
    154         assert!(
    155             EXAMPLE.contains(required),
    156             "example is missing `{required}`"
    157         );
    158     }
    159 }
    160 
    161 fn table_keys<'a>(source: &'a str, table: &str) -> BTreeSet<&'a str> {
    162     let Some((_, body)) = source.split_once(table) else {
    163         return BTreeSet::new();
    164     };
    165     body.lines()
    166         .skip(1)
    167         .take_while(|line| !line.starts_with('['))
    168         .filter_map(|line| line.split_once('=').map(|(key, _)| key.trim()))
    169         .filter(|key| {
    170             !key.is_empty()
    171                 && key.chars().all(|character| {
    172                     character.is_ascii_alphanumeric() || matches!(character, '_' | '-')
    173                 })
    174         })
    175         .collect()
    176 }
    177 
    178 fn declarations<'a>(source: &'a str, prefix: &str) -> BTreeSet<&'a str> {
    179     source
    180         .lines()
    181         .map(str::trim)
    182         .filter_map(|line| line.strip_prefix(prefix))
    183         .filter_map(|line| line.strip_suffix(';'))
    184         .collect()
    185 }
    186 
    187 fn collect_rust_sources(root: &Path, paths: &mut Vec<PathBuf>) {
    188     for entry in fs::read_dir(root).expect("read source directory") {
    189         let path = entry.expect("source entry").path();
    190         if path.is_dir() {
    191             collect_rust_sources(&path, paths);
    192         } else if path.extension().and_then(|extension| extension.to_str()) == Some("rs") {
    193             paths.push(path);
    194         }
    195     }
    196 }