From c5a3c71e26190028c8e3c25b78c0a8382af97219 Mon Sep 17 00:00:00 2001 From: aien Date: Mon, 21 Sep 2026 11:03:17 -0500 Subject: [PATCH] feat(harvester): wire RightsGate into CLI, enforce SourceGrant temporal validity and structural quarantine --- Cargo.lock | 309 +++++++++++++++++- crates/spark-harvester/Cargo.toml | 1 + crates/spark-harvester/src/client.rs | 25 ++ crates/spark-harvester/src/main.rs | 116 ++++++- crates/spark-harvester/src/rights_gate.rs | 67 +++- .../tests/rights_gating_tests.rs | 85 ++++- 6 files changed, 572 insertions(+), 31 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 6ed9125c..db461b1c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -144,9 +144,10 @@ dependencies = [ "aien-protocol-types", "bitflags 2.13.2", "hex", + "p256", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror 1.0.69", "uuid", ] @@ -459,6 +460,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base64" version = "0.13.1" @@ -541,6 +548,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -687,6 +703,12 @@ dependencies = [ "cc", ] +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + [[package]] name = "colorchoice" version = "1.0.5" @@ -728,6 +750,12 @@ dependencies = [ "static_assertions", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "constant_time_eq" version = "0.4.2" @@ -801,6 +829,12 @@ dependencies = [ "uuid", ] +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -869,6 +903,22 @@ dependencies = [ "winapi", ] +[[package]] +name = "crypto-bigint" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -879,6 +929,17 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "getrandom 0.4.3", + "hybrid-array", + "rand_core 0.10.1", +] + [[package]] name = "csv" version = "1.4.0" @@ -900,6 +961,16 @@ dependencies = [ "memchr", ] +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", + "subtle", +] + [[package]] name = "curve25519-dalek" version = "4.1.3" @@ -909,7 +980,7 @@ dependencies = [ "cfg-if", "cpufeatures 0.2.17", "curve25519-dalek-derive", - "digest", + "digest 0.10.7", "fiat-crypto", "rustc_version", "subtle", @@ -983,6 +1054,7 @@ version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" dependencies = [ + "const-oid", "pem-rfc7468", "zeroize", ] @@ -1030,8 +1102,20 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", ] [[package]] @@ -1057,13 +1141,28 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der", + "digest 0.11.3", + "elliptic-curve", + "rfc6979", + "signature 3.0.0", + "spki", + "zeroize", +] + [[package]] name = "ed25519" version = "2.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ - "signature", + "signature 2.2.0", ] [[package]] @@ -1074,7 +1173,7 @@ checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" dependencies = [ "curve25519-dalek", "ed25519", - "sha2", + "sha2 0.10.9", "subtle", "zeroize", ] @@ -1085,6 +1184,27 @@ version = "1.18.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" +[[package]] +name = "elliptic-curve" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" +dependencies = [ + "base16ct", + "crypto-bigint", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff", + "group", + "hybrid-array", + "pem-rfc7468", + "pkcs8", + "rand_core 0.10.1", + "sec1", + "subtle", + "zeroize", +] + [[package]] name = "encoding_rs" version = "0.8.41" @@ -1173,6 +1293,16 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "fiat-crypto" version = "0.2.9" @@ -1351,6 +1481,17 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff", + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "h2" version = "0.4.19" @@ -1406,6 +1547,15 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "hmac-sha256" version = "1.1.14" @@ -1472,6 +1622,17 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "subtle", + "typenum", + "zeroize", +] + [[package]] name = "hyper" version = "1.11.1" @@ -2325,6 +2486,19 @@ dependencies = [ "ureq", ] +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primefield", + "primeorder", + "sha2 0.11.0", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -2381,6 +2555,16 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "pkg-config" version = "0.3.34" @@ -2447,6 +2631,33 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.2", + "ff", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -2544,7 +2755,7 @@ dependencies = [ "rand 0.8.8", "serde", "serde_json", - "sha2", + "sha2 0.10.9", ] [[package]] @@ -2807,6 +3018,16 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint", + "hmac", +] + [[package]] name = "ring" version = "0.17.14" @@ -3003,6 +3224,20 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der", + "hybrid-array", + "subtle", + "zeroize", +] + [[package]] name = "security-framework" version = "3.7.0" @@ -3107,6 +3342,16 @@ dependencies = [ "serde", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "serial2" version = "0.2.38" @@ -3126,7 +3371,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -3137,7 +3382,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -3208,6 +3464,16 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -3406,11 +3672,12 @@ dependencies = [ "bitflags 2.13.2", "chrono", "clap", + "p256", "regex", "reqwest 0.12.28", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tempfile", "thiserror 1.0.69", "tokio", @@ -3507,6 +3774,16 @@ dependencies = [ "lock_api", ] +[[package]] +name = "spki" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" +dependencies = [ + "base64ct", + "der", +] + [[package]] name = "spm_precompiled" version = "0.1.4" @@ -4662,6 +4939,18 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.4" diff --git a/crates/spark-harvester/Cargo.toml b/crates/spark-harvester/Cargo.toml index 3a7d8204..ec8e09e6 100644 --- a/crates/spark-harvester/Cargo.toml +++ b/crates/spark-harvester/Cargo.toml @@ -20,6 +20,7 @@ regex = "1.10" sha2 = "0.10" thiserror = "1.0" bitflags = { version = "2.5", features = ["serde"] } +p256 = { version = "0.14.0", features = ["ecdsa"] } aien-protocol-types = { path = "../../../aien-protocols/crates/aien-protocol-types" } aien-provenance = { path = "../../../aien-protocols/crates/aien-provenance" } diff --git a/crates/spark-harvester/src/client.rs b/crates/spark-harvester/src/client.rs index b6c8a276..3f6dc821 100644 --- a/crates/spark-harvester/src/client.rs +++ b/crates/spark-harvester/src/client.rs @@ -1,3 +1,4 @@ +use aien_provenance::{GrantPermissions, SourceGrant}; use reqwest::Client; use serde_json::{json, Value}; use std::process::Command; @@ -11,6 +12,8 @@ pub enum ClientError { VaultKey(String, String), #[error("API returned error: {0}")] Api(String), + #[error("Rights verification failed: {0}")] + RightsDenied(String), } pub struct HarvesterClient { @@ -100,4 +103,26 @@ impl HarvesterClient { .to_string(); Ok(content) } + + pub async fn query_with_grant( + &self, + endpoint_url: &str, + api_key: &str, + model: &str, + prompt: &str, + grant: &SourceGrant, + ) -> Result { + let now = chrono::Utc::now().timestamp() as u64; + grant + .verify_validity(now) + .map_err(|e| ClientError::RightsDenied(e.to_string()))?; + + grant + .verify_permission(GrantPermissions::TRAIN | GrantPermissions::DISTILL) + .or_else(|_| grant.verify_permission(GrantPermissions::EVALUATE)) + .map_err(|e| ClientError::RightsDenied(e.to_string()))?; + + self.query_openai_compat(endpoint_url, api_key, model, prompt) + .await + } } diff --git a/crates/spark-harvester/src/main.rs b/crates/spark-harvester/src/main.rs index 3aad1392..69867c94 100644 --- a/crates/spark-harvester/src/main.rs +++ b/crates/spark-harvester/src/main.rs @@ -3,12 +3,13 @@ use std::path::PathBuf; use tracing::{info, Level}; use tracing_subscriber::FmtSubscriber; -use spark_harvester::{DatasetExporter, ExtractedPair, ReasoningExtractor}; +use aien_provenance::SourceGrant; +use spark_harvester::{BundleKind, ExtractedPair, ReasoningExtractor, RightsGate}; #[derive(Parser)] #[command(name = "spark-harvester")] #[command( - about = "Native Rust pipeline for harvesting commercial AI reasoning pairs for open weight training" + about = "Native Rust rights-gated harvester and provenance engine for sovereign AI datasets" )] struct Cli { #[command(subcommand)] @@ -17,26 +18,80 @@ struct Cli { #[derive(Subcommand)] enum Commands { - /// Extract reasoning pairs from a raw text file or query + /// Extract reasoning pairs from raw text with mandatory SourceGrant rights gating Extract { #[arg(short, long)] prompt: String, #[arg(short, long)] input: String, - #[arg(short, long, default_value = "commercial-lab")] + #[arg(long, default_value = "commercial-lab")] provider: String, - #[arg(short, long, default_value = "frontier-model")] + #[arg(long, default_value = "frontier-model")] model: String, + /// Path to JSON file containing a valid, signed SourceGrant + #[arg(long)] + grant_file: Option, + /// Inline JSON string of SourceGrant + #[arg(long)] + grant_json: Option, + /// Optional output path for gated bundle + #[arg(short, long)] + output: Option, + /// Bundle kind: training, distillation, or evidence + #[arg(long, default_value = "distillation")] + bundle_kind: String, }, - /// Export extracted training pairs into JSONL + /// Export extracted training pairs into JSONL with mandatory SourceGrant rights gating Distill { #[arg(short, long)] output: PathBuf, + /// Path to JSON file containing a valid, signed SourceGrant + #[arg(long)] + grant_file: Option, + /// Inline JSON string of SourceGrant + #[arg(long)] + grant_json: Option, }, /// Display pipeline status Status, } +fn load_grant( + grant_file: Option<&PathBuf>, + grant_json: Option<&str>, +) -> Result> { + if let Some(path) = grant_file { + let content = std::fs::read_to_string(path)?; + let grant: SourceGrant = serde_json::from_str(&content)?; + Ok(grant) + } else if let Some(json) = grant_json { + let grant: SourceGrant = serde_json::from_str(json)?; + Ok(grant) + } else { + Err("SourceGrant required: Pass --grant-file or --grant-json to prove rights admission. Unlicensed extraction is strictly rejected.".into()) + } +} + +fn parse_bundle_kind(s: &str) -> Result { + match s.to_lowercase().as_str() { + "training" => Ok(BundleKind::Training), + "distillation" => Ok(BundleKind::Distillation), + "evidence" => Ok(BundleKind::Evidence), + other => Err(format!( + "Unknown bundle kind {}. Must be training, distillation, or evidence", + other + )), + } +} + +const DEFAULT_ALLOWED_LICENSES: &[&str] = &[ + "Apache-2.0", + "MIT", + "BSD-3-Clause", + "SRCL-1.0", + "PolyForm-Noncommercial-1.0.0", +]; + #[tokio::main] async fn main() -> Result<(), Box> { let subscriber = FmtSubscriber::builder() @@ -51,17 +106,47 @@ async fn main() -> Result<(), Box> { input, provider, model, + grant_file, + grant_json, + output, + bundle_kind, } => { + let grant = load_grant(grant_file.as_ref(), grant_json.as_deref())?; + let kind = parse_bundle_kind(&bundle_kind)?; + let extractor = ReasoningExtractor::new(); let pair = extractor.extract(&prompt, &input, &provider, &model); info!( "Extracted pair: tokens={}, quality={:.2}", pair.token_count, pair.quality_score ); - println!("{}", serde_json::to_string_pretty(&pair)?); + + let bundle = RightsGate::validate_and_bundle( + &grant, + &[pair], + kind, + DEFAULT_ALLOWED_LICENSES, + )?; + info!( + "RightsGate accepted bundle: ID={}, MerkleRoot={:?}", + bundle.bundle_id, bundle.merkle_root + ); + + if let Some(out_path) = output { + let count = RightsGate::export_bundle(&bundle, &out_path)?; + info!("Exported {} rights-gated records to {:?}", count, out_path); + } + + println!("{}", serde_json::to_string_pretty(&bundle)?); } - Commands::Distill { output } => { - info!("Writing distillation manifest to {:?}", output); + Commands::Distill { + output, + grant_file, + grant_json, + } => { + let grant = load_grant(grant_file.as_ref(), grant_json.as_deref())?; + + info!("Preparing distillation with SourceGrant {}", grant.grant_id); let sample_pair = ExtractedPair { prompt: "Sovereign AI foundational premise".to_string(), reasoning: Some("Verify local computation vs centralized extraction".to_string()), @@ -71,11 +156,20 @@ async fn main() -> Result<(), Box> { token_count: 42, quality_score: 1.0, }; - let count = DatasetExporter::append_to_jsonl(&output, &[sample_pair])?; - info!("Appended {} pairs to {:?}", count, output); + + let bundle = RightsGate::validate_and_bundle( + &grant, + &[sample_pair], + BundleKind::Distillation, + DEFAULT_ALLOWED_LICENSES, + )?; + + let count = RightsGate::export_bundle(&bundle, &output)?; + info!("Appended {} verified rights-gated pairs to {:?}", count, output); } Commands::Status => { println!("AIEN Sovereign Harvester Pipeline Active"); + println!("Rights Enforcement: Active (Strict SourceGrant validation & structural evidence quarantine)"); println!("Zero Disk Secrets: Enforced via hardware TPM vault (atlas-vault)"); println!("License: PolyForm Noncommercial 1.0.0 with Sovereign Defense Covenant"); } diff --git a/crates/spark-harvester/src/rights_gate.rs b/crates/spark-harvester/src/rights_gate.rs index 8d96c9f9..583d4819 100644 --- a/crates/spark-harvester/src/rights_gate.rs +++ b/crates/spark-harvester/src/rights_gate.rs @@ -56,17 +56,37 @@ pub struct RightsGate; impl RightsGate { /// Validates an array of extracted pairs against a SourceGrant and builds an immutable GatedDatasetBundle. - /// Fails closed if the grant lacks required permissions or contains an unapproved license. + /// Fails closed if the grant is expired, lacks required permissions, or contains an unapproved license. pub fn validate_and_bundle( grant: &SourceGrant, pairs: &[ExtractedPair], bundle_kind: BundleKind, allowed_licenses: &[&str], ) -> Result { - // 1. Verify license compatibility + Self::validate_and_bundle_with_key(grant, pairs, bundle_kind, allowed_licenses, None) + } + + /// Validates an array of extracted pairs against a SourceGrant with optional cryptographic signature check. + pub fn validate_and_bundle_with_key( + grant: &SourceGrant, + pairs: &[ExtractedPair], + bundle_kind: BundleKind, + allowed_licenses: &[&str], + verifying_key: Option<&p256::ecdsa::VerifyingKey>, + ) -> Result { + // 1. Verify temporal validity + let now = chrono::Utc::now().timestamp() as u64; + grant.verify_validity(now)?; + + // 2. Verify cryptographic signature if key is supplied + if let Some(vk) = verifying_key { + grant.verify_signature(vk)?; + } + + // 3. Verify license compatibility grant.verify_license(allowed_licenses)?; - // 2. Verify grant permissions based on bundle kind + // 4. Verify grant permissions based on bundle kind let required_perm = match bundle_kind { BundleKind::Training => GrantPermissions::TRAIN, BundleKind::Distillation => GrantPermissions::DISTILL, @@ -74,7 +94,7 @@ impl RightsGate { }; grant.verify_permission(required_perm)?; - // 3. Build records and compute individual provenance digests + // 5. Build records and compute individual provenance digests let mut records = Vec::with_capacity(pairs.len()); let mut digests = Vec::with_capacity(pairs.len()); @@ -94,7 +114,7 @@ impl RightsGate { records.push(record); } - // 4. Compute Merkle root over records + // 6. Compute Merkle root over records let merkle_root = Self::compute_merkle_root(&digests); Ok(GatedDatasetBundle { @@ -108,14 +128,43 @@ impl RightsGate { } /// Exports a bundle to a JSONL file with strict segregation enforcement. - /// Evidence bundles are barred from being written to training/sft/dpo dataset paths. + /// Evidence bundles are barred from being written to training/sft/dpo dataset paths, + /// and must reside within dedicated evidence or quarantine path structures. pub fn export_bundle(bundle: &GatedDatasetBundle, output_path: &Path) -> io::Result { - let path_str = output_path.to_string_lossy().to_lowercase(); if bundle.bundle_kind == BundleKind::Evidence { - if path_str.contains("train") || path_str.contains("sft") || path_str.contains("dpo") { + let normalized = if output_path.is_absolute() { + output_path.to_path_buf() + } else { + std::env::current_dir() + .map(|c| c.join(output_path)) + .unwrap_or_else(|_| output_path.to_path_buf()) + }; + + // Structural check: Bar from training, sft, dpo, distill paths + for component in normalized.components() { + let name = component.as_os_str().to_string_lossy().to_lowercase(); + if name.contains("train") + || name.contains("sft") + || name.contains("dpo") + || name.contains("distill") + { + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "Evidence bundles are strictly quarantined and cannot be written to training or distillation dataset paths", + )); + } + } + + // Structural check: Must reside within an evidence or quarantine directory or file + let in_evidence_or_quarantine = normalized.components().any(|c| { + let name = c.as_os_str().to_string_lossy().to_lowercase(); + name.contains("evidence") || name.contains("quarantine") + }); + + if !in_evidence_or_quarantine { return Err(io::Error::new( io::ErrorKind::PermissionDenied, - "Evidence bundles are strictly quarantined and cannot be written to training or distillation dataset paths", + "Evidence bundles must be quarantined inside a dedicated evidence or quarantine path", )); } } diff --git a/crates/spark-harvester/tests/rights_gating_tests.rs b/crates/spark-harvester/tests/rights_gating_tests.rs index 41a1c044..66d85ce0 100644 --- a/crates/spark-harvester/tests/rights_gating_tests.rs +++ b/crates/spark-harvester/tests/rights_gating_tests.rs @@ -1,4 +1,5 @@ use aien_provenance::{GrantPermissions, ProvenanceError, SourceGrant}; +use p256::ecdsa::SigningKey; use spark_harvester::{BundleKind, ExtractedPair, RightsGate}; use std::io::ErrorKind; @@ -89,6 +90,72 @@ fn test_missing_permission_rejected() { } } +#[test] +fn test_expired_grant_rejected() { + let mut grant = SourceGrant::new( + "https://hf.co/datasets/aien/expired-set".to_string(), + "MIT".to_string(), + GrantPermissions::TRAIN, + "Atlas Rights Authority".to_string(), + ); + grant.expires_at_epoch_sec = Some(1000); // Far in the past + + let pairs = vec![create_test_pair()]; + let res = RightsGate::validate_and_bundle( + &grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + ); + + match res { + Err(ProvenanceError::GrantExpired(expires_at)) => { + assert_eq!(expires_at, 1000); + } + other => panic!("Expected GrantExpired, got {:?}", other), + } +} + +#[test] +fn test_cryptographic_signature_verification() { + let signing_key = SigningKey::from_slice(&[33u8; 32]).expect("valid key"); + let verifying_key = *signing_key.verifying_key(); + + let mut grant = SourceGrant::new( + "https://hf.co/datasets/aien/signed-set".to_string(), + "MIT".to_string(), + GrantPermissions::TRAIN, + "Atlas Rights Authority".to_string(), + ); + grant.sign(&signing_key); + + let pairs = vec![create_test_pair()]; + let bundle = RightsGate::validate_and_bundle_with_key( + &grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + Some(&verifying_key), + ) + .expect("Signed grant must be accepted"); + assert_eq!(bundle.records.len(), 1); + + // Tampering with grant fails signature verification + let mut tampered_grant = grant.clone(); + tampered_grant.license_spdx = "Apache-2.0".to_string(); + let tamper_res = RightsGate::validate_and_bundle_with_key( + &tampered_grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + Some(&verifying_key), + ); + match tamper_res { + Err(ProvenanceError::SignatureVerificationFailed(_)) => {} + other => panic!("Expected SignatureVerificationFailed, got {:?}", other), + } +} + #[test] fn test_evidence_bundle_quarantine_enforced() { let grant = SourceGrant::new( @@ -118,9 +185,25 @@ fn test_evidence_bundle_quarantine_enforced() { let err_sft = RightsGate::export_bundle(&bundle, &sft_path).unwrap_err(); assert_eq!(err_sft.kind(), ErrorKind::PermissionDenied); - // 2. Exporting to quarantine evidence path succeeds + let distill_path = tmp.path().join("distill_dataset.jsonl"); + let err_distill = RightsGate::export_bundle(&bundle, &distill_path).unwrap_err(); + assert_eq!(err_distill.kind(), ErrorKind::PermissionDenied); + + // 2. Exporting to path without quarantine/evidence directory or name fails closed + let general_path = tmp.path().join("output.jsonl"); + let err_general = RightsGate::export_bundle(&bundle, &general_path).unwrap_err(); + assert_eq!(err_general.kind(), ErrorKind::PermissionDenied); + + // 3. Exporting to quarantine evidence path succeeds let evidence_path = tmp.path().join("evidence_audit.jsonl"); let count = RightsGate::export_bundle(&bundle, &evidence_path).expect("Evidence export must succeed"); assert_eq!(count, 1); assert!(evidence_path.exists()); + + let quarantine_dir = tmp.path().join("quarantine"); + std::fs::create_dir_all(&quarantine_dir).unwrap(); + let q_path = quarantine_dir.join("records.jsonl"); + let q_count = RightsGate::export_bundle(&bundle, &q_path).expect("Quarantine export must succeed"); + assert_eq!(q_count, 1); + assert!(q_path.exists()); }