lib

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

package_boundary.rs (10521B)


      1 use std::{collections::BTreeSet, fs, path::Path};
      2 
      3 #[allow(unused_imports)]
      4 use radroots_signing::{
      5     Actor, Error, SignReceipt, SignRequest, Signer, SignerStatus, actor as _, authorization as _,
      6     capability as _, error as _, identity as _, receipt as _, recovery as _, request as _,
      7     signer as _, status as _,
      8 };
      9 
     10 const MANIFEST: &str = include_str!("../Cargo.toml");
     11 const EXAMPLE: &str = include_str!("../examples/host_signer.rs");
     12 const PUBLIC_API: &str = include_str!("../../../contracts/api_baselines/radroots_signing.txt");
     13 const README: &str = include_str!("../README.md");
     14 const ROOT: &str = include_str!("../src/lib.rs");
     15 
     16 #[test]
     17 fn manifest_has_final_identity_features_and_dependencies() {
     18     for required in [
     19         "name = \"radroots_signing\"",
     20         "version = \"0.1.0-alpha\"",
     21         "publish = [\"crates-io\"]",
     22         "default = [\"std\", \"serde\"]",
     23         "artifacts = [\"radroots_protocol/chat\", \"radroots_protocol/listing\"]",
     24         "radroots_domain = { workspace = true, default-features = false }",
     25         "radroots_event = { workspace = true, default-features = false }",
     26         "radroots_event_codec = { workspace = true, default-features = false }",
     27         "radroots_identity = { workspace = true, default-features = false }",
     28         "radroots_protocol = { workspace = true, default-features = false, features = [\"nip01\", \"intent\"] }",
     29     ] {
     30         assert!(
     31             MANIFEST.contains(required),
     32             "manifest is missing {required}"
     33         );
     34     }
     35     assert_eq!(
     36         table_keys(MANIFEST, "[features]"),
     37         BTreeSet::from(["artifacts", "chat", "commerce", "default", "serde", "std"])
     38     );
     39     assert_eq!(
     40         table_keys(MANIFEST, "[dependencies]"),
     41         BTreeSet::from([
     42             "hex",
     43             "radroots_domain",
     44             "radroots_event",
     45             "radroots_event_codec",
     46             "radroots_identity",
     47             "radroots_protocol",
     48             "serde",
     49             "sha2",
     50             "zeroize",
     51         ])
     52     );
     53     assert_eq!(
     54         table_keys(MANIFEST, "[dev-dependencies]"),
     55         BTreeSet::from(["nostr", "radroots_blossom", "serde_json"])
     56     );
     57     for forbidden in [
     58         "async-trait",
     59         "keyring",
     60         "nostr",
     61         "nostr-sdk",
     62         "reqwest",
     63         "sqlx",
     64         "tokio",
     65     ] {
     66         assert!(
     67             !table_keys(MANIFEST, "[dependencies]").contains(forbidden),
     68             "signing runtime must not depend on {forbidden}"
     69         );
     70     }
     71 }
     72 
     73 #[test]
     74 fn crate_root_declares_the_approved_module_skeleton() {
     75     assert!(ROOT.contains("#![cfg_attr(not(feature = \"std\"), no_std)]"));
     76     for module in [
     77         "actor",
     78         "authorization",
     79         "capability",
     80         "commerce",
     81         "error",
     82         "host",
     83         "identity",
     84         "issuance",
     85         "provider",
     86         "recovery",
     87         "request",
     88         "receipt",
     89         "signer",
     90         "status",
     91     ] {
     92         let declaration = format!("pub mod {module};");
     93         assert!(
     94             ROOT.contains(&declaration),
     95             "crate root is missing {module}"
     96         );
     97     }
     98     assert_eq!(
     99         root_declarations("pub mod "),
    100         BTreeSet::from([
    101             "actor",
    102             "authorization",
    103             "capability",
    104             "commerce",
    105             "error",
    106             "host",
    107             "identity",
    108             "issuance",
    109             "provider",
    110             "receipt",
    111             "recovery",
    112             "request",
    113             "signer",
    114             "status",
    115         ])
    116     );
    117     let _ = core::mem::size_of::<Actor>();
    118     let _ = core::mem::size_of::<SignRequest>();
    119     let _ = core::mem::size_of::<SignReceipt>();
    120     let _ = core::mem::size_of::<SignerStatus>();
    121     let _ = core::mem::size_of::<Error>();
    122     fn assert_object_safe(_: &dyn Signer) {}
    123     let _ = assert_object_safe;
    124     for root_export in [
    125         "pub use actor::Actor;",
    126         "pub use authorization::{CurrentAuthoringAuthority, CurrentAuthoringDecision};",
    127         "pub use error::Error;",
    128         "pub use identity::{AuthoredArtifactId, SignerRequestId, SigningIntentId, SigningOperationId};",
    129         "pub use receipt::{AuthoredSignEvidence, SignReceipt};",
    130         "pub use request::{SignRequest, SigningPurpose};",
    131         "pub use signer::Signer;",
    132         "pub use status::SignerStatus;",
    133     ] {
    134         assert!(ROOT.contains(root_export), "missing {root_export}");
    135     }
    136     assert_eq!(
    137         ROOT.lines()
    138             .map(str::trim)
    139             .filter(|line| line.starts_with("pub use "))
    140             .collect::<BTreeSet<_>>(),
    141         BTreeSet::from([
    142             "pub use actor::Actor;",
    143             "pub use authorization::{CurrentAuthoringAuthority, CurrentAuthoringDecision};",
    144             "pub use error::Error;",
    145             "pub use identity::{AuthoredArtifactId, SignerRequestId, SigningIntentId, SigningOperationId};",
    146             "pub use receipt::{AuthoredSignEvidence, SignReceipt};",
    147             "pub use request::{SignRequest, SigningPurpose};",
    148             "pub use signer::Signer;",
    149             "pub use status::SignerStatus;",
    150         ])
    151     );
    152     assert!(!ROOT.contains("prelude"));
    153 }
    154 
    155 #[test]
    156 fn package_documentation_and_reviewed_api_baseline_are_complete() {
    157     for required in [
    158         "## Typical flow",
    159         "## Host SPI contract",
    160         "## Deadlines, cancellation, and commit points",
    161         "## Serialization contract",
    162         "## Security and side effects",
    163         "## Features",
    164         "## Intended consumers",
    165         "radroots_crates_release_v1.toml",
    166         "examples/host_signer.rs",
    167     ] {
    168         assert!(README.contains(required), "README is missing {required}");
    169     }
    170     for required in [
    171         "impl Signer for HostSigner",
    172         "fn status(&self) -> BoxFuture",
    173         "fn sign(&self, _request: SignRequest) -> BoxFuture",
    174         "let signer: &dyn Signer",
    175         "drop(future)",
    176     ] {
    177         assert!(EXAMPLE.contains(required), "example is missing {required}");
    178     }
    179     for required in [
    180         "pub mod radroots_signing::actor",
    181         "pub mod radroots_signing::capability",
    182         "pub mod radroots_signing::error",
    183         "pub mod radroots_signing::receipt",
    184         "pub mod radroots_signing::request",
    185         "pub mod radroots_signing::signer",
    186         "pub mod radroots_signing::status",
    187         "pub enum radroots_signing::request::SigningPurpose",
    188         "pub radroots_signing::request::SigningPurpose::BlossomUploadAuthorization",
    189         "pub trait radroots_signing::Signer",
    190     ] {
    191         assert!(
    192             PUBLIC_API.contains(required),
    193             "public API baseline is missing {required}"
    194         );
    195     }
    196 }
    197 
    198 #[test]
    199 fn every_public_module_has_crate_level_documentation() {
    200     let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    201     for module in [
    202         "actor",
    203         "authorization",
    204         "capability",
    205         "error",
    206         "host",
    207         "identity",
    208         "issuance",
    209         "provider",
    210         "recovery",
    211         "request",
    212         "receipt",
    213         "signer",
    214         "status",
    215     ] {
    216         let path = source_root.join(format!("{module}.rs"));
    217         let source = fs::read_to_string(&path).expect("read module source");
    218         assert!(
    219             source.starts_with("//! "),
    220             "public module {module} must start with module documentation"
    221         );
    222     }
    223 }
    224 
    225 #[test]
    226 fn production_sources_publish_only_the_approved_traits_and_no_host_stack() {
    227     let source_root = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
    228     let mut sources = Vec::new();
    229     collect_rust_sources(&source_root, &mut sources);
    230     assert!(!sources.is_empty());
    231     let mut public_traits = BTreeSet::new();
    232 
    233     for path in sources {
    234         let source = fs::read_to_string(&path).expect("read signing source");
    235         let production = source.split("\n#[cfg(test)]").next().unwrap_or(&source);
    236         for line in production.lines() {
    237             let trimmed = line.trim_start();
    238             if let Some(name) = trimmed
    239                 .strip_prefix("pub trait ")
    240                 .and_then(|rest| rest.split([':', '<', ' ']).next())
    241             {
    242                 public_traits.insert(name.to_owned());
    243             }
    244             for forbidden in [
    245                 "nostr::",
    246                 "nostr_sdk::",
    247                 "reqwest::",
    248                 "sqlx::",
    249                 "tokio::",
    250                 "keyring::",
    251                 "std::fs",
    252                 "std::path",
    253                 "SecretKey",
    254                 "PrivateKey",
    255             ] {
    256                 assert!(
    257                     !line.contains(forbidden),
    258                     "signing production source must not contain {forbidden}: {}: {trimmed}",
    259                     path.display()
    260                 );
    261             }
    262         }
    263     }
    264 
    265     assert_eq!(
    266         public_traits,
    267         [
    268             "CurrentAuthoringAuthority",
    269             "ExactIssuer",
    270             "HostBound",
    271             "NonceSource",
    272             "ParticipantProvider",
    273             "ProgressObserver",
    274             "Signer",
    275             "SignerCallbacks"
    276         ]
    277         .into_iter()
    278         .map(str::to_owned)
    279         .collect()
    280     );
    281 }
    282 
    283 fn table_keys<'a>(manifest: &'a str, heading: &str) -> BTreeSet<&'a str> {
    284     let table = manifest
    285         .split_once(heading)
    286         .unwrap_or_else(|| panic!("missing manifest table {heading}"))
    287         .1;
    288     table
    289         .lines()
    290         .skip(1)
    291         .take_while(|line| !line.trim_start().starts_with('['))
    292         .filter_map(|line| {
    293             let line = line.trim();
    294             (line
    295                 .bytes()
    296                 .next()
    297                 .is_some_and(|byte| byte.is_ascii_lowercase() || byte == b'_')
    298                 && !line.starts_with('#'))
    299             .then(|| line.split_once('=').map(|(key, _)| key.trim()))
    300             .flatten()
    301         })
    302         .collect()
    303 }
    304 
    305 fn root_declarations(prefix: &str) -> BTreeSet<&str> {
    306     ROOT.lines()
    307         .map(str::trim)
    308         .filter_map(|line| line.strip_prefix(prefix))
    309         .filter_map(|name| name.strip_suffix(';'))
    310         .collect()
    311 }
    312 
    313 fn collect_rust_sources(directory: &Path, paths: &mut Vec<std::path::PathBuf>) {
    314     for entry in fs::read_dir(directory).expect("read signing source directory") {
    315         let path = entry.expect("source directory entry").path();
    316         if path.is_dir() {
    317             collect_rust_sources(&path, paths);
    318         } else if path.extension().and_then(|value| value.to_str()) == Some("rs") {
    319             paths.push(path);
    320         }
    321     }
    322 }