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 / aien-closure / src / verify.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 | //! The verification pipeline behind `verify-closure`. |
| 17 | |
| 18 | use crate::declare; |
| 19 | use crate::digest::source_digest; |
| 20 | use crate::error::{Code, Finding}; |
| 21 | use crate::graph::{cargo_packages, closure_of, find_cycle, graph_of, Package}; |
| 22 | use crate::manifest::{self, Manifest}; |
| 23 | use aien_proof::chain::{tier_satisfies, verify_chain}; |
| 24 | use aien_proof::evidence::{receipt_id, Receipt, Tier, Verdict, RECEIPT_DIR}; |
| 25 | use std::collections::{BTreeMap, BTreeSet}; |
| 26 | use std::fs; |
| 27 | use std::path::{Path, PathBuf}; |
| 28 | |
| 29 | pub const LOCK_FILE: &str = "closure.lock"; |
| 30 | pub const LOCK_HEADER: &str = "closure-lock v1"; |
| 31 | |
| 32 | pub struct Options { |
| 33 | pub root: PathBuf, |
| 34 | pub store: PathBuf, |
| 35 | /// Write `closure.lock` (only when no other finding exists) before |
| 36 | /// comparing, so a fresh lock verifies. |
| 37 | pub write_lock: bool, |
| 38 | } |
| 39 | |
| 40 | pub struct Outcome { |
| 41 | pub findings: Vec<Finding>, |
| 42 | /// Number of components that carry a manifest. |
| 43 | pub components: usize, |
| 44 | /// Components with no findings. |
| 45 | pub passed: Vec<(String, String)>, |
| 46 | } |
| 47 | |
| 48 | impl Outcome { |
| 49 | pub fn ok(&self) -> bool { |
| 50 | self.findings.is_empty() |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | /// Minimum receipt tier a verifier profile demands. Unknown profiles have no |
| 55 | /// entry, which the verifier reports as UNKNOWN_VERIFIER_PROFILE. |
| 56 | pub fn profile_min_tier(profile: &str) -> Option<Tier> { |
| 57 | match profile { |
| 58 | "host-v1" => Some(Tier::HostTest), |
| 59 | "qemu-v1" => Some(Tier::Qemu), |
| 60 | "production-v1" => Some(Tier::Production), |
| 61 | _ => None, |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | enum Load { |
| 66 | Missing, |
| 67 | Mismatch(String), |
| 68 | Ok(Box<Receipt>), |
| 69 | } |
| 70 | |
| 71 | fn receipt_path(store: &Path, id: &str) -> PathBuf { |
| 72 | store.join(RECEIPT_DIR).join(format!("{id}.json")) |
| 73 | } |
| 74 | |
| 75 | /// Read a receipt by claimed id and recompute its identity with aien-proof. |
| 76 | fn load(store: &Path, id: &str) -> Load { |
| 77 | let Ok(bytes) = fs::read(receipt_path(store, id)) else { |
| 78 | return Load::Missing; |
| 79 | }; |
| 80 | let r: Receipt = match serde_json::from_slice(&bytes) { |
| 81 | Ok(r) => r, |
| 82 | Err(e) => return Load::Mismatch(format!("not a valid receipt: {e}")), |
| 83 | }; |
| 84 | match receipt_id(&r) { |
| 85 | Err(e) => Load::Mismatch(e), |
| 86 | Ok(c) if c != id || r.id.to_ascii_lowercase() != id => Load::Mismatch(format!( |
| 87 | "file {id} has canonical identity {c} and claims {}", |
| 88 | r.id |
| 89 | )), |
| 90 | Ok(_) => Load::Ok(Box::new(r)), |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | struct ChainFacts { |
| 95 | findings: Vec<(Code, String)>, |
| 96 | tainted: Vec<String>, |
| 97 | root: Option<Box<Receipt>>, |
| 98 | } |
| 99 | |
| 100 | /// Walk the receipt graph from `id`, classifying missing, mismatched and |
| 101 | /// tainted receipts. Tainted means recorded dirty or TEST_ONLY_TRUST. |
| 102 | fn walk_receipts(store: &Path, id: &str) -> ChainFacts { |
| 103 | let mut facts = ChainFacts { |
| 104 | findings: vec![], |
| 105 | tainted: vec![], |
| 106 | root: None, |
| 107 | }; |
| 108 | let mut seen = BTreeSet::new(); |
| 109 | let mut todo = vec![id.to_string()]; |
| 110 | while let Some(cur) = todo.pop() { |
| 111 | if !seen.insert(cur.clone()) { |
| 112 | continue; |
| 113 | } |
| 114 | match load(store, &cur) { |
| 115 | Load::Missing => facts |
| 116 | .findings |
| 117 | .push((Code::MissingReceipt, format!("receipt {cur} not in store"))), |
| 118 | Load::Mismatch(m) => facts |
| 119 | .findings |
| 120 | .push((Code::ReceiptHashMismatch, format!("receipt {cur}: {m}"))), |
| 121 | Load::Ok(r) => { |
| 122 | if r.dirty { |
| 123 | facts |
| 124 | .tainted |
| 125 | .push(format!("{cur} recorded from a dirty tree")); |
| 126 | } |
| 127 | if r.tier == Tier::TestOnlyTrust { |
| 128 | facts.tainted.push(format!("{cur} is TEST_ONLY_TRUST")); |
| 129 | } |
| 130 | todo.extend(r.dependencies.iter().map(|d| d.to_ascii_lowercase())); |
| 131 | if cur == id { |
| 132 | facts.root = Some(r); |
| 133 | } |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | facts |
| 138 | } |
| 139 | |
| 140 | fn check_component( |
| 141 | m: &Manifest, |
| 142 | pkg: &Package, |
| 143 | manifests: &BTreeMap<String, Manifest>, |
| 144 | store: &Path, |
| 145 | out: &mut Vec<Finding>, |
| 146 | ) { |
| 147 | let name = m.component.as_str(); |
| 148 | let mut add = |code: Code, detail: String| out.push(Finding::new(code, name, detail)); |
| 149 | |
| 150 | // Profile. |
| 151 | let min_tier = profile_min_tier(&m.profile); |
| 152 | if min_tier.is_none() { |
| 153 | add( |
| 154 | Code::UnknownVerifierProfile, |
| 155 | format!("profile {:?} is not known to this verifier", m.profile), |
| 156 | ); |
| 157 | } |
| 158 | |
| 159 | // Declarations (SPEC 6.2): an actual edge the manifest does not declare is |
| 160 | // UNDECLARED_IMPORT; a declared dep that is not an actual edge is |
| 161 | // UNVERIFIED_DEPENDENCY. |
| 162 | let actual: BTreeSet<String> = pkg.deps.iter().cloned().collect(); |
| 163 | let declared: BTreeSet<String> = m.deps.keys().cloned().collect(); |
| 164 | for d in declare::compare(&actual, &declared) { |
| 165 | let dep = &d.name; |
| 166 | let detail = match d.code { |
| 167 | Code::UndeclaredImport => { |
| 168 | format!("edge to {dep} is not declared in {}", manifest::FILE_NAME) |
| 169 | } |
| 170 | _ => format!("declared dep {dep} is not an edge of the graph"), |
| 171 | }; |
| 172 | add(d.code, detail); |
| 173 | } |
| 174 | |
| 175 | // Edges: every declared actual edge pinned to the dep's own receipt. |
| 176 | for dep in &pkg.deps { |
| 177 | if let Some(pin) = m.deps.get(dep) { |
| 178 | match manifests.get(dep) { |
| 179 | None => add( |
| 180 | Code::UnverifiedDependency, |
| 181 | format!("dependency {dep} has no {}", manifest::FILE_NAME), |
| 182 | ), |
| 183 | Some(dm) => match pin { |
| 184 | None => add( |
| 185 | Code::DependencyNotPinned, |
| 186 | format!("dep {dep} declared without a receipt pin"), |
| 187 | ), |
| 188 | Some(p) if *p != dm.receipt => add( |
| 189 | Code::DependencyNotPinned, |
| 190 | format!( |
| 191 | "dep {dep} pinned to {p} but {dep} is qualified by {}", |
| 192 | dm.receipt |
| 193 | ), |
| 194 | ), |
| 195 | Some(_) => {} |
| 196 | }, |
| 197 | } |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | // Receipt and chain. |
| 202 | let facts = walk_receipts(store, &m.receipt); |
| 203 | let broken = !facts.findings.is_empty(); |
| 204 | for (code, detail) in facts.findings { |
| 205 | add(code, detail); |
| 206 | } |
| 207 | for t in facts.tainted { |
| 208 | add(Code::TaintedArtifact, t); |
| 209 | } |
| 210 | if let Some(root) = &facts.root { |
| 211 | // Pins must be bound inside the receipt, so the chain covers them. |
| 212 | let rdeps: BTreeSet<String> = root |
| 213 | .dependencies |
| 214 | .iter() |
| 215 | .map(|d| d.to_ascii_lowercase()) |
| 216 | .collect(); |
| 217 | for (dep, pin) in &m.deps { |
| 218 | if let Some(p) = pin { |
| 219 | if !rdeps.contains(p) { |
| 220 | add( |
| 221 | Code::DependencyNotPinned, |
| 222 | format!( |
| 223 | "receipt {} does not depend on pinned receipt {p} of {dep}", |
| 224 | m.receipt |
| 225 | ), |
| 226 | ); |
| 227 | } |
| 228 | } |
| 229 | } |
| 230 | // Source binding. |
| 231 | if !root.input_artifacts.iter().any(|a| a == &m.source) { |
| 232 | add( |
| 233 | Code::StaleReceipt, |
| 234 | format!("receipt {} was not taken at {}", m.receipt, m.source), |
| 235 | ); |
| 236 | } |
| 237 | if let Some(need) = min_tier { |
| 238 | if root.tier != Tier::TestOnlyTrust && !tier_satisfies(need, root.tier) { |
| 239 | add( |
| 240 | Code::UnverifiedDependency, |
| 241 | format!( |
| 242 | "receipt tier {} does not satisfy profile {}", |
| 243 | root.tier.as_str(), |
| 244 | m.profile |
| 245 | ), |
| 246 | ); |
| 247 | } |
| 248 | } |
| 249 | if root.result != Verdict::Pass { |
| 250 | add( |
| 251 | Code::UnverifiedDependency, |
| 252 | format!("receipt {} result is {}", m.receipt, root.result.as_str()), |
| 253 | ); |
| 254 | } |
| 255 | } |
| 256 | if !broken { |
| 257 | match verify_chain(&receipt_path(store, &m.receipt), store) { |
| 258 | Err(e) => add(Code::UnverifiedDependency, format!("chain error: {e}")), |
| 259 | Ok(rep) if rep.status != Verdict::Pass => { |
| 260 | let why = rep.reasons.join("; "); |
| 261 | let code = if why.contains("dependency cycle") { |
| 262 | Code::DependencyCycle |
| 263 | } else { |
| 264 | Code::UnverifiedDependency |
| 265 | }; |
| 266 | add(code, format!("chain {}: {why}", rep.status.as_str())); |
| 267 | } |
| 268 | Ok(_) => {} |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | // Current source against the digest the manifest records. |
| 273 | match source_digest(&pkg.dir) { |
| 274 | Err(e) => add(Code::StaleReceipt, format!("cannot digest source: {e}")), |
| 275 | Ok(d) => { |
| 276 | let now = format!("blake3:{d}"); |
| 277 | if now != m.source { |
| 278 | add( |
| 279 | Code::StaleReceipt, |
| 280 | format!("source is {now} but manifest records {}", m.source), |
| 281 | ); |
| 282 | } |
| 283 | } |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | /// Render the lock: header, one `component` line each, then every transitive |
| 288 | /// dependency with its pinned receipt id. Sorted, so it is deterministic. |
| 289 | pub fn render_lock(manifests: &BTreeMap<String, Manifest>, graph: &crate::graph::Graph) -> String { |
| 290 | let mut s = format!("{LOCK_HEADER}\n"); |
| 291 | for (name, m) in manifests { |
| 292 | s.push_str(&format!("component {name} {} {}\n", m.receipt, m.source)); |
| 293 | for dep in closure_of(graph, name) { |
| 294 | let id = manifests.get(&dep).map_or("-", |d| d.receipt.as_str()); |
| 295 | s.push_str(&format!("needs {name} {dep} {id}\n")); |
| 296 | } |
| 297 | } |
| 298 | s |
| 299 | } |
| 300 | |
| 301 | /// Run every check. `Err` is an internal error (cannot run cargo, cannot |
| 302 | /// read the repo); callers must treat it as failure too. |
| 303 | pub fn verify(opts: &Options) -> Result<Outcome, String> { |
| 304 | let packages = cargo_packages(&opts.root)?; |
| 305 | let graph = graph_of(&packages); |
| 306 | let mut findings: Vec<Finding> = Vec::new(); |
| 307 | |
| 308 | // Manifests. |
| 309 | let mut manifests: BTreeMap<String, Manifest> = BTreeMap::new(); |
| 310 | for pkg in &packages { |
| 311 | let path = pkg.dir.join(manifest::FILE_NAME); |
| 312 | if !path.exists() { |
| 313 | continue; |
| 314 | } |
| 315 | let parsed = fs::read_to_string(&path) |
| 316 | .map_err(|e| e.to_string()) |
| 317 | .and_then(|t| manifest::parse(&t)) |
| 318 | .and_then(|m| { |
| 319 | if m.component == pkg.name { |
| 320 | Ok(m) |
| 321 | } else { |
| 322 | Err(format!( |
| 323 | "component {:?} does not match package {:?}", |
| 324 | m.component, pkg.name |
| 325 | )) |
| 326 | } |
| 327 | }); |
| 328 | match parsed { |
| 329 | Ok(m) => { |
| 330 | manifests.insert(pkg.name.clone(), m); |
| 331 | } |
| 332 | Err(e) => findings.push(Finding::new( |
| 333 | Code::UnverifiedDependency, |
| 334 | &pkg.name, |
| 335 | format!("bad {}: {e}", manifest::FILE_NAME), |
| 336 | )), |
| 337 | } |
| 338 | } |
| 339 | if manifests.is_empty() && findings.is_empty() { |
| 340 | findings.push(Finding::new( |
| 341 | Code::UnverifiedDependency, |
| 342 | "-", |
| 343 | format!( |
| 344 | "no {} found under {}", |
| 345 | manifest::FILE_NAME, |
| 346 | opts.root.display() |
| 347 | ), |
| 348 | )); |
| 349 | } |
| 350 | |
| 351 | // Cycles. |
| 352 | if let Some(cycle) = find_cycle(&graph) { |
| 353 | findings.push(Finding::new( |
| 354 | Code::DependencyCycle, |
| 355 | &cycle[0], |
| 356 | cycle.join(" -> "), |
| 357 | )); |
| 358 | } |
| 359 | |
| 360 | // Components with a manifest. |
| 361 | let by_name: BTreeMap<&str, &Package> = packages.iter().map(|p| (p.name.as_str(), p)).collect(); |
| 362 | for (name, m) in &manifests { |
| 363 | check_component( |
| 364 | m, |
| 365 | by_name[name.as_str()], |
| 366 | &manifests, |
| 367 | &opts.store, |
| 368 | &mut findings, |
| 369 | ); |
| 370 | } |
| 371 | |
| 372 | // Lock file, only meaningful when the rest is clean. |
| 373 | if findings.is_empty() { |
| 374 | let want = render_lock(&manifests, &graph); |
| 375 | let path = opts.root.join(LOCK_FILE); |
| 376 | if opts.write_lock { |
| 377 | fs::write(&path, &want).map_err(|e| format!("cannot write {}: {e}", path.display()))?; |
| 378 | } |
| 379 | match fs::read_to_string(&path) { |
| 380 | Ok(have) if have == want => {} |
| 381 | Ok(have) => { |
| 382 | // A pin for something the component does not depend on is |
| 383 | // UNVERIFIED_DEPENDENCY (SPEC 6.2). Everything else that |
| 384 | // differs (missing line, wrong id) is DEPENDENCY_NOT_PINNED. |
| 385 | for (comp, dep) in declare::extra_needs(&have, &want) { |
| 386 | findings.push(Finding::new( |
| 387 | Code::UnverifiedDependency, |
| 388 | &comp, |
| 389 | format!("{LOCK_FILE} pins {dep} for {comp}, which does not depend on it"), |
| 390 | )); |
| 391 | } |
| 392 | if declare::without_extra_needs(&have, &want) != want { |
| 393 | findings.push(Finding::new( |
| 394 | Code::DependencyNotPinned, |
| 395 | "-", |
| 396 | format!("{LOCK_FILE} does not match the rebuilt closure"), |
| 397 | )); |
| 398 | } |
| 399 | } |
| 400 | Err(_) => findings.push(Finding::new( |
| 401 | Code::DependencyNotPinned, |
| 402 | "-", |
| 403 | format!("{LOCK_FILE} is missing"), |
| 404 | )), |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | findings.sort(); |
| 409 | findings.dedup(); |
| 410 | let bad: BTreeSet<&str> = findings.iter().map(|f| f.component.as_str()).collect(); |
| 411 | let passed = manifests |
| 412 | .iter() |
| 413 | .filter(|(n, _)| !bad.contains(n.as_str())) |
| 414 | .map(|(n, m)| (n.clone(), m.receipt.clone())) |
| 415 | .collect(); |
| 416 | Ok(Outcome { |
| 417 | findings, |
| 418 | components: manifests.len(), |
| 419 | passed, |
| 420 | }) |
| 421 | } |