From 6fd486b01682651b28473f0aafe39e50ac09326c Mon Sep 17 00:00:00 2001 From: aien Date: Mon, 21 Sep 2026 11:40:53 -0500 Subject: [PATCH] feat(harvester): close side-door exports, mandate signature verification, and fix CI sibling resolution --- .github/workflows/ci.yml | 15 ++- .gitignore | 1 + Cargo.lock | 1 + .../src/transformer_backend.rs | 6 +- crates/spark-harvester/Cargo.toml | 3 +- crates/spark-harvester/src/client.rs | 7 +- crates/spark-harvester/src/export.rs | 3 +- crates/spark-harvester/src/main.rs | 73 ++++++++++++- crates/spark-harvester/src/rights_gate.rs | 26 ++--- .../tests/rights_gating_tests.rs | 100 +++++++++++++++--- 10 files changed, 196 insertions(+), 39 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 174ede13..cefa763a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,17 @@ jobs: - name: Checkout Source uses: actions/checkout@v4 + - name: Checkout Sibling Protocols Dependency + uses: actions/checkout@v4 + with: + repository: aien-dev/aien-protocols + path: aien-protocols + + - name: Setup Sibling Dependencies + run: | + mkdir -p ../aien-protocols + cp -r aien-protocols/* ../aien-protocols/ + - name: Install Stable Rust Toolchain uses: dtolnay/rust-toolchain@stable with: @@ -33,7 +44,7 @@ jobs: run: cargo clippy --workspace --all-targets -- -D warnings - name: Run Workspace Unit and Integration Tests - run: cargo test --workspace --verbose + run: cargo test --workspace --verbose -- --test-threads=1 - name: Enforce Zero Disk Secrets Invariant run: | @@ -47,7 +58,7 @@ jobs: - name: Enforce Sovereign Voice and Anti-Slop Invariant run: | echo "Auditing repository for em dashes, en dashes, and formulaic tropes..." - BAD_CHARS=$(grep -rnE --exclude-dir=target --exclude-dir=.git --exclude="*.rs" --exclude="*.json" --exclude="*.safetensors" --exclude="FORGEJO_CI.md" "—|–" crates/ docs/ README.md || true) + BAD_CHARS=$(grep -rnE --exclude-dir=target --exclude-dir=.git --exclude-dir=aien-protocols --exclude="*.rs" --exclude="*.json" --exclude="*.safetensors" --exclude="FORGEJO_CI.md" "—|–" crates/ docs/ README.md || true) if [ -n "$BAD_CHARS" ]; then echo "::error::Em dashes or en dashes detected:" echo "$BAD_CHARS" diff --git a/.gitignore b/.gitignore index 036881fe..53239de3 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ __pycache__/ *.so receipt.json tests_results.json +aien-protocols/ diff --git a/Cargo.lock b/Cargo.lock index db461b1c..c69eea97 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3672,6 +3672,7 @@ dependencies = [ "bitflags 2.13.2", "chrono", "clap", + "hex", "p256", "regex", "reqwest 0.12.28", diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 2653e8f7..6a00c96f 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -284,7 +284,11 @@ impl NativeTransformerBackend { } /// Ingests multiple branch-specific delta tokens sequentially. - pub fn append_branch_tokens(&mut self, branch: BranchHandle, tokens: &[u32]) -> Result<(), String> { + pub fn append_branch_tokens( + &mut self, + branch: BranchHandle, + tokens: &[u32], + ) -> Result<(), String> { for &tok in tokens { self.append_branch_token(branch, tok)?; } diff --git a/crates/spark-harvester/Cargo.toml b/crates/spark-harvester/Cargo.toml index ec8e09e6..118b4332 100644 --- a/crates/spark-harvester/Cargo.toml +++ b/crates/spark-harvester/Cargo.toml @@ -20,7 +20,8 @@ regex = "1.10" sha2 = "0.10" thiserror = "1.0" bitflags = { version = "2.5", features = ["serde"] } -p256 = { version = "0.14.0", features = ["ecdsa"] } +p256 = { version = "0.14.0", features = ["ecdsa", "pem"] } +hex = "0.4" 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 3f6dc821..6fe80a4e 100644 --- a/crates/spark-harvester/src/client.rs +++ b/crates/spark-harvester/src/client.rs @@ -68,7 +68,7 @@ impl HarvesterClient { } } - pub async fn query_openai_compat( + pub(crate) async fn query_openai_compat( &self, endpoint_url: &str, api_key: &str, @@ -111,12 +111,17 @@ impl HarvesterClient { model: &str, prompt: &str, grant: &SourceGrant, + authority_verifying_key: &p256::ecdsa::VerifyingKey, ) -> Result { let now = chrono::Utc::now().timestamp() as u64; grant .verify_validity(now) .map_err(|e| ClientError::RightsDenied(e.to_string()))?; + grant + .verify_signature(authority_verifying_key) + .map_err(|e| ClientError::RightsDenied(e.to_string()))?; + grant .verify_permission(GrantPermissions::TRAIN | GrantPermissions::DISTILL) .or_else(|_| grant.verify_permission(GrantPermissions::EVALUATE)) diff --git a/crates/spark-harvester/src/export.rs b/crates/spark-harvester/src/export.rs index a2d0210c..18751400 100644 --- a/crates/spark-harvester/src/export.rs +++ b/crates/spark-harvester/src/export.rs @@ -7,7 +7,8 @@ use std::path::Path; pub struct DatasetExporter; impl DatasetExporter { - pub fn append_to_jsonl(path: &Path, pairs: &[ExtractedPair]) -> io::Result { + #[allow(dead_code)] + pub(crate) fn append_to_jsonl(path: &Path, pairs: &[ExtractedPair]) -> io::Result { let mut file = OpenOptions::new().create(true).append(true).open(path)?; let mut written = 0; diff --git a/crates/spark-harvester/src/main.rs b/crates/spark-harvester/src/main.rs index 69867c94..54e97f41 100644 --- a/crates/spark-harvester/src/main.rs +++ b/crates/spark-harvester/src/main.rs @@ -1,4 +1,5 @@ use clap::{Parser, Subcommand}; +use p256::pkcs8::DecodePublicKey; use std::path::PathBuf; use tracing::{info, Level}; use tracing_subscriber::FmtSubscriber; @@ -34,6 +35,12 @@ enum Commands { /// Inline JSON string of SourceGrant #[arg(long)] grant_json: Option, + /// Authority verifying key (hex-encoded SEC1 or PEM) + #[arg(long)] + authority_key: Option, + /// Path to PEM or SEC1 file containing authority verifying key + #[arg(long)] + authority_key_file: Option, /// Optional output path for gated bundle #[arg(short, long)] output: Option, @@ -51,6 +58,12 @@ enum Commands { /// Inline JSON string of SourceGrant #[arg(long)] grant_json: Option, + /// Authority verifying key (hex-encoded SEC1 or PEM) + #[arg(long)] + authority_key: Option, + /// Path to PEM or SEC1 file containing authority verifying key + #[arg(long)] + authority_key_file: Option, }, /// Display pipeline status Status, @@ -72,6 +85,51 @@ fn load_grant( } } +fn load_authority_key( + authority_key: Option<&str>, + authority_key_file: Option<&PathBuf>, +) -> Result> { + if let Some(path) = authority_key_file { + let content = std::fs::read_to_string(path)?; + let trimmed = content.trim(); + if trimmed.starts_with("-----BEGIN") { + let vk = p256::ecdsa::VerifyingKey::from_public_key_pem(trimmed)?; + return Ok(vk); + } + if let Ok(bytes) = hex::decode(trimmed) { + let vk = p256::ecdsa::VerifyingKey::from_sec1_bytes(&bytes)?; + return Ok(vk); + } + let raw = std::fs::read(path)?; + let vk = p256::ecdsa::VerifyingKey::from_sec1_bytes(&raw)?; + return Ok(vk); + } + if let Some(k) = authority_key { + let trimmed = k.trim(); + if trimmed.starts_with("-----BEGIN") { + let vk = p256::ecdsa::VerifyingKey::from_public_key_pem(trimmed)?; + return Ok(vk); + } + let bytes = hex::decode(trimmed)?; + let vk = p256::ecdsa::VerifyingKey::from_sec1_bytes(&bytes)?; + return Ok(vk); + } + if let Ok(vault_val) = + spark_harvester::HarvesterClient::resolve_vault_key("ATLAS_AUTHORITY_PUBKEY") + { + let trimmed = vault_val.trim(); + if trimmed.starts_with("-----BEGIN") { + let vk = p256::ecdsa::VerifyingKey::from_public_key_pem(trimmed)?; + return Ok(vk); + } + if let Ok(bytes) = hex::decode(trimmed) { + let vk = p256::ecdsa::VerifyingKey::from_sec1_bytes(&bytes)?; + return Ok(vk); + } + } + Err("Authority verifying key required: pass --authority-key , --authority-key-file , or register ATLAS_AUTHORITY_PUBKEY in atlas-vault.".into()) +} + fn parse_bundle_kind(s: &str) -> Result { match s.to_lowercase().as_str() { "training" => Ok(BundleKind::Training), @@ -108,10 +166,14 @@ async fn main() -> Result<(), Box> { model, grant_file, grant_json, + authority_key, + authority_key_file, output, bundle_kind, } => { let grant = load_grant(grant_file.as_ref(), grant_json.as_deref())?; + let authority_vk = + load_authority_key(authority_key.as_deref(), authority_key_file.as_ref())?; let kind = parse_bundle_kind(&bundle_kind)?; let extractor = ReasoningExtractor::new(); @@ -126,6 +188,7 @@ async fn main() -> Result<(), Box> { &[pair], kind, DEFAULT_ALLOWED_LICENSES, + &authority_vk, )?; info!( "RightsGate accepted bundle: ID={}, MerkleRoot={:?}", @@ -143,8 +206,12 @@ async fn main() -> Result<(), Box> { output, grant_file, grant_json, + authority_key, + authority_key_file, } => { let grant = load_grant(grant_file.as_ref(), grant_json.as_deref())?; + let authority_vk = + load_authority_key(authority_key.as_deref(), authority_key_file.as_ref())?; info!("Preparing distillation with SourceGrant {}", grant.grant_id); let sample_pair = ExtractedPair { @@ -162,10 +229,14 @@ async fn main() -> Result<(), Box> { &[sample_pair], BundleKind::Distillation, DEFAULT_ALLOWED_LICENSES, + &authority_vk, )?; let count = RightsGate::export_bundle(&bundle, &output)?; - info!("Appended {} verified rights-gated pairs to {:?}", count, output); + info!( + "Appended {} verified rights-gated pairs to {:?}", + count, output + ); } Commands::Status => { println!("AIEN Sovereign Harvester Pipeline Active"); diff --git a/crates/spark-harvester/src/rights_gate.rs b/crates/spark-harvester/src/rights_gate.rs index 583d4819..6edd023a 100644 --- a/crates/spark-harvester/src/rights_gate.rs +++ b/crates/spark-harvester/src/rights_gate.rs @@ -56,32 +56,20 @@ pub struct RightsGate; impl RightsGate { /// Validates an array of extracted pairs against a SourceGrant and builds an immutable GatedDatasetBundle. - /// Fails closed if the grant is expired, lacks required permissions, or contains an unapproved license. + /// Cryptographic signature verification against the authority verifying key is mandatory and fails closed. pub fn validate_and_bundle( grant: &SourceGrant, pairs: &[ExtractedPair], bundle_kind: BundleKind, allowed_licenses: &[&str], - ) -> Result { - 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>, + authority_verifying_key: &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)?; - } + // 2. Mandatory cryptographic signature verification + grant.verify_signature(authority_verifying_key)?; // 3. Verify license compatibility grant.verify_license(allowed_licenses)?; @@ -195,11 +183,11 @@ impl RightsGate { let mut next = Vec::new(); for chunk in current.chunks(2) { let mut hasher = Sha256::new(); - hasher.update(&chunk[0].0); + hasher.update(chunk[0].0); if chunk.len() > 1 { - hasher.update(&chunk[1].0); + hasher.update(chunk[1].0); } else { - hasher.update(&chunk[0].0); + hasher.update(chunk[0].0); } next.push(Digest32(hasher.finalize().into())); } diff --git a/crates/spark-harvester/tests/rights_gating_tests.rs b/crates/spark-harvester/tests/rights_gating_tests.rs index 66d85ce0..21a7c51e 100644 --- a/crates/spark-harvester/tests/rights_gating_tests.rs +++ b/crates/spark-harvester/tests/rights_gating_tests.rs @@ -7,7 +7,9 @@ fn create_test_pair() -> ExtractedPair { ExtractedPair { prompt: "Explain copy-on-write paged attention".to_string(), reasoning: Some("Analyze memory refcounting and block sharing mechanics".to_string()), - completion: "CoW allocates physical pages only when divergent tokens are written to a shared block.".to_string(), + completion: + "CoW allocates physical pages only when divergent tokens are written to a shared block." + .to_string(), provider: "sovereign-lab".to_string(), model: "atlas-omni-reasoning".to_string(), token_count: 32, @@ -15,14 +17,22 @@ fn create_test_pair() -> ExtractedPair { } } +fn create_authority_keys() -> (SigningKey, p256::ecdsa::VerifyingKey) { + let signing_key = SigningKey::from_slice(&[42u8; 32]).expect("valid signing key"); + let verifying_key = *signing_key.verifying_key(); + (signing_key, verifying_key) +} + #[test] fn test_rights_gated_training_bundle_admitted_with_valid_grant() { - let grant = SourceGrant::new( + let (sk, vk) = create_authority_keys(); + let mut grant = SourceGrant::new( "https://hf.co/datasets/aien/sovereign-math".to_string(), "Apache-2.0".to_string(), GrantPermissions::TRAIN | GrantPermissions::DISTILL, "Atlas Rights Authority".to_string(), ); + grant.sign(&sk); let pairs = vec![create_test_pair()]; let bundle = RightsGate::validate_and_bundle( @@ -30,23 +40,57 @@ fn test_rights_gated_training_bundle_admitted_with_valid_grant() { &pairs, BundleKind::Training, &["Apache-2.0", "MIT", "SRCL-1.0"], + &vk, ) - .expect("Valid training grant must be accepted"); + .expect("Valid signed training grant must be accepted"); assert_eq!(bundle.bundle_kind, BundleKind::Training); assert_eq!(bundle.records.len(), 1); assert_ne!(bundle.merkle_root, aien_protocol_types::Digest32::ZERO); - assert_eq!(bundle.records[0].source_uri, "https://hf.co/datasets/aien/sovereign-math"); + assert_eq!( + bundle.records[0].source_uri, + "https://hf.co/datasets/aien/sovereign-math" + ); } #[test] -fn test_unapproved_license_rejected() { +fn test_unsigned_grant_rejected_fails_closed() { + let (_sk, vk) = create_authority_keys(); let grant = SourceGrant::new( + "https://hf.co/datasets/aien/unsigned-dataset".to_string(), + "Apache-2.0".to_string(), + GrantPermissions::TRAIN, + "Unauthenticated Issuer".to_string(), + ); + + let pairs = vec![create_test_pair()]; + let res = RightsGate::validate_and_bundle( + &grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + &vk, + ); + + match res { + Err(ProvenanceError::MissingSignature) => {} + other => panic!( + "Expected MissingSignature for unsigned grant, got {:?}", + other + ), + } +} + +#[test] +fn test_unapproved_license_rejected() { + let (sk, vk) = create_authority_keys(); + let mut grant = SourceGrant::new( "https://example.com/proprietary-dataset".to_string(), "CC-BY-NC-4.0".to_string(), GrantPermissions::TRAIN, "Untrusted Third Party".to_string(), ); + grant.sign(&sk); let pairs = vec![create_test_pair()]; let res = RightsGate::validate_and_bundle( @@ -54,6 +98,7 @@ fn test_unapproved_license_rejected() { &pairs, BundleKind::Training, &["Apache-2.0", "MIT", "SRCL-1.0"], + &vk, ); match res { @@ -66,12 +111,14 @@ fn test_unapproved_license_rejected() { #[test] fn test_missing_permission_rejected() { - let grant = SourceGrant::new( + let (sk, vk) = create_authority_keys(); + let mut grant = SourceGrant::new( "https://hf.co/datasets/aien/eval-set".to_string(), "MIT".to_string(), GrantPermissions::EVALUATE, // Only EVALUATE, not TRAIN "Atlas Rights Authority".to_string(), ); + grant.sign(&sk); let pairs = vec![create_test_pair()]; let res = RightsGate::validate_and_bundle( @@ -79,6 +126,7 @@ fn test_missing_permission_rejected() { &pairs, BundleKind::Training, &["Apache-2.0", "MIT", "SRCL-1.0"], + &vk, ); match res { @@ -92,6 +140,7 @@ fn test_missing_permission_rejected() { #[test] fn test_expired_grant_rejected() { + let (sk, vk) = create_authority_keys(); let mut grant = SourceGrant::new( "https://hf.co/datasets/aien/expired-set".to_string(), "MIT".to_string(), @@ -99,6 +148,7 @@ fn test_expired_grant_rejected() { "Atlas Rights Authority".to_string(), ); grant.expires_at_epoch_sec = Some(1000); // Far in the past + grant.sign(&sk); let pairs = vec![create_test_pair()]; let res = RightsGate::validate_and_bundle( @@ -106,6 +156,7 @@ fn test_expired_grant_rejected() { &pairs, BundleKind::Training, &["Apache-2.0", "MIT", "SRCL-1.0"], + &vk, ); match res { @@ -130,12 +181,12 @@ fn test_cryptographic_signature_verification() { grant.sign(&signing_key); let pairs = vec![create_test_pair()]; - let bundle = RightsGate::validate_and_bundle_with_key( + let bundle = RightsGate::validate_and_bundle( &grant, &pairs, BundleKind::Training, &["Apache-2.0", "MIT", "SRCL-1.0"], - Some(&verifying_key), + &verifying_key, ) .expect("Signed grant must be accepted"); assert_eq!(bundle.records.len(), 1); @@ -143,27 +194,47 @@ fn test_cryptographic_signature_verification() { // 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( + let tamper_res = RightsGate::validate_and_bundle( &tampered_grant, &pairs, BundleKind::Training, &["Apache-2.0", "MIT", "SRCL-1.0"], - Some(&verifying_key), + &verifying_key, ); match tamper_res { Err(ProvenanceError::SignatureVerificationFailed(_)) => {} other => panic!("Expected SignatureVerificationFailed, got {:?}", other), } + + // Wrong authority key fails signature verification + let wrong_signing_key = SigningKey::from_slice(&[99u8; 32]).unwrap(); + let wrong_verifying_key = *wrong_signing_key.verifying_key(); + let wrong_key_res = RightsGate::validate_and_bundle( + &grant, + &pairs, + BundleKind::Training, + &["Apache-2.0", "MIT", "SRCL-1.0"], + &wrong_verifying_key, + ); + match wrong_key_res { + Err(ProvenanceError::SignatureVerificationFailed(_)) => {} + other => panic!( + "Expected SignatureVerificationFailed with wrong key, got {:?}", + other + ), + } } #[test] fn test_evidence_bundle_quarantine_enforced() { - let grant = SourceGrant::new( + let (sk, vk) = create_authority_keys(); + let mut grant = SourceGrant::new( "https://hf.co/datasets/aien/benchmark-evidence".to_string(), "MIT".to_string(), GrantPermissions::EVALUATE, "Atlas Rights Authority".to_string(), ); + grant.sign(&sk); let pairs = vec![create_test_pair()]; let bundle = RightsGate::validate_and_bundle( @@ -171,6 +242,7 @@ fn test_evidence_bundle_quarantine_enforced() { &pairs, BundleKind::Evidence, &["Apache-2.0", "MIT", "SRCL-1.0"], + &vk, ) .expect("Evidence grant must be accepted"); @@ -196,14 +268,16 @@ fn test_evidence_bundle_quarantine_enforced() { // 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"); + 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"); + let q_count = + RightsGate::export_bundle(&bundle, &q_path).expect("Quarantine export must succeed"); assert_eq!(q_count, 1); assert!(q_path.exists()); }