interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-proof / src / chain.rs

449 lines · 16384 bytes Raw Blame History
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//! Receipt dependency graph verification (`aien-proof verify-chain`).
17//!
18//! Rules, all fail closed:
19//! - dependency IDs are immutable hashes; bytes that do not hash to the
20//! claimed ID are rejected, so substitution and duplicates with different
21//! bytes cannot pass;
22//! - cycles are rejected;
23//! - a missing dependency yields INCOMPLETE, never PASS;
24//! - validation traverses the whole reachable graph;
25//! - a PASS root requires every reachable receipt to be PASS; a FAIL
26//! dependency fails the chain, BLOCKED or INCOMPLETE dependencies block it;
27//! - TEST_ONLY_TRUST ancestry can never support a PRODUCTION receipt;
28//! - a QEMU tier receipt can never satisfy a physical tier requirement
29//! (enforced per requirement in [`crate::gate`]).
30
31use std::collections::{BTreeMap, BTreeSet};
32use std::path::{Path, PathBuf};
33
34use crate::evidence::{load_receipt, verify_with_store, Receipt, Report, Tier, Verdict};
35
36/// Full reachable graph report for one root receipt.
37#[derive(Debug, Clone)]
38pub struct ChainReport {
39 pub root: String,
40 pub status: Verdict,
41 pub lines: Vec<ChainLine>,
42 pub reasons: Vec<String>,
43}
44
45/// One visited receipt in traversal order.
46#[derive(Debug, Clone)]
47pub struct ChainLine {
48 pub id: String,
49 pub kind: String,
50 pub tier: Tier,
51 pub status: Verdict,
52 pub depth: usize,
53 pub note: String,
54}
55
56/// Dependency resolver: receipt ID to verified receipt plus its report.
57pub type Resolver<'a> = &'a dyn Fn(&str) -> Result<(Receipt, Report), String>;
58
59/// Verify the complete reachable receipt graph for the receipt file at
60/// `path`. Dependencies resolve from `store`.
61pub fn verify_chain(path: &Path, store: &Path) -> Result<ChainReport, String> {
62 let text = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
63 let (root, root_report) = verify_with_store(&text, store)?;
64 let resolve = |id: &str| -> Result<(Receipt, Report), String> {
65 let receipt = load_receipt(store, id)?;
66 let bytes = std::fs::read(store.join("receipts").join(format!("{id}.json")))
67 .map_err(|e| e.to_string())?;
68 let (_, report) = verify_with_store(&bytes, store)?;
69 Ok((receipt, report))
70 };
71 Ok(verify_graph(&root, &root_report, store, &resolve))
72}
73
74struct Walker<'a> {
75 store: &'a Path,
76 resolve: Resolver<'a>,
77 graph: BTreeMap<String, Receipt>,
78 visiting: BTreeSet<String>,
79 done: BTreeSet<String>,
80 lines: Vec<ChainLine>,
81 missing: Vec<String>,
82 failed: Vec<String>,
83 blocked: Vec<String>,
84 cycle: Option<String>,
85}
86
87impl<'a> Walker<'a> {
88 fn visit(&mut self, id: &str, depth: usize) {
89 if self.cycle.is_some() || self.done.contains(id) {
90 return;
91 }
92 if self.visiting.contains(id) {
93 self.cycle = Some(format!("dependency cycle through receipt {id}"));
94 return;
95 }
96 self.visiting.insert(id.to_string());
97 let (receipt, report) = match (self.resolve)(id) {
98 Ok(v) => v,
99 Err(e) => {
100 self.missing.push(format!("{id}: {e}"));
101 self.lines.push(ChainLine {
102 id: id.to_string(),
103 kind: "?".to_string(),
104 tier: Tier::TestOnlyTrust,
105 status: Verdict::Incomplete,
106 depth,
107 note: "MISSING".to_string(),
108 });
109 self.visiting.remove(id);
110 self.done.insert(id.to_string());
111 return;
112 }
113 };
114 let lease_report = crate::lease::lease_status(&receipt, self.store);
115 let lease_bad = lease_report
116 .as_ref()
117 .is_some_and(|r| r.status != Verdict::Pass);
118 let mut note = report.reasons.join("; ");
119 if let Some(lease) = &lease_report {
120 if lease.status != Verdict::Pass {
121 if !note.is_empty() {
122 note.push_str("; ");
123 }
124 note.push_str(&lease.reasons.join("; "));
125 match lease.status {
126 Verdict::Fail => self.failed.push(format!("{id}: lease binding failed")),
127 Verdict::Incomplete => self.missing.push(format!("{id}: lease incomplete")),
128 _ => self
129 .blocked
130 .push(format!("{id}: lease {}", lease.status.as_str())),
131 }
132 }
133 }
134 let status = if lease_bad && report.status == Verdict::Pass {
135 Verdict::Incomplete
136 } else {
137 report.status
138 };
139 match status {
140 Verdict::Pass => {}
141 Verdict::Fail => self.failed.push(format!("{id}: dependency records FAIL")),
142 Verdict::Blocked => self.blocked.push(format!("{id}: dependency BLOCKED")),
143 Verdict::Incomplete => self.missing.push(format!("{id}: dependency INCOMPLETE")),
144 Verdict::Skipped => self.blocked.push(format!("{id}: dependency SKIPPED")),
145 }
146 if note.is_empty() {
147 note = status.as_str().to_string();
148 }
149 self.lines.push(ChainLine {
150 id: id.to_string(),
151 kind: receipt.kind.clone(),
152 tier: receipt.tier,
153 status,
154 depth,
155 note,
156 });
157 self.graph.insert(id.to_string(), receipt.clone());
158 let mut deps = receipt.dependencies.clone();
159 deps.sort();
160 for dep in deps {
161 self.visit(&dep.to_ascii_lowercase(), depth + 1);
162 }
163 self.visiting.remove(id);
164 self.done.insert(id.to_string());
165 }
166}
167
168/// Graph traversal over an abstract resolver. The file backed [`verify_chain`]
169/// supplies a store resolver; tests supply an in memory resolver so cycles,
170/// which hash linked IDs make infeasible to construct on disk, are still
171/// exercised directly.
172pub fn verify_graph(
173 root: &Receipt,
174 root_report: &Report,
175 store: &Path,
176 resolve: Resolver<'_>,
177) -> ChainReport {
178 let root_id = root.id.to_ascii_lowercase();
179 let mut walker = Walker {
180 store,
181 resolve,
182 graph: BTreeMap::new(),
183 visiting: BTreeSet::new(),
184 done: BTreeSet::new(),
185 lines: Vec::new(),
186 missing: Vec::new(),
187 failed: Vec::new(),
188 blocked: Vec::new(),
189 cycle: None,
190 };
191 let mut reasons: Vec<String> = Vec::new();
192
193 if root_report.status == Verdict::Fail {
194 walker.failed.push(format!("{root_id}: root receipt FAIL"));
195 }
196 let mut deps = root.dependencies.clone();
197 deps.sort();
198 for dep in deps {
199 walker.visit(&dep.to_ascii_lowercase(), 1);
200 }
201 walker
202 .lines
203 .sort_by(|a, b| (a.depth, &a.id).cmp(&(b.depth, &b.id)));
204
205 if let Some(c) = walker.cycle {
206 return ChainReport {
207 root: root_id,
208 status: Verdict::Fail,
209 lines: walker.lines,
210 reasons: vec![c],
211 };
212 }
213 // Contamination: test only ancestry under a production root.
214 if root.tier == Tier::Production {
215 let bad: Vec<String> = walker
216 .graph
217 .values()
218 .filter(|r| r.tier == Tier::TestOnlyTrust)
219 .map(|r| r.id.clone())
220 .collect();
221 if !bad.is_empty() {
222 reasons.push(format!(
223 "PRODUCTION receipt depends on TEST_ONLY_TRUST receipts: {}",
224 bad.join(", ")
225 ));
226 return ChainReport {
227 root: root_id,
228 status: Verdict::Fail,
229 lines: walker.lines,
230 reasons,
231 };
232 }
233 }
234
235 let status = if !walker.failed.is_empty() {
236 reasons.extend(walker.failed.clone());
237 Verdict::Fail
238 } else if root_report.status == Verdict::Fail {
239 reasons.extend(root_report.reasons.clone());
240 Verdict::Fail
241 } else if !walker.missing.is_empty() {
242 reasons.extend(walker.missing.clone());
243 reasons.push("missing or incomplete dependencies never yield PASS".to_string());
244 Verdict::Incomplete
245 } else if !walker.blocked.is_empty() {
246 reasons.extend(walker.blocked.clone());
247 Verdict::Blocked
248 } else {
249 match root_report.status {
250 Verdict::Pass => {
251 reasons.push(format!(
252 "chain OK: root {root_id} plus {} reachable receipts all PASS",
253 walker.graph.len()
254 ));
255 Verdict::Pass
256 }
257 other => {
258 reasons.extend(root_report.reasons.clone());
259 other
260 }
261 }
262 };
263 ChainReport {
264 root: root_id,
265 status,
266 lines: walker.lines,
267 reasons,
268 }
269}
270
271/// True when a receipt at `have` tier satisfies a requirement of `need` tier.
272/// Physical requirements need physical evidence; test only trust satisfies
273/// nothing but itself.
274pub fn tier_satisfies(need: Tier, have: Tier) -> bool {
275 if have == Tier::TestOnlyTrust {
276 return need == Tier::TestOnlyTrust;
277 }
278 if need.is_physical() && !have.is_physical() {
279 return false;
280 }
281 have.rank() >= need.rank()
282}
283
284pub fn chain_path_arg(path: &str) -> PathBuf {
285 PathBuf::from(path)
286}
287
288#[cfg(test)]
289mod tests {
290 use super::*;
291 use crate::evidence::fixtures::{sample, sealed};
292 use crate::evidence::{store_receipt, Mutation, Report};
293
294 fn qemu_receipt(kind: &str, deps: Vec<String>) -> Receipt {
295 let mut r = sample();
296 r.kind = kind.to_string();
297 r.dependencies = deps;
298 sealed(r)
299 }
300
301 fn put(store: &Path, r: &Receipt) -> String {
302 store_receipt(store, r).unwrap()
303 }
304
305 fn write_root(dir: &Path, r: &Receipt) -> PathBuf {
306 let path = dir.join("root.json");
307 let text = serde_json::to_string_pretty(r).unwrap();
308 std::fs::write(&path, format!("{text}\n")).unwrap();
309 path
310 }
311
312 #[test]
313 fn empty_chain_passes() {
314 let store = crate::testutil::temp_dir("chain-empty");
315 let r = qemu_receipt("m3", vec![]);
316 let id = put(&store, &r);
317 let dir = crate::testutil::temp_dir("chain-empty-root");
318 let path = write_root(&dir, &r);
319 let report = verify_chain(&path, &store).unwrap();
320 assert_eq!(report.status, Verdict::Pass);
321 assert_eq!(report.root, id);
322 }
323
324 #[test]
325 fn missing_dependency_is_incomplete_never_pass() {
326 let store = crate::testutil::temp_dir("chain-missing");
327 let r = sealed(qemu_receipt("seed-0b-machine1", vec!["f".repeat(64)]));
328 let dir = crate::testutil::temp_dir("chain-missing-root");
329 let path = write_root(&dir, &r);
330 let report = verify_chain(&path, &store).unwrap();
331 assert_eq!(report.status, Verdict::Incomplete);
332 }
333
334 #[test]
335 fn tampered_dependency_file_fails_closed() {
336 let store = crate::testutil::temp_dir("chain-tamper");
337 let dep = put(&store, &qemu_receipt("m3", vec![]));
338 let root = sealed(qemu_receipt("seed", vec![dep.clone()]));
339 let dir = crate::testutil::temp_dir("chain-tamper-root");
340 let path = write_root(&dir, &root);
341 assert_eq!(verify_chain(&path, &store).unwrap().status, Verdict::Pass);
342 let dep_path = store.join("receipts").join(format!("{dep}.json"));
343 let text = std::fs::read_to_string(&dep_path).unwrap().replacen(
344 "artifact_signature_valid",
345 "artifact_signature_tampered",
346 1,
347 );
348 std::fs::write(&dep_path, text).unwrap();
349 assert_eq!(
350 verify_chain(&path, &store).unwrap().status,
351 Verdict::Incomplete
352 );
353 }
354
355 #[test]
356 fn cyclic_dependencies_rejected() {
357 // Hash linked IDs make real cycles infeasible to construct on disk,
358 // which is itself a defense. The traversal guard is exercised here
359 // through an in memory resolver with a genuine two node cycle.
360 let store = crate::testutil::temp_dir("chain-cycle");
361 let mut a = sample();
362 a.id = "a".repeat(64);
363 a.kind = "cycle-a".to_string();
364 a.dependencies = vec!["b".repeat(64)];
365 let mut b = sample();
366 b.id = "b".repeat(64);
367 b.kind = "cycle-b".to_string();
368 b.dependencies = vec!["a".repeat(64)];
369 let map: BTreeMap<String, (Receipt, Report)> = BTreeMap::from([
370 ("a".repeat(64), (a.clone(), Report::pass("ok"))),
371 ("b".repeat(64), (b.clone(), Report::pass("ok"))),
372 ]);
373 let resolve = |id: &str| map.get(id).cloned().ok_or_else(|| "missing".to_string());
374 let mut root = sample();
375 root.id = "r".repeat(64);
376 root.kind = "cycle-root".to_string();
377 root.dependencies = vec!["a".repeat(64)];
378 let report = verify_graph(&root, &Report::pass("ok"), &store, &resolve);
379 assert_eq!(report.status, Verdict::Fail);
380 assert!(report.reasons.iter().any(|r| r.contains("cycle")));
381 }
382
383 #[test]
384 fn blocked_dependency_blocks_chain_never_passes() {
385 let store = crate::testutil::temp_dir("chain-blocked");
386 let mut dep = sample();
387 dep.kind = "qemu-qual".to_string();
388 dep.result = Verdict::Blocked;
389 let dep_id = put(&store, &sealed(dep));
390 let root = sealed(qemu_receipt("seed", vec![dep_id]));
391 let dir = crate::testutil::temp_dir("chain-blocked-root");
392 let path = write_root(&dir, &root);
393 let report = verify_chain(&path, &store).unwrap();
394 assert_eq!(report.status, Verdict::Blocked);
395 }
396
397 #[test]
398 fn failed_dependency_fails_chain() {
399 let store = crate::testutil::temp_dir("chain-fail");
400 let mut dep = sample();
401 dep.kind = "qemu-qual".to_string();
402 dep.result = Verdict::Fail;
403 let dep_id = put(&store, &sealed(dep));
404 let root = sealed(qemu_receipt("seed", vec![dep_id]));
405 let dir = crate::testutil::temp_dir("chain-fail-root");
406 let path = write_root(&dir, &root);
407 assert_eq!(verify_chain(&path, &store).unwrap().status, Verdict::Fail);
408 }
409
410 #[test]
411 fn illegal_tier_escalation_fails() {
412 // PRODUCTION root with TEST_ONLY_TRUST ancestry.
413 let store = crate::testutil::temp_dir("chain-tier");
414 let mut t = sample();
415 t.kind = "lab-note".to_string();
416 t.tier = Tier::TestOnlyTrust;
417 t.env_class = "TEST_ONLY_TRUST".to_string();
418 let t_id = put(&store, &sealed(t));
419 let mut p = sample();
420 p.kind = "prod-release".to_string();
421 p.tier = Tier::Production;
422 p.env_class = "PRODUCTION".to_string();
423 p.authority = "release board 2026-09".to_string();
424 p.dependencies = vec![t_id];
425 let p = sealed(p);
426 let dir = crate::testutil::temp_dir("chain-tier-root");
427 let path = write_root(&dir, &p);
428 assert_eq!(verify_chain(&path, &store).unwrap().status, Verdict::Fail);
429 }
430
431 #[test]
432 fn tier_satisfaction_matrix() {
433 assert!(tier_satisfies(Tier::Qemu, Tier::Qemu));
434 assert!(tier_satisfies(Tier::Qemu, Tier::Machine1Mutating));
435 assert!(!tier_satisfies(Tier::Machine1Attended, Tier::Qemu));
436 assert!(!tier_satisfies(Tier::Machine1Attended, Tier::QemuSecurity));
437 assert!(tier_satisfies(
438 Tier::Machine1ReadOnly,
439 Tier::Machine1Mutating
440 ));
441 assert!(!tier_satisfies(Tier::HostTest, Tier::TestOnlyTrust));
442 assert!(tier_satisfies(Tier::TestOnlyTrust, Tier::TestOnlyTrust));
443 }
444
445 #[test]
446 fn mutation_import_used() {
447 assert_eq!(Mutation::None.as_str(), "NONE");
448 }
449}