aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / spark-harvester / src / rights_gate.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use crate::extractor::ExtractedPair; |
| 17 | use aien_protocol_types::Digest32; |
| 18 | use aien_provenance::{GrantPermissions, ProvenanceError, SourceGrant}; |
| 19 | use serde::{Deserialize, Serialize}; |
| 20 | use sha2::{Digest, Sha256}; |
| 21 | use std::fs::OpenOptions; |
| 22 | use std::io::{self, Write}; |
| 23 | use std::path::Path; |
| 24 | use uuid::Uuid; |
| 25 | |
| 26 | #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] |
| 27 | pub enum BundleKind { |
| 28 | Training, |
| 29 | Distillation, |
| 30 | Evidence, |
| 31 | } |
| 32 | |
| 33 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] |
| 34 | pub struct GatedDatasetRecord { |
| 35 | pub record_id: Uuid, |
| 36 | pub bundle_kind: BundleKind, |
| 37 | pub grant_id: Uuid, |
| 38 | pub source_uri: String, |
| 39 | pub license_spdx: String, |
| 40 | pub pair: ExtractedPair, |
| 41 | pub provenance_digest: Digest32, |
| 42 | } |
| 43 | |
| 44 | impl GatedDatasetRecord { |
| 45 | pub fn compute_digest(&self) -> Digest32 { |
| 46 | let mut hasher = Sha256::new(); |
| 47 | hasher.update(self.record_id.as_bytes()); |
| 48 | hasher.update(self.grant_id.as_bytes()); |
| 49 | hasher.update(self.source_uri.as_bytes()); |
| 50 | hasher.update(self.license_spdx.as_bytes()); |
| 51 | hasher.update(self.pair.prompt.as_bytes()); |
| 52 | hasher.update(self.pair.completion.as_bytes()); |
| 53 | if let Some(ref r) = self.pair.reasoning { |
| 54 | hasher.update(r.as_bytes()); |
| 55 | } |
| 56 | Digest32(hasher.finalize().into()) |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] |
| 61 | pub struct GatedDatasetBundle { |
| 62 | pub bundle_id: Uuid, |
| 63 | pub bundle_kind: BundleKind, |
| 64 | pub license_spdx: String, |
| 65 | pub records: Vec<GatedDatasetRecord>, |
| 66 | pub merkle_root: Digest32, |
| 67 | pub created_at: String, |
| 68 | } |
| 69 | |
| 70 | pub struct RightsGate; |
| 71 | |
| 72 | impl RightsGate { |
| 73 | /// Validates an array of extracted pairs against a SourceGrant and builds an immutable GatedDatasetBundle. |
| 74 | /// Cryptographic signature verification against the authority verifying key is mandatory and fails closed. |
| 75 | pub fn validate_and_bundle( |
| 76 | grant: &SourceGrant, |
| 77 | pairs: &[ExtractedPair], |
| 78 | bundle_kind: BundleKind, |
| 79 | allowed_licenses: &[&str], |
| 80 | authority_verifying_key: &p256::ecdsa::VerifyingKey, |
| 81 | ) -> Result<GatedDatasetBundle, ProvenanceError> { |
| 82 | // 1. Verify temporal validity |
| 83 | let now = chrono::Utc::now().timestamp() as u64; |
| 84 | grant.verify_validity(now)?; |
| 85 | |
| 86 | // 2. Mandatory cryptographic signature verification |
| 87 | grant.verify_signature(authority_verifying_key)?; |
| 88 | |
| 89 | // 3. Verify license compatibility |
| 90 | grant.verify_license(allowed_licenses)?; |
| 91 | |
| 92 | // 4. Verify grant permissions based on bundle kind |
| 93 | let required_perm = match bundle_kind { |
| 94 | BundleKind::Training => GrantPermissions::TRAIN, |
| 95 | BundleKind::Distillation => GrantPermissions::DISTILL, |
| 96 | BundleKind::Evidence => GrantPermissions::EVALUATE, |
| 97 | }; |
| 98 | grant.verify_permission(required_perm)?; |
| 99 | |
| 100 | // 5. Build records and compute individual provenance digests |
| 101 | let mut records = Vec::with_capacity(pairs.len()); |
| 102 | let mut digests = Vec::with_capacity(pairs.len()); |
| 103 | |
| 104 | for pair in pairs { |
| 105 | let record_id = Uuid::new_v4(); |
| 106 | let mut record = GatedDatasetRecord { |
| 107 | record_id, |
| 108 | bundle_kind, |
| 109 | grant_id: grant.grant_id, |
| 110 | source_uri: grant.source_uri.clone(), |
| 111 | license_spdx: grant.license_spdx.clone(), |
| 112 | pair: pair.clone(), |
| 113 | provenance_digest: Digest32::ZERO, |
| 114 | }; |
| 115 | record.provenance_digest = record.compute_digest(); |
| 116 | digests.push(record.provenance_digest); |
| 117 | records.push(record); |
| 118 | } |
| 119 | |
| 120 | // 6. Compute Merkle root over records |
| 121 | let merkle_root = Self::compute_merkle_root(&digests); |
| 122 | |
| 123 | Ok(GatedDatasetBundle { |
| 124 | bundle_id: Uuid::new_v4(), |
| 125 | bundle_kind, |
| 126 | license_spdx: grant.license_spdx.clone(), |
| 127 | records, |
| 128 | merkle_root, |
| 129 | created_at: chrono::Utc::now().to_rfc3339(), |
| 130 | }) |
| 131 | } |
| 132 | |
| 133 | /// Exports a bundle to a JSONL file with strict segregation enforcement. |
| 134 | /// Evidence bundles are barred from being written to training/sft/dpo dataset paths, |
| 135 | /// and must reside within dedicated evidence or quarantine path structures. |
| 136 | pub fn export_bundle(bundle: &GatedDatasetBundle, output_path: &Path) -> io::Result<usize> { |
| 137 | if bundle.bundle_kind == BundleKind::Evidence { |
| 138 | let normalized = if output_path.is_absolute() { |
| 139 | output_path.to_path_buf() |
| 140 | } else { |
| 141 | std::env::current_dir() |
| 142 | .map(|c| c.join(output_path)) |
| 143 | .unwrap_or_else(|_| output_path.to_path_buf()) |
| 144 | }; |
| 145 | |
| 146 | // Structural check: Bar from training, sft, dpo, distill paths |
| 147 | for component in normalized.components() { |
| 148 | let name = component.as_os_str().to_string_lossy().to_lowercase(); |
| 149 | if name.contains("train") |
| 150 | || name.contains("sft") |
| 151 | || name.contains("dpo") |
| 152 | || name.contains("distill") |
| 153 | { |
| 154 | return Err(io::Error::new( |
| 155 | io::ErrorKind::PermissionDenied, |
| 156 | "Evidence bundles are strictly quarantined and cannot be written to training or distillation dataset paths", |
| 157 | )); |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | // Structural check: Must reside within an evidence or quarantine directory or file |
| 162 | let in_evidence_or_quarantine = normalized.components().any(|c| { |
| 163 | let name = c.as_os_str().to_string_lossy().to_lowercase(); |
| 164 | name.contains("evidence") || name.contains("quarantine") |
| 165 | }); |
| 166 | |
| 167 | if !in_evidence_or_quarantine { |
| 168 | return Err(io::Error::new( |
| 169 | io::ErrorKind::PermissionDenied, |
| 170 | "Evidence bundles must be quarantined inside a dedicated evidence or quarantine path", |
| 171 | )); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | let file = OpenOptions::new() |
| 176 | .create(true) |
| 177 | .append(true) |
| 178 | .open(output_path)?; |
| 179 | let mut writer = io::BufWriter::new(file); |
| 180 | |
| 181 | let mut count = 0; |
| 182 | for record in &bundle.records { |
| 183 | let serialized = serde_json::to_string(record)?; |
| 184 | writer.write_all(serialized.as_bytes())?; |
| 185 | writer.write_all(b"\n")?; |
| 186 | count += 1; |
| 187 | } |
| 188 | writer.flush()?; |
| 189 | Ok(count) |
| 190 | } |
| 191 | |
| 192 | fn compute_merkle_root(digests: &[Digest32]) -> Digest32 { |
| 193 | if digests.is_empty() { |
| 194 | return Digest32::ZERO; |
| 195 | } |
| 196 | let mut current = digests.to_vec(); |
| 197 | while current.len() > 1 { |
| 198 | let mut next = Vec::new(); |
| 199 | for chunk in current.chunks(2) { |
| 200 | let mut hasher = Sha256::new(); |
| 201 | hasher.update(chunk[0].0); |
| 202 | if chunk.len() > 1 { |
| 203 | hasher.update(chunk[1].0); |
| 204 | } else { |
| 205 | hasher.update(chunk[0].0); |
| 206 | } |
| 207 | next.push(Digest32(hasher.finalize().into())); |
| 208 | } |
| 209 | current = next; |
| 210 | } |
| 211 | current[0] |
| 212 | } |
| 213 | } |