diff --git a/crates/aien-proof/gates/P3_DEVELOPMENT_QEMU_ENTRY.json b/crates/aien-proof/gates/P3_DEVELOPMENT_QEMU_ENTRY.json new file mode 100644 index 00000000..c0613839 --- /dev/null +++ b/crates/aien-proof/gates/P3_DEVELOPMENT_QEMU_ENTRY.json @@ -0,0 +1,10 @@ +{ + "gate": "P3_DEVELOPMENT_QEMU_ENTRY", + "description": "Authorizes host implementation, host crash/fault tests, disposable QEMU storage work, and QEMU P3 qualification. It grants no physical storage mutation authority.", + "requires": [ + {"name":"M0_NATIVE_ROLLBACK_QEMU","kind":"m0-native-rollback-qemu","min_tier":"QEMU","repo":"https://github.com/aien-dev/aienos","machine":"qemu-aarch64-aavmf","procedure_contains":"qemu_native_rollback_test.sh@","min_input_artifacts":2,"assertions":["rollback_harness_version_recorded","qemu_aavmf_environment_recorded","rollback_normal_pass","rollback_fault_pass","rollback_timeout_pass","rollback_rejected_pass","rollback_absent_pass","rollback_repeat_boot_pass","bootnext_consumed","default_boot_unchanged","m0_native_rollback_qemu_pass"],"assertion_sources":[{"id":"bootnext_consumed","source":"aavmf_variables"},{"id":"default_boot_unchanged","source":"aavmf_variables"}],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"SEED0B_QEMU","kind":"","gate_ref":"SEED0B_QEMU"}, + {"name":"ADR0015","kind":"adr0015-format","min_tier":"HOST_TEST","assertions":["adr0015_accepted_frozen"],"require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"STRICT_MAIN","kind":"strict-main-verification","min_tier":"HOST_TEST","assertions":["strict_main_pass"],"require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/gates/P3_MACHINE1_WRITE_ENTRY.json b/crates/aien-proof/gates/P3_MACHINE1_WRITE_ENTRY.json new file mode 100644 index 00000000..55ed1074 --- /dev/null +++ b/crates/aien-proof/gates/P3_MACHINE1_WRITE_ENTRY.json @@ -0,0 +1,12 @@ +{ + "gate": "P3_MACHINE1_WRITE_ENTRY", + "description": "Physical P3 writes require the development QEMU gate plus owner trust, Machine 1 rollback, bounded target, exact-region provisioning authority, attended qualification, and the existing machine-1 hold.", + "requires": [ + {"name":"P3_DEVELOPMENT_QEMU_ENTRY","kind":"","gate_ref":"P3_DEVELOPMENT_QEMU_ENTRY"}, + {"name":"OWNER_SECURE_BOOT_TRUST_CHAIN","kind":"owner-secure-boot-trust","min_tier":"MACHINE1_ATTENDED","assertions":["owner_trust_prerequisite_pass","secure_boot_on"],"resource":"machine-1","require_clean":true,"missing_as":"BLOCKED","missing_reason":"HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN"}, + {"name":"M0_NATIVE_ROLLBACK_MACHINE1","kind":"m0-native-rollback-machine1","min_tier":"MACHINE1_ATTENDED","assertions":["secure_boot_unchanged","permanent_bootorder_unchanged","bootnext_consumed","linux_default_returned","root_uuid_unchanged","esp_uuid_unchanged","expected_mounts_healthy","candidate_digest_exact","source_commit_exact","operator_attended"],"assertion_sources":[{"id":"secure_boot_unchanged","source":"uefi_observed"},{"id":"permanent_bootorder_unchanged","source":"uefi_observed"},{"id":"bootnext_consumed","source":"uefi_observed"},{"id":"linux_default_returned","source":"linux_observed"},{"id":"root_uuid_unchanged","source":"linux_observed"},{"id":"esp_uuid_unchanged","source":"linux_observed"},{"id":"expected_mounts_healthy","source":"linux_observed"}],"mutation":"ONE_TIME_BOOT_SELECTION","resource":"machine-1","require_clean":true,"missing_as":"BLOCKED","missing_reason":"HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN"}, + {"name":"BOUNDED_MACHINE1_STORE_REGION","kind":"bounded-machine1-store-region","min_tier":"MACHINE1_ATTENDED","assertions":["bounded_region_identity_exact","region_bounds_verified"],"mutation":"BOUNDED_TEST_REGION_WRITE","resource":"machine-1","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"PROVISIONING_AUTHORITY_EXACT_REGION","kind":"machine1-region-provisioning-authority","min_tier":"MACHINE1_ATTENDED","assertions":["provisioning_authority_exact_region"],"resource":"machine-1","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"OPERATOR_ATTENDED_HARDWARE_QUALIFICATION","kind":"machine1-attended-qualification","min_tier":"MACHINE1_ATTENDED","assertions":["operator_attended","hardware_qualification_context_valid"],"resource":"machine-1","require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/gates/P3_STORE_MACHINE1.json b/crates/aien-proof/gates/P3_STORE_MACHINE1.json new file mode 100644 index 00000000..88410fc7 --- /dev/null +++ b/crates/aien-proof/gates/P3_STORE_MACHINE1.json @@ -0,0 +1,10 @@ +{ + "gate": "P3_STORE_MACHINE1", + "description": "Machine 1 P3 Store execution is limited to the approved bounded test region and requires attended qualification under the existing machine-1 hold.", + "requires": [ + {"name":"P3_MACHINE1_WRITE_ENTRY","kind":"","gate_ref":"P3_MACHINE1_WRITE_ENTRY"}, + {"name":"Bounded physical region","kind":"bounded-machine1-store-region","min_tier":"MACHINE1_ATTENDED","resource":"machine-1","assertions":["bounded_region_identity_exact","region_bounds_verified"],"mutation":"BOUNDED_TEST_REGION_WRITE","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"Exact-region provisioning authority","kind":"machine1-region-provisioning-authority","min_tier":"MACHINE1_ATTENDED","resource":"machine-1","assertions":["provisioning_authority_exact_region"],"require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"Machine 1 execution receipt","kind":"p3-store-machine1-execution","min_tier":"MACHINE1_MUTATING","resource":"machine-1","assertions":["store_previous_or_new_only","store_graph_valid","store_nospace_zero_writes","store_io_error_not_fallback","operator_attended"],"dependency_kinds":["bounded-machine1-store-region","machine1-region-provisioning-authority"],"mutation":"BOUNDED_TEST_REGION_WRITE","require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/gates/P3_STORE_QEMU.json b/crates/aien-proof/gates/P3_STORE_QEMU.json new file mode 100644 index 00000000..3be72d5f --- /dev/null +++ b/crates/aien-proof/gates/P3_STORE_QEMU.json @@ -0,0 +1,10 @@ +{ + "gate": "P3_STORE_QEMU", + "description": "QEMU P3 Store qualification. Store semantics are supplied by Store v1 tests and verified here as structured receipts.", + "requires": [ + {"name":"P3_DEVELOPMENT_QEMU_ENTRY","kind":"","gate_ref":"P3_DEVELOPMENT_QEMU_ENTRY"}, + {"name":"Store format qualification","kind":"store-v1-format-qualification","min_tier":"QEMU","assertions":["store_format_v1_valid","store_golden_vectors_match"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"Crash and recovery suite","kind":"store-v1-crash-consistency","min_tier":"QEMU","assertions":["store_previous_or_new_only","store_graph_valid","store_nospace_zero_writes","store_io_error_not_fallback"],"dependency_kinds":["store-v1-format-qualification"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"QEMU block-device suite","kind":"store-v1-qemu-block-device","min_tier":"QEMU","assertions":["qemu_block_device_suite_pass"],"dependency_kinds":["store-v1-format-qualification","store-v1-crash-consistency"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/gates/SEED-0B.json b/crates/aien-proof/gates/SEED-0B.json new file mode 100644 index 00000000..a63bb573 --- /dev/null +++ b/crates/aien-proof/gates/SEED-0B.json @@ -0,0 +1,16 @@ +{ + "gate": "SEED-0B", + "description": "EXAMPLE manifest shape only. Not evidence that SEED-0B has passed. A real closure needs the stored receipts listed below, each verified with its full chain.", + "requires": [ + {"name": "M3", "kind": "m3", "min_tier": "HOST_TEST", "assertions": [], "require_clean": true}, + {"name": "artifact identity", "kind": "seed-0b-qemu", "min_tier": "QEMU", "assertions": ["artifact_identity"], "require_clean": true}, + {"name": "artifact signature", "kind": "seed-0b-qemu", "min_tier": "QEMU", "assertions": ["artifact_signature_valid"], "require_clean": true}, + {"name": "grant attenuation", "kind": "seed-0b-qemu", "min_tier": "QEMU", "assertions": ["granted_subset_requested"], "require_clean": true}, + {"name": "authorized operation", "kind": "seed-0b-qemu", "min_tier": "QEMU", "assertions": ["authorized_op_permitted"], "require_clean": true}, + {"name": "unauthorized denial", "kind": "seed-0b-qemu", "min_tier": "QEMU", "assertions": ["unauthorized_write_denied"], "require_clean": true}, + {"name": "cleanup", "kind": "seed-0b-qemu", "min_tier": "QEMU", "assertions": ["all_task_frames_reclaimed", "machine_returned_to_linux"], "require_clean": true}, + {"name": "hostile matrix", "kind": "seed-0b-hostile-matrix", "min_tier": "QEMU", "assertions": [], "require_clean": true}, + {"name": "SEED-0B-QEMU", "kind": "seed-0b-qemu", "min_tier": "QEMU", "assertions": [], "require_clean": true}, + {"name": "SEED-0B-MACHINE1", "kind": "seed-0b-machine1", "min_tier": "MACHINE1_ATTENDED", "assertions": [], "require_clean": true} + ] +} diff --git a/crates/aien-proof/gates/SEED0B_QEMU.json b/crates/aien-proof/gates/SEED0B_QEMU.json new file mode 100644 index 00000000..a2d5d7d0 --- /dev/null +++ b/crates/aien-proof/gates/SEED0B_QEMU.json @@ -0,0 +1,7 @@ +{ + "gate": "SEED0B_QEMU", + "description": "QEMU-only SEED-0B gate. It proves only the structured assertions from the exact imported QEMU run.", + "requires": [ + {"name":"SEED-0B QEMU evidence","kind":"seed0b-qemu","min_tier":"QEMU","assertions":["seed0b_signature_valid","granted_subset_requested","unauthorized_write_denied","forged_handle_denied","all_task_frames_reclaimed"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/gates/STORE_V1_FORMAT_PR_MERGE.json b/crates/aien-proof/gates/STORE_V1_FORMAT_PR_MERGE.json new file mode 100644 index 00000000..bacaeb03 --- /dev/null +++ b/crates/aien-proof/gates/STORE_V1_FORMAT_PR_MERGE.json @@ -0,0 +1,9 @@ +{ + "gate": "STORE_V1_FORMAT_PR_MERGE", + "description": "Allows the narrow ADR 0015 and pure Store v1 format/golden-vector PR to merge after strict main verification. It does not authorize P3 QEMU qualification or physical storage mutation, and does not require full SEED-0B completion.", + "requires": [ + {"name":"ADR0015 frozen","kind":"adr0015-format","min_tier":"HOST_TEST","assertions":["adr0015_accepted_frozen"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"Store v1 format and golden vectors","kind":"store-v1-format-golden-vectors","min_tier":"HOST_TEST","assertions":["store_format_v1_valid","store_golden_vectors_match"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"}, + {"name":"STRICT_MAIN","kind":"strict-main-verification","min_tier":"HOST_TEST","assertions":["strict_main_pass"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/src/chain.rs b/crates/aien-proof/src/chain.rs new file mode 100644 index 00000000..d9aa8ba8 --- /dev/null +++ b/crates/aien-proof/src/chain.rs @@ -0,0 +1,434 @@ +//! Receipt dependency graph verification (`aien-proof verify-chain`). +//! +//! Rules, all fail closed: +//! - dependency IDs are immutable hashes; bytes that do not hash to the +//! claimed ID are rejected, so substitution and duplicates with different +//! bytes cannot pass; +//! - cycles are rejected; +//! - a missing dependency yields INCOMPLETE, never PASS; +//! - validation traverses the whole reachable graph; +//! - a PASS root requires every reachable receipt to be PASS; a FAIL +//! dependency fails the chain, BLOCKED or INCOMPLETE dependencies block it; +//! - TEST_ONLY_TRUST ancestry can never support a PRODUCTION receipt; +//! - a QEMU tier receipt can never satisfy a physical tier requirement +//! (enforced per requirement in [`crate::gate`]). + +use std::collections::{BTreeMap, BTreeSet}; +use std::path::{Path, PathBuf}; + +use crate::evidence::{load_receipt, verify_with_store, Receipt, Report, Tier, Verdict}; + +/// Full reachable graph report for one root receipt. +#[derive(Debug, Clone)] +pub struct ChainReport { + pub root: String, + pub status: Verdict, + pub lines: Vec, + pub reasons: Vec, +} + +/// One visited receipt in traversal order. +#[derive(Debug, Clone)] +pub struct ChainLine { + pub id: String, + pub kind: String, + pub tier: Tier, + pub status: Verdict, + pub depth: usize, + pub note: String, +} + +/// Dependency resolver: receipt ID to verified receipt plus its report. +pub type Resolver<'a> = &'a dyn Fn(&str) -> Result<(Receipt, Report), String>; + +/// Verify the complete reachable receipt graph for the receipt file at +/// `path`. Dependencies resolve from `store`. +pub fn verify_chain(path: &Path, store: &Path) -> Result { + let text = std::fs::read(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; + let (root, root_report) = verify_with_store(&text, store)?; + let resolve = |id: &str| -> Result<(Receipt, Report), String> { + let receipt = load_receipt(store, id)?; + let bytes = std::fs::read(store.join("receipts").join(format!("{id}.json"))) + .map_err(|e| e.to_string())?; + let (_, report) = verify_with_store(&bytes, store)?; + Ok((receipt, report)) + }; + Ok(verify_graph(&root, &root_report, store, &resolve)) +} + +struct Walker<'a> { + store: &'a Path, + resolve: Resolver<'a>, + graph: BTreeMap, + visiting: BTreeSet, + done: BTreeSet, + lines: Vec, + missing: Vec, + failed: Vec, + blocked: Vec, + cycle: Option, +} + +impl<'a> Walker<'a> { + fn visit(&mut self, id: &str, depth: usize) { + if self.cycle.is_some() || self.done.contains(id) { + return; + } + if self.visiting.contains(id) { + self.cycle = Some(format!("dependency cycle through receipt {id}")); + return; + } + self.visiting.insert(id.to_string()); + let (receipt, report) = match (self.resolve)(id) { + Ok(v) => v, + Err(e) => { + self.missing.push(format!("{id}: {e}")); + self.lines.push(ChainLine { + id: id.to_string(), + kind: "?".to_string(), + tier: Tier::TestOnlyTrust, + status: Verdict::Incomplete, + depth, + note: "MISSING".to_string(), + }); + self.visiting.remove(id); + self.done.insert(id.to_string()); + return; + } + }; + let lease_report = crate::lease::lease_status(&receipt, self.store); + let lease_bad = lease_report + .as_ref() + .is_some_and(|r| r.status != Verdict::Pass); + let mut note = report.reasons.join("; "); + if let Some(lease) = &lease_report { + if lease.status != Verdict::Pass { + if !note.is_empty() { + note.push_str("; "); + } + note.push_str(&lease.reasons.join("; ")); + match lease.status { + Verdict::Fail => self.failed.push(format!("{id}: lease binding failed")), + Verdict::Incomplete => self.missing.push(format!("{id}: lease incomplete")), + _ => self + .blocked + .push(format!("{id}: lease {}", lease.status.as_str())), + } + } + } + let status = if lease_bad && report.status == Verdict::Pass { + Verdict::Incomplete + } else { + report.status + }; + match status { + Verdict::Pass => {} + Verdict::Fail => self.failed.push(format!("{id}: dependency records FAIL")), + Verdict::Blocked => self.blocked.push(format!("{id}: dependency BLOCKED")), + Verdict::Incomplete => self.missing.push(format!("{id}: dependency INCOMPLETE")), + Verdict::Skipped => self.blocked.push(format!("{id}: dependency SKIPPED")), + } + if note.is_empty() { + note = status.as_str().to_string(); + } + self.lines.push(ChainLine { + id: id.to_string(), + kind: receipt.kind.clone(), + tier: receipt.tier, + status, + depth, + note, + }); + self.graph.insert(id.to_string(), receipt.clone()); + let mut deps = receipt.dependencies.clone(); + deps.sort(); + for dep in deps { + self.visit(&dep.to_ascii_lowercase(), depth + 1); + } + self.visiting.remove(id); + self.done.insert(id.to_string()); + } +} + +/// Graph traversal over an abstract resolver. The file backed [`verify_chain`] +/// supplies a store resolver; tests supply an in memory resolver so cycles, +/// which hash linked IDs make infeasible to construct on disk, are still +/// exercised directly. +pub fn verify_graph( + root: &Receipt, + root_report: &Report, + store: &Path, + resolve: Resolver<'_>, +) -> ChainReport { + let root_id = root.id.to_ascii_lowercase(); + let mut walker = Walker { + store, + resolve, + graph: BTreeMap::new(), + visiting: BTreeSet::new(), + done: BTreeSet::new(), + lines: Vec::new(), + missing: Vec::new(), + failed: Vec::new(), + blocked: Vec::new(), + cycle: None, + }; + let mut reasons: Vec = Vec::new(); + + if root_report.status == Verdict::Fail { + walker.failed.push(format!("{root_id}: root receipt FAIL")); + } + let mut deps = root.dependencies.clone(); + deps.sort(); + for dep in deps { + walker.visit(&dep.to_ascii_lowercase(), 1); + } + walker + .lines + .sort_by(|a, b| (a.depth, &a.id).cmp(&(b.depth, &b.id))); + + if let Some(c) = walker.cycle { + return ChainReport { + root: root_id, + status: Verdict::Fail, + lines: walker.lines, + reasons: vec![c], + }; + } + // Contamination: test only ancestry under a production root. + if root.tier == Tier::Production { + let bad: Vec = walker + .graph + .values() + .filter(|r| r.tier == Tier::TestOnlyTrust) + .map(|r| r.id.clone()) + .collect(); + if !bad.is_empty() { + reasons.push(format!( + "PRODUCTION receipt depends on TEST_ONLY_TRUST receipts: {}", + bad.join(", ") + )); + return ChainReport { + root: root_id, + status: Verdict::Fail, + lines: walker.lines, + reasons, + }; + } + } + + let status = if !walker.failed.is_empty() { + reasons.extend(walker.failed.clone()); + Verdict::Fail + } else if root_report.status == Verdict::Fail { + reasons.extend(root_report.reasons.clone()); + Verdict::Fail + } else if !walker.missing.is_empty() { + reasons.extend(walker.missing.clone()); + reasons.push("missing or incomplete dependencies never yield PASS".to_string()); + Verdict::Incomplete + } else if !walker.blocked.is_empty() { + reasons.extend(walker.blocked.clone()); + Verdict::Blocked + } else { + match root_report.status { + Verdict::Pass => { + reasons.push(format!( + "chain OK: root {root_id} plus {} reachable receipts all PASS", + walker.graph.len() + )); + Verdict::Pass + } + other => { + reasons.extend(root_report.reasons.clone()); + other + } + } + }; + ChainReport { + root: root_id, + status, + lines: walker.lines, + reasons, + } +} + +/// True when a receipt at `have` tier satisfies a requirement of `need` tier. +/// Physical requirements need physical evidence; test only trust satisfies +/// nothing but itself. +pub fn tier_satisfies(need: Tier, have: Tier) -> bool { + if have == Tier::TestOnlyTrust { + return need == Tier::TestOnlyTrust; + } + if need.is_physical() && !have.is_physical() { + return false; + } + have.rank() >= need.rank() +} + +pub fn chain_path_arg(path: &str) -> PathBuf { + PathBuf::from(path) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evidence::fixtures::{sample, sealed}; + use crate::evidence::{store_receipt, Mutation, Report}; + + fn qemu_receipt(kind: &str, deps: Vec) -> Receipt { + let mut r = sample(); + r.kind = kind.to_string(); + r.dependencies = deps; + sealed(r) + } + + fn put(store: &Path, r: &Receipt) -> String { + store_receipt(store, r).unwrap() + } + + fn write_root(dir: &Path, r: &Receipt) -> PathBuf { + let path = dir.join("root.json"); + let text = serde_json::to_string_pretty(r).unwrap(); + std::fs::write(&path, format!("{text}\n")).unwrap(); + path + } + + #[test] + fn empty_chain_passes() { + let store = crate::testutil::temp_dir("chain-empty"); + let r = qemu_receipt("m3", vec![]); + let id = put(&store, &r); + let dir = crate::testutil::temp_dir("chain-empty-root"); + let path = write_root(&dir, &r); + let report = verify_chain(&path, &store).unwrap(); + assert_eq!(report.status, Verdict::Pass); + assert_eq!(report.root, id); + } + + #[test] + fn missing_dependency_is_incomplete_never_pass() { + let store = crate::testutil::temp_dir("chain-missing"); + let r = sealed(qemu_receipt("seed-0b-machine1", vec!["f".repeat(64)])); + let dir = crate::testutil::temp_dir("chain-missing-root"); + let path = write_root(&dir, &r); + let report = verify_chain(&path, &store).unwrap(); + assert_eq!(report.status, Verdict::Incomplete); + } + + #[test] + fn tampered_dependency_file_fails_closed() { + let store = crate::testutil::temp_dir("chain-tamper"); + let dep = put(&store, &qemu_receipt("m3", vec![])); + let root = sealed(qemu_receipt("seed", vec![dep.clone()])); + let dir = crate::testutil::temp_dir("chain-tamper-root"); + let path = write_root(&dir, &root); + assert_eq!(verify_chain(&path, &store).unwrap().status, Verdict::Pass); + let dep_path = store.join("receipts").join(format!("{dep}.json")); + let text = std::fs::read_to_string(&dep_path).unwrap().replacen( + "artifact_signature_valid", + "artifact_signature_tampered", + 1, + ); + std::fs::write(&dep_path, text).unwrap(); + assert_eq!( + verify_chain(&path, &store).unwrap().status, + Verdict::Incomplete + ); + } + + #[test] + fn cyclic_dependencies_rejected() { + // Hash linked IDs make real cycles infeasible to construct on disk, + // which is itself a defense. The traversal guard is exercised here + // through an in memory resolver with a genuine two node cycle. + let store = crate::testutil::temp_dir("chain-cycle"); + let mut a = sample(); + a.id = "a".repeat(64); + a.kind = "cycle-a".to_string(); + a.dependencies = vec!["b".repeat(64)]; + let mut b = sample(); + b.id = "b".repeat(64); + b.kind = "cycle-b".to_string(); + b.dependencies = vec!["a".repeat(64)]; + let map: BTreeMap = BTreeMap::from([ + ("a".repeat(64), (a.clone(), Report::pass("ok"))), + ("b".repeat(64), (b.clone(), Report::pass("ok"))), + ]); + let resolve = |id: &str| map.get(id).cloned().ok_or_else(|| "missing".to_string()); + let mut root = sample(); + root.id = "r".repeat(64); + root.kind = "cycle-root".to_string(); + root.dependencies = vec!["a".repeat(64)]; + let report = verify_graph(&root, &Report::pass("ok"), &store, &resolve); + assert_eq!(report.status, Verdict::Fail); + assert!(report.reasons.iter().any(|r| r.contains("cycle"))); + } + + #[test] + fn blocked_dependency_blocks_chain_never_passes() { + let store = crate::testutil::temp_dir("chain-blocked"); + let mut dep = sample(); + dep.kind = "qemu-qual".to_string(); + dep.result = Verdict::Blocked; + let dep_id = put(&store, &sealed(dep)); + let root = sealed(qemu_receipt("seed", vec![dep_id])); + let dir = crate::testutil::temp_dir("chain-blocked-root"); + let path = write_root(&dir, &root); + let report = verify_chain(&path, &store).unwrap(); + assert_eq!(report.status, Verdict::Blocked); + } + + #[test] + fn failed_dependency_fails_chain() { + let store = crate::testutil::temp_dir("chain-fail"); + let mut dep = sample(); + dep.kind = "qemu-qual".to_string(); + dep.result = Verdict::Fail; + let dep_id = put(&store, &sealed(dep)); + let root = sealed(qemu_receipt("seed", vec![dep_id])); + let dir = crate::testutil::temp_dir("chain-fail-root"); + let path = write_root(&dir, &root); + assert_eq!(verify_chain(&path, &store).unwrap().status, Verdict::Fail); + } + + #[test] + fn illegal_tier_escalation_fails() { + // PRODUCTION root with TEST_ONLY_TRUST ancestry. + let store = crate::testutil::temp_dir("chain-tier"); + let mut t = sample(); + t.kind = "lab-note".to_string(); + t.tier = Tier::TestOnlyTrust; + t.env_class = "TEST_ONLY_TRUST".to_string(); + let t_id = put(&store, &sealed(t)); + let mut p = sample(); + p.kind = "prod-release".to_string(); + p.tier = Tier::Production; + p.env_class = "PRODUCTION".to_string(); + p.authority = "release board 2026-09".to_string(); + p.dependencies = vec![t_id]; + let p = sealed(p); + let dir = crate::testutil::temp_dir("chain-tier-root"); + let path = write_root(&dir, &p); + assert_eq!(verify_chain(&path, &store).unwrap().status, Verdict::Fail); + } + + #[test] + fn tier_satisfaction_matrix() { + assert!(tier_satisfies(Tier::Qemu, Tier::Qemu)); + assert!(tier_satisfies(Tier::Qemu, Tier::Machine1Mutating)); + assert!(!tier_satisfies(Tier::Machine1Attended, Tier::Qemu)); + assert!(!tier_satisfies(Tier::Machine1Attended, Tier::QemuSecurity)); + assert!(tier_satisfies( + Tier::Machine1ReadOnly, + Tier::Machine1Mutating + )); + assert!(!tier_satisfies(Tier::HostTest, Tier::TestOnlyTrust)); + assert!(tier_satisfies(Tier::TestOnlyTrust, Tier::TestOnlyTrust)); + } + + #[test] + fn mutation_import_used() { + assert_eq!(Mutation::None.as_str(), "NONE"); + } +} diff --git a/crates/aien-proof/src/evidence.rs b/crates/aien-proof/src/evidence.rs new file mode 100644 index 00000000..678ec357 --- /dev/null +++ b/crates/aien-proof/src/evidence.rs @@ -0,0 +1,1235 @@ +//! Canonical evidence receipts (EvidenceReceiptV1). +//! +//! A receipt is a structured proof object: exact source, exact artifacts, +//! exact machine, structured assertions, and links to earlier receipts, to +//! Crumb ledger events, and to the resource lease that protected the run. +//! +//! Identity rule: the receipt ID is the BLAKE3 hash of an explicit canonical +//! byte encoding defined in [`canonical_bytes`]. The human readable JSON +//! rendering is not canonical. Map ordering, local paths, string timestamp +//! formats, and Rust struct layout never affect the ID, because the canonical +//! form uses fixed field order, length prefixed strings, and big endian +//! integers throughout. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; +use std::fs; +use std::path::Path; + +pub const SCHEMA: &str = "EvidenceReceiptV1"; +pub const SCHEMA_VERSION: u32 = 1; +/// Domain separator for the canonical encoding. +pub const DOMAIN: &[u8] = b"AIEN_EVIDENCE_RECEIPT_V1"; +/// Features a receipt may require. Verification rejects anything else. +const KNOWN_FEATURES: &[&str] = &["v1-base"]; +/// Subdirectory of the proof board root holding receipts. +pub const RECEIPT_DIR: &str = "receipts"; + +/// Final result of a receipt. Missing data never collapses into `Pass`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "UPPERCASE")] +pub enum Verdict { + Pass, + Fail, + Blocked, + Incomplete, + Skipped, +} + +impl Verdict { + pub fn parse(s: &str) -> Option { + match s.to_ascii_uppercase().as_str() { + "PASS" => Some(Verdict::Pass), + "FAIL" => Some(Verdict::Fail), + "BLOCKED" => Some(Verdict::Blocked), + "INCOMPLETE" => Some(Verdict::Incomplete), + "SKIPPED" => Some(Verdict::Skipped), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Verdict::Pass => "PASS", + Verdict::Fail => "FAIL", + Verdict::Blocked => "BLOCKED", + Verdict::Incomplete => "INCOMPLETE", + Verdict::Skipped => "SKIPPED", + } + } + + fn code(self) -> u8 { + match self { + Verdict::Pass => 0, + Verdict::Fail => 1, + Verdict::Blocked => 2, + Verdict::Incomplete => 3, + Verdict::Skipped => 4, + } + } + + fn from_code(b: u8) -> Option { + match b { + 0 => Some(Verdict::Pass), + 1 => Some(Verdict::Fail), + 2 => Some(Verdict::Blocked), + 3 => Some(Verdict::Incomplete), + 4 => Some(Verdict::Skipped), + _ => None, + } + } +} + +/// Qualification tier. A QEMU proof is never physical qualification. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +pub enum Tier { + #[serde(rename = "TEST_ONLY_TRUST")] + TestOnlyTrust, + #[serde(rename = "HOST_TEST")] + HostTest, + #[serde(rename = "QEMU")] + Qemu, + #[serde(rename = "QEMU_SECURITY")] + QemuSecurity, + #[serde(rename = "MACHINE1_READ_ONLY")] + Machine1ReadOnly, + #[serde(rename = "MACHINE1_ATTENDED")] + Machine1Attended, + #[serde(rename = "MACHINE1_MUTATING")] + Machine1Mutating, + #[serde(rename = "PRODUCTION")] + Production, +} + +impl Tier { + pub fn parse(s: &str) -> Option { + match s { + "TEST_ONLY_TRUST" => Some(Tier::TestOnlyTrust), + "HOST_TEST" => Some(Tier::HostTest), + "QEMU" => Some(Tier::Qemu), + "QEMU_SECURITY" => Some(Tier::QemuSecurity), + "MACHINE1_READ_ONLY" => Some(Tier::Machine1ReadOnly), + "MACHINE1_ATTENDED" => Some(Tier::Machine1Attended), + "MACHINE1_MUTATING" => Some(Tier::Machine1Mutating), + "PRODUCTION" => Some(Tier::Production), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Tier::TestOnlyTrust => "TEST_ONLY_TRUST", + Tier::HostTest => "HOST_TEST", + Tier::Qemu => "QEMU", + Tier::QemuSecurity => "QEMU_SECURITY", + Tier::Machine1ReadOnly => "MACHINE1_READ_ONLY", + Tier::Machine1Attended => "MACHINE1_ATTENDED", + Tier::Machine1Mutating => "MACHINE1_MUTATING", + Tier::Production => "PRODUCTION", + } + } + + /// Rank used for minimum tier checks. Higher means stronger evidence. + pub fn rank(self) -> u8 { + match self { + Tier::TestOnlyTrust => 0, + Tier::HostTest => 1, + Tier::Qemu => 2, + Tier::QemuSecurity => 3, + Tier::Machine1ReadOnly => 4, + Tier::Machine1Attended => 5, + Tier::Machine1Mutating => 6, + Tier::Production => 7, + } + } + + pub fn is_hardware(self) -> bool { + matches!( + self, + Tier::Machine1ReadOnly | Tier::Machine1Attended | Tier::Machine1Mutating + ) + } + + pub fn is_physical(self) -> bool { + self.is_hardware() || self == Tier::Production + } +} + +/// Hardware mutation classification. Descriptive, not authorization. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Mutation { + #[serde(rename = "NONE")] + None, + #[serde(rename = "VOLATILE_ONLY")] + VolatileOnly, + #[serde(rename = "REMOVABLE_MEDIA_ONLY")] + RemovableMediaOnly, + #[serde(rename = "ONE_TIME_BOOT_SELECTION")] + OneTimeBootSelection, + #[serde(rename = "BOUNDED_TEST_REGION_WRITE")] + BoundedTestRegionWrite, + #[serde(rename = "BOOT_CONFIGURATION_CHANGE")] + BootConfigurationChange, + #[serde(rename = "TRUST_ROOT_CHANGE")] + TrustRootChange, + #[serde(rename = "TPM_POLICY_CHANGE")] + TpmPolicyChange, + #[serde(rename = "DESTRUCTIVE_STORAGE")] + DestructiveStorage, +} + +impl Mutation { + pub fn parse(s: &str) -> Option { + match s { + "NONE" => Some(Mutation::None), + "VOLATILE_ONLY" => Some(Mutation::VolatileOnly), + "REMOVABLE_MEDIA_ONLY" => Some(Mutation::RemovableMediaOnly), + "ONE_TIME_BOOT_SELECTION" => Some(Mutation::OneTimeBootSelection), + "BOUNDED_TEST_REGION_WRITE" => Some(Mutation::BoundedTestRegionWrite), + "BOOT_CONFIGURATION_CHANGE" => Some(Mutation::BootConfigurationChange), + "TRUST_ROOT_CHANGE" => Some(Mutation::TrustRootChange), + "TPM_POLICY_CHANGE" => Some(Mutation::TpmPolicyChange), + "DESTRUCTIVE_STORAGE" => Some(Mutation::DestructiveStorage), + _ => None, + } + } + + pub fn as_str(self) -> &'static str { + match self { + Mutation::None => "NONE", + Mutation::VolatileOnly => "VOLATILE_ONLY", + Mutation::RemovableMediaOnly => "REMOVABLE_MEDIA_ONLY", + Mutation::OneTimeBootSelection => "ONE_TIME_BOOT_SELECTION", + Mutation::BoundedTestRegionWrite => "BOUNDED_TEST_REGION_WRITE", + Mutation::BootConfigurationChange => "BOOT_CONFIGURATION_CHANGE", + Mutation::TrustRootChange => "TRUST_ROOT_CHANGE", + Mutation::TpmPolicyChange => "TPM_POLICY_CHANGE", + Mutation::DestructiveStorage => "DESTRUCTIVE_STORAGE", + } + } + + fn severity(self) -> u8 { + match self { + Mutation::None => 0, + Mutation::VolatileOnly => 1, + Mutation::RemovableMediaOnly => 2, + Mutation::OneTimeBootSelection => 3, + Mutation::BoundedTestRegionWrite => 4, + Mutation::BootConfigurationChange => 5, + Mutation::TrustRootChange => 6, + Mutation::TpmPolicyChange => 6, + Mutation::DestructiveStorage => 7, + } + } + + fn code(self) -> u8 { + match self { + Mutation::None => 0, + Mutation::VolatileOnly => 1, + Mutation::RemovableMediaOnly => 2, + Mutation::OneTimeBootSelection => 3, + Mutation::BoundedTestRegionWrite => 4, + Mutation::BootConfigurationChange => 5, + Mutation::TrustRootChange => 6, + Mutation::TpmPolicyChange => 7, + Mutation::DestructiveStorage => 8, + } + } + + fn from_code(b: u8) -> Option { + match b { + 0 => Some(Mutation::None), + 1 => Some(Mutation::VolatileOnly), + 2 => Some(Mutation::RemovableMediaOnly), + 3 => Some(Mutation::OneTimeBootSelection), + 4 => Some(Mutation::BoundedTestRegionWrite), + 5 => Some(Mutation::BootConfigurationChange), + 6 => Some(Mutation::TrustRootChange), + 7 => Some(Mutation::TpmPolicyChange), + 8 => Some(Mutation::DestructiveStorage), + _ => None, + } + } +} + +/// One structured assertion. Console lines may exist, but this record is the +/// proof: stable ID, expected and observed values, outcome, and source. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Assertion { + pub id: String, + #[serde(default)] + pub expected: String, + #[serde(default)] + pub observed: String, + pub pass: bool, + #[serde(default)] + pub source: String, + #[serde(default)] + pub note: String, +} + +/// Reference to a Crumb ledger event recorded for the run. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LedgerRef { + pub index: u64, + /// Hex of the ledger event hash. + pub hash: String, +} + +/// Binding to the exclusive resource lease that protected a hardware run. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct LeaseRef { + /// Hold ID (hex of the hold audit event hash). + pub hold_id: String, + /// Resource the lease covered, for example `machine-1`. + pub resource: String, +} + +/// Canonical evidence receipt, version 1. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Receipt { + pub schema: String, + pub version: u32, + /// BLAKE3 hex of the canonical encoding. Must recompute exactly. + pub id: String, + /// Free form procedure class, for example `seed-0b-qemu`. + pub kind: String, + pub tier: Tier, + pub result: Verdict, + /// Unix seconds. Metadata only; stored as an integer so no string + /// clock format can affect identity. + pub timestamp: u64, + pub repo: String, + /// Exact source commit, lowercase hex, 40 or 64 digits. + pub commit: String, + /// True when the source tree had uncommitted changes. + pub dirty: bool, + /// Compiler and flag identity, for example `rustc -vV` output. + pub toolchain: String, + /// Command or procedure identity, for example the joined command line. + pub procedure: String, + /// Machine or resource identity, for example `machine-1`. + pub machine: String, + /// Environment classification. Must equal the tier string, so a QEMU + /// run can never be labeled as physical qualification. + pub env_class: String, + pub input_artifacts: Vec, + pub output_artifacts: Vec, + pub assertions: Vec, + /// Immutable receipt IDs (hashes) this receipt depends on. + pub dependencies: Vec, + pub declared_mutation: Mutation, + pub observed_mutation: Mutation, + #[serde(default)] + pub authority: String, + /// BLAKE3 hex of the complete captured output. + pub output_digest: String, + #[serde(default)] + pub external_refs: Vec, + #[serde(default)] + pub ledger: Option, + #[serde(default)] + pub lease: Option, + /// Features the verifier must understand. Unknown entries fail closed. + #[serde(default)] + pub required_features: Vec, + /// Must stay empty. Any content fails verification. + #[serde(default)] + pub reserved: String, +} + +/// Verification outcome for one receipt or chain. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Report { + pub status: Verdict, + pub reasons: Vec, +} + +impl Report { + pub fn pass(reason: &str) -> Self { + Report { + status: Verdict::Pass, + reasons: vec![reason.to_string()], + } + } + + pub fn fail(reasons: Vec) -> Self { + Report { + status: Verdict::Fail, + reasons, + } + } + + pub fn closed(status: Verdict, reasons: Vec) -> Self { + Report { status, reasons } + } + + pub fn ok(&self) -> bool { + self.status == Verdict::Pass + } +} + +fn is_hex(s: &str) -> bool { + !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit()) +} + +fn is_lower_hex(s: &str) -> bool { + !s.is_empty() + && s.bytes() + .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) +} + +fn hex_to_bytes(s: &str) -> Option> { + if !s.len().is_multiple_of(2) || !is_hex(s) { + return None; + } + let mut out = Vec::with_capacity(s.len() / 2); + let bytes = s.as_bytes(); + let mut i = 0; + while i < bytes.len() { + let hi = char::from(bytes[i]).to_digit(16)?; + let lo = char::from(bytes[i + 1]).to_digit(16)?; + out.push(((hi << 4) | lo) as u8); + i += 2; + } + Some(out) +} + +pub fn check_commit(commit: &str) -> Result<(), String> { + if (commit.len() == 40 || commit.len() == 64) && is_lower_hex(commit) { + Ok(()) + } else { + Err(format!( + "commit must be 40 or 64 lowercase hex digits, got {commit:?}" + )) + } +} + +fn check_digest_list(name: &str, items: &[String]) -> Result<(), String> { + for item in items { + if let Some((algo, hex)) = item.split_once(':') { + match algo { + "blake3" | "sha256" | "sha512" => {} + _ => return Err(format!("{name}: unknown digest algo in {item:?}")), + } + if hex.len() < 32 || hex.len() % 2 != 0 || !is_hex(hex) { + return Err(format!("{name}: bad digest hex in {item:?}")); + } + } else if item.len() == 64 && is_hex(item) { + // Bare 64 digit hex, read as BLAKE3. + } else { + return Err(format!( + "{name}: digest must be : or 64 hex digits, got {item:?}" + )); + } + } + Ok(()) +} + +fn push_str(out: &mut Vec, s: &str) { + out.extend_from_slice(&(s.len() as u64).to_be_bytes()); + out.extend_from_slice(s.as_bytes()); +} + +fn push_u32(out: &mut Vec, v: u32) { + out.extend_from_slice(&v.to_be_bytes()); +} + +fn push_u64(out: &mut Vec, v: u64) { + out.extend_from_slice(&v.to_be_bytes()); +} + +fn sorted_unique(items: &[String]) -> Vec { + let set: BTreeSet<&str> = items.iter().map(String::as_str).collect(); + set.into_iter().map(str::to_string).collect() +} + +/// Build the canonical byte encoding. Every format violation is an error, +/// so malformed input fails closed before any hash is compared. +pub fn canonical_bytes(r: &Receipt) -> Result, String> { + if r.schema != SCHEMA { + return Err(format!("unknown receipt schema {:?}", r.schema)); + } + if r.version != SCHEMA_VERSION { + return Err(format!("unsupported receipt version {}", r.version)); + } + for f in &r.required_features { + if !KNOWN_FEATURES.contains(&f.as_str()) { + return Err(format!("unknown required receipt feature {f:?}")); + } + } + if !r.reserved.is_empty() { + return Err("reserved field must be empty".to_string()); + } + if r.kind.is_empty() { + return Err("receipt kind must not be empty".to_string()); + } + if r.repo.is_empty() { + return Err("repo must not be empty".to_string()); + } + check_commit(&r.commit)?; + if r.procedure.is_empty() { + return Err("procedure identity must not be empty".to_string()); + } + if r.machine.is_empty() { + return Err("machine identity must not be empty".to_string()); + } + if r.env_class != r.tier.as_str() { + return Err(format!( + "env_class {:?} contradicts tier {:?}", + r.env_class, + r.tier.as_str() + )); + } + check_digest_list("input_artifacts", &r.input_artifacts)?; + check_digest_list("output_artifacts", &r.output_artifacts)?; + if r.output_digest.len() != 64 || !is_hex(&r.output_digest) { + return Err("output_digest must be 64 hex digits (BLAKE3)".to_string()); + } + let output_digest = hex_to_bytes(&r.output_digest).ok_or("bad output_digest")?; + if r.assertions.is_empty() && r.result == Verdict::Pass { + return Err("PASS receipts must carry at least one assertion".to_string()); + } + let mut seen_assertions = BTreeSet::new(); + for a in &r.assertions { + if a.id.is_empty() { + return Err("assertion id must not be empty".to_string()); + } + if !seen_assertions.insert(a.id.clone()) { + return Err(format!("duplicate assertion id {:?}", a.id)); + } + } + for d in &r.dependencies { + if d.len() != 64 || !is_hex(d) { + return Err(format!("dependency {d:?} is not a 64 digit receipt hash")); + } + } + if r.observed_mutation.severity() > r.declared_mutation.severity() { + return Err(format!( + "observed mutation {} exceeds declared mutation {}", + r.observed_mutation.as_str(), + r.declared_mutation.as_str() + )); + } + check_tier_mutation(r.tier, r.observed_mutation)?; + if r.tier == Tier::Production { + let low = r.authority.to_ascii_lowercase(); + if r.authority.trim().is_empty() { + return Err("PRODUCTION receipts require an authority reference".to_string()); + } + if low.contains("test-only") || low.contains("test_only") || low.contains("testonly") { + return Err("a TEST_ONLY signer cannot produce a PRODUCTION receipt".to_string()); + } + } + if r.tier.is_hardware() && r.lease.is_none() { + // Not a canonical encoding failure; verification reports INCOMPLETE. + } + if let Some(ledger) = &r.ledger { + if ledger.hash.len() != 64 || !is_hex(&ledger.hash) { + return Err("ledger hash must be 64 hex digits".to_string()); + } + } + if let Some(lease) = &r.lease { + if lease.hold_id.len() != 64 || !is_hex(&lease.hold_id) { + return Err("lease hold_id must be 64 hex digits".to_string()); + } + if lease.resource.trim().is_empty() { + return Err("lease resource must not be empty".to_string()); + } + } + + let mut out = Vec::new(); + out.extend_from_slice(DOMAIN); + push_u32(&mut out, SCHEMA_VERSION); + push_str(&mut out, &r.kind); + push_str(&mut out, r.tier.as_str()); + out.push(r.result.code()); + push_str(&mut out, &r.repo); + push_str(&mut out, &r.commit); + out.push(u8::from(r.dirty)); + push_str(&mut out, &r.toolchain); + push_str(&mut out, &r.procedure); + push_str(&mut out, &r.machine); + push_str(&mut out, &r.env_class); + let inputs = sorted_unique(&r.input_artifacts); + push_u32(&mut out, inputs.len() as u32); + for item in &inputs { + push_str(&mut out, item); + } + let outputs = sorted_unique(&r.output_artifacts); + push_u32(&mut out, outputs.len() as u32); + for item in &outputs { + push_str(&mut out, item); + } + let mut assertions = r.assertions.clone(); + assertions.sort_by(|a, b| a.id.cmp(&b.id)); + push_u32(&mut out, assertions.len() as u32); + for a in &assertions { + push_str(&mut out, &a.id); + push_str(&mut out, &a.expected); + push_str(&mut out, &a.observed); + out.push(u8::from(a.pass)); + push_str(&mut out, &a.source); + push_str(&mut out, &a.note); + } + let deps = sorted_unique(&r.dependencies); + push_u32(&mut out, deps.len() as u32); + for d in &deps { + let raw = hex_to_bytes(d).ok_or("bad dependency hash")?; + out.extend_from_slice(&raw); + } + out.push(r.declared_mutation.code()); + out.push(r.observed_mutation.code()); + push_str(&mut out, &r.authority); + out.extend_from_slice(&output_digest); + let refs = sorted_unique(&r.external_refs); + push_u32(&mut out, refs.len() as u32); + for item in &refs { + push_str(&mut out, item); + } + match &r.ledger { + Some(ledger) => { + out.push(1); + push_u64(&mut out, ledger.index); + let raw = hex_to_bytes(&ledger.hash).ok_or("bad ledger hash")?; + out.extend_from_slice(&raw); + } + None => out.push(0), + } + match &r.lease { + Some(lease) => { + out.push(1); + let normalized = lease.hold_id.to_ascii_lowercase(); + let raw = hex_to_bytes(&normalized).ok_or("bad hold id")?; + out.extend_from_slice(&raw); + push_str(&mut out, &lease.resource); + } + None => out.push(0), + } + push_u64(&mut out, r.timestamp); + let feats = sorted_unique(&r.required_features); + push_u32(&mut out, feats.len() as u32); + for f in &feats { + push_str(&mut out, f); + } + push_u32(&mut out, 0); + Ok(out) +} + +/// Maximum observed hardware mutation allowed per tier. +fn check_tier_mutation(tier: Tier, observed: Mutation) -> Result<(), String> { + let max = match tier { + Tier::Machine1ReadOnly => Mutation::RemovableMediaOnly.severity(), + Tier::Machine1Attended => Mutation::BootConfigurationChange.severity(), + Tier::Machine1Mutating | Tier::Production => u8::MAX, + _ => Mutation::BoundedTestRegionWrite.severity(), + }; + if observed.severity() > max { + return Err(format!( + "tier {} cannot claim observed mutation {}", + tier.as_str(), + observed.as_str() + )); + } + if tier == Tier::Machine1ReadOnly + && matches!( + observed, + Mutation::BoundedTestRegionWrite + | Mutation::BootConfigurationChange + | Mutation::TrustRootChange + | Mutation::TpmPolicyChange + | Mutation::DestructiveStorage + ) + { + return Err(format!( + "a read-only Machine 1 run cannot claim mutation {}", + observed.as_str() + )); + } + Ok(()) +} + +/// Compute the canonical receipt ID. +pub fn receipt_id(r: &Receipt) -> Result { + let bytes = canonical_bytes(r)?; + Ok(blake3::hash(&bytes).to_hex().to_string()) +} + +struct Cursor<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Cursor<'a> { + fn take(&mut self, n: usize) -> Result<&'a [u8], String> { + let end = self.pos.saturating_add(n); + if end > self.bytes.len() { + return Err("canonical encoding truncated".to_string()); + } + let slice = &self.bytes[self.pos..end]; + self.pos = end; + Ok(slice) + } + + fn byte(&mut self) -> Result { + Ok(self.take(1)?[0]) + } + + fn u32_be(&mut self) -> Result { + let b = self.take(4)?; + Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]])) + } + + fn u64_be(&mut self) -> Result { + let b = self.take(8)?; + Ok(u64::from_be_bytes([ + b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], + ])) + } + + fn text(&mut self) -> Result { + let len = self.u64_be()? as usize; + if len > 16 * 1024 * 1024 { + return Err("canonical string too long".to_string()); + } + let raw = self.take(len)?; + String::from_utf8(raw.to_vec()).map_err(|_| "canonical string not UTF-8".to_string()) + } + + fn count(&mut self) -> Result { + let n = self.u32_be()? as usize; + if n > 100_000 { + return Err("canonical list too long".to_string()); + } + Ok(n) + } + + fn hash_hex(&mut self) -> Result { + let raw = self.take(32)?; + Ok(raw.iter().map(|b| format!("{b:02x}")).collect()) + } +} + +/// Strictly decode canonical bytes back to a receipt. Anything malformed, +/// truncated, extended with trailing bytes, carrying unknown enum codes, +/// unknown features, or nonzero reserved content fails closed. The decoded +/// receipt's ID is recomputed from the bytes. +pub fn decode_canonical(bytes: &[u8]) -> Result { + let mut c = Cursor { bytes, pos: 0 }; + if c.take(DOMAIN.len())? != DOMAIN { + return Err("bad canonical domain separator".to_string()); + } + if c.u32_be()? != SCHEMA_VERSION { + return Err("unsupported canonical version".to_string()); + } + let kind = c.text()?; + let tier = Tier::parse(&c.text()?).ok_or("unknown tier in canonical encoding")?; + let result = Verdict::from_code(c.byte()?).ok_or("unknown result in canonical encoding")?; + let repo = c.text()?; + let commit = c.text()?; + let dirty = match c.byte()? { + 0 => false, + 1 => true, + _ => return Err("bad dirty flag in canonical encoding".to_string()), + }; + let toolchain = c.text()?; + let procedure = c.text()?; + let machine = c.text()?; + let env_class = c.text()?; + let mut input_artifacts = Vec::new(); + for _ in 0..c.count()? { + input_artifacts.push(c.text()?); + } + let mut output_artifacts = Vec::new(); + for _ in 0..c.count()? { + output_artifacts.push(c.text()?); + } + let mut assertions = Vec::new(); + for _ in 0..c.count()? { + assertions.push(Assertion { + id: c.text()?, + expected: c.text()?, + observed: c.text()?, + pass: match c.byte()? { + 0 => false, + 1 => true, + _ => return Err("bad assertion result in canonical encoding".to_string()), + }, + source: c.text()?, + note: c.text()?, + }); + } + let mut dependencies = Vec::new(); + for _ in 0..c.count()? { + dependencies.push(c.hash_hex()?); + } + let declared_mutation = + Mutation::from_code(c.byte()?).ok_or("unknown mutation in canonical encoding")?; + let observed_mutation = + Mutation::from_code(c.byte()?).ok_or("unknown mutation in canonical encoding")?; + let authority = c.text()?; + let output_digest = c.hash_hex()?; + let mut external_refs = Vec::new(); + for _ in 0..c.count()? { + external_refs.push(c.text()?); + } + let ledger = match c.byte()? { + 0 => None, + 1 => Some(LedgerRef { + index: c.u64_be()?, + hash: c.hash_hex()?, + }), + _ => return Err("bad ledger flag in canonical encoding".to_string()), + }; + let lease = match c.byte()? { + 0 => None, + 1 => { + let hold_id = c.hash_hex()?; + let resource = c.text()?; + Some(LeaseRef { hold_id, resource }) + } + _ => return Err("bad lease flag in canonical encoding".to_string()), + }; + let timestamp = c.u64_be()?; + let mut required_features = Vec::new(); + for _ in 0..c.count()? { + required_features.push(c.text()?); + } + if c.u32_be()? != 0 { + return Err("reserved field must be zero".to_string()); + } + if c.pos != bytes.len() { + return Err("trailing bytes after canonical encoding".to_string()); + } + let mut receipt = Receipt { + schema: SCHEMA.to_string(), + version: SCHEMA_VERSION, + id: String::new(), + kind, + tier, + result, + timestamp, + repo, + commit, + dirty, + toolchain, + procedure, + machine, + env_class, + input_artifacts, + output_artifacts, + assertions, + dependencies, + declared_mutation, + observed_mutation, + authority, + output_digest, + external_refs, + ledger, + lease, + required_features, + reserved: String::new(), + }; + // Re-encode to confirm the bytes were canonical and to mint the ID. + // Canonical encoding also re-applies every semantic check. + let reencoded = canonical_bytes(&receipt)?; + if reencoded != bytes { + return Err("canonical encoding not in canonical order".to_string()); + } + receipt.id = blake3::hash(bytes).to_hex().to_string(); + Ok(receipt) +} + +/// Parse receipt JSON and check identity plus internal consistency. +/// Ledger and lease stores are checked separately by [`verify_with_store`]. +pub fn verify_bytes(text: &[u8]) -> Result<(Receipt, Report), String> { + let receipt: Receipt = + serde_json::from_slice(text).map_err(|e| format!("receipt JSON invalid: {e}"))?; + let computed = receipt_id(&receipt)?; + if receipt.id.to_ascii_lowercase() != computed { + return Err(format!( + "receipt id mismatch: file claims {}, canonical identity is {}", + receipt.id, computed + )); + } + Ok((receipt.clone(), check_consistency(&receipt))) +} + +/// Consistency rules that need no store access. +fn check_consistency(r: &Receipt) -> Report { + let mut problems = Vec::new(); + if r.result == Verdict::Pass { + if r.assertions.iter().any(|a| !a.pass) { + problems.push("result is PASS but a structured assertion failed".to_string()); + } + if r.tier.is_hardware() && r.lease.is_none() { + return Report::closed( + Verdict::Incomplete, + vec![ + "hardware receipt has no resource lease binding; run under `aien-proof hold` and reference the hold".to_string(), + ], + ); + } + } + if r.result == Verdict::Blocked && r.tier.is_physical() { + problems.push("a run marked BLOCKED cannot close a gate".to_string()); + } + if problems.is_empty() { + match r.result { + Verdict::Pass => Report::pass("identity matches, assertions all pass"), + Verdict::Fail => { + Report::closed(Verdict::Fail, vec!["receipt records FAIL".to_string()]) + } + Verdict::Blocked => Report::closed( + Verdict::Blocked, + vec!["receipt records BLOCKED".to_string()], + ), + Verdict::Incomplete => Report::closed( + Verdict::Incomplete, + vec!["receipt records INCOMPLETE".to_string()], + ), + Verdict::Skipped => Report::closed( + Verdict::Skipped, + vec!["receipt records SKIPPED".to_string()], + ), + } + } else { + Report::fail(problems) + } +} + +/// Full single receipt verification against a proof store root: +/// identity, consistency, ledger event, and lease binding. +pub fn verify_with_store(text: &[u8], store: &Path) -> Result<(Receipt, Report), String> { + let (receipt, mut report) = verify_bytes(text)?; + if report.status == Verdict::Fail { + return Ok((receipt, report)); + } + if let Some(problem) = crate::ledger_bind::check_ledger_ref(&receipt, store)? { + return Ok((receipt, Report::fail(vec![problem]))); + } + if let Some(report2) = crate::lease::check_lease_ref(&receipt, store)? { + if report2.status != Verdict::Pass { + return Ok((receipt, report2)); + } + } + if report.status == Verdict::Pass { + // Recompute the consistency PASS line with store checks included. + report = Report::pass("identity, ledger, and lease bindings check out"); + if receipt.result != Verdict::Pass { + report = check_consistency(&receipt); + } + } + Ok((receipt, report)) +} + +/// Load a receipt from the store by ID. A file whose bytes hash to a +/// different ID is a duplicate ID collision and fails closed. +pub fn load_receipt(store: &Path, id: &str) -> Result { + let normalized = id.to_ascii_lowercase(); + if normalized.len() != 64 || !is_hex(&normalized) { + return Err(format!("receipt id {id:?} is not a 64 digit hash")); + } + let path = store.join(RECEIPT_DIR).join(format!("{normalized}.json")); + let text = fs::read(&path).map_err(|_| format!("missing dependency receipt {normalized}"))?; + let (receipt, _) = verify_bytes(&text)?; + if receipt.id.to_ascii_lowercase() != normalized { + return Err(format!( + "receipt file {normalized} holds bytes for receipt {}", + receipt.id + )); + } + Ok(receipt) +} + +/// Write a receipt into the store under its canonical ID. +pub fn store_receipt(store: &Path, receipt: &Receipt) -> Result { + let computed = receipt_id(receipt)?; + if receipt.id.to_ascii_lowercase() != computed { + return Err(format!( + "refusing to store: id {} does not match canonical {computed}", + receipt.id + )); + } + let dir = store.join(RECEIPT_DIR); + fs::create_dir_all(&dir).map_err(|e| e.to_string())?; + let path = dir.join(format!("{computed}.json")); + let mut owned = receipt.clone(); + owned.id = computed.clone(); + let text = serde_json::to_string_pretty(&owned).map_err(|e| e.to_string())?; + fs::write(&path, format!("{text}\n")).map_err(|e| e.to_string())?; + Ok(computed) +} + +/// List all receipt IDs present in the store. +pub fn list_receipts(store: &Path) -> Vec { + let mut ids = Vec::new(); + let dir = store.join(RECEIPT_DIR); + let entries = fs::read_dir(dir).into_iter().flatten().flatten(); + for entry in entries { + let name = entry.file_name().to_string_lossy().into_owned(); + if let Some(id) = name.strip_suffix(".json") { + if id.len() == 64 && is_hex(id) { + ids.push(id.to_ascii_lowercase()); + } + } + } + ids.sort(); + ids +} + +#[cfg(test)] +pub(crate) mod fixtures { + use super::*; + + pub fn sample() -> Receipt { + Receipt { + schema: SCHEMA.to_string(), + version: SCHEMA_VERSION, + id: String::new(), + kind: "seed-0b-qemu".to_string(), + tier: Tier::Qemu, + result: Verdict::Pass, + timestamp: 1_786_000_000, + repo: "https://github.com/aien-dev/aienos".to_string(), + commit: "a".repeat(40), + dirty: false, + toolchain: "rustc 1.90.0".to_string(), + procedure: "scripts/qemu_seed0b.sh".to_string(), + machine: "qemu-virt-aarch64".to_string(), + env_class: "QEMU".to_string(), + input_artifacts: vec!["blake3:".to_string() + &"b".repeat(64)], + output_artifacts: vec![], + assertions: vec![Assertion { + id: "artifact_signature_valid".to_string(), + expected: "valid".to_string(), + observed: "valid".to_string(), + pass: true, + source: "qemu_seed0b.sh".to_string(), + note: String::new(), + }], + dependencies: vec![], + declared_mutation: Mutation::None, + observed_mutation: Mutation::None, + authority: String::new(), + output_digest: "c".repeat(64), + external_refs: vec![], + ledger: None, + lease: None, + required_features: vec![], + reserved: String::new(), + } + } + + pub fn sealed(mut r: Receipt) -> Receipt { + let id = receipt_id(&r).unwrap(); + r.id = id; + r + } +} + +#[cfg(test)] +mod tests { + use super::fixtures::{sample, sealed}; + use super::*; + + #[test] + fn identity_is_stable_and_order_independent() { + let a = sealed(sample()); + let mut b = a.clone(); + b.input_artifacts + .push("blake3:".to_string() + &"a".repeat(64)); + b.input_artifacts.swap(0, 1); + b.assertions.push(Assertion { + id: "aaa_first".to_string(), + expected: "x".to_string(), + observed: "x".to_string(), + pass: true, + source: "s".to_string(), + note: String::new(), + }); + let mut c = b.clone(); + c.assertions.swap(0, 1); + // Different assertion sets differ; same set in any order matches. + assert_ne!(receipt_id(&a).unwrap(), receipt_id(&b).unwrap()); + assert_eq!(receipt_id(&b).unwrap(), receipt_id(&c).unwrap()); + let _ = a; + } + + #[test] + fn altered_bytes_fail_closed() { + let r = sealed(sample()); + let mut text = serde_json::to_vec(&r).unwrap(); + text[60] ^= 0x01; + assert!(verify_bytes(&text).is_err()); + } + + #[test] + fn changed_commit_changes_identity() { + let mut r = sample(); + let before = receipt_id(&r).unwrap(); + r.commit = "d".repeat(40); + assert_ne!(receipt_id(&r).unwrap(), before); + } + + #[test] + fn changed_artifact_hash_changes_identity() { + let mut r = sample(); + let before = receipt_id(&r).unwrap(); + r.input_artifacts = vec!["blake3:".to_string() + &"d".repeat(64)]; + assert_ne!(receipt_id(&r).unwrap(), before); + } + + #[test] + fn changed_assertion_result_fails_pass_claim() { + let mut r = sealed(sample()); + r.assertions[0].pass = false; + // Identity changed, so reseal, then consistency must fail the PASS. + let r = sealed(r); + let text = serde_json::to_vec(&r).unwrap(); + let (_, report) = verify_bytes(&text).unwrap(); + assert_eq!(report.status, Verdict::Fail); + } + + #[test] + fn pass_without_assertions_is_rejected() { + let mut r = sample(); + r.assertions.clear(); + assert!(receipt_id(&r).is_err()); + } + + #[test] + fn unknown_required_feature_fails_closed() { + let mut r = sample(); + r.required_features = vec!["v9-teleport".to_string()]; + assert!(receipt_id(&r).unwrap_err().contains("unknown required")); + } + + #[test] + fn reserved_content_fails_closed() { + let mut r = sample(); + r.reserved = "x".to_string(); + assert!(receipt_id(&r).unwrap_err().contains("reserved")); + } + + #[test] + fn malformed_canonical_inputs_fail() { + let mut r = sample(); + r.commit = "not-a-sha".to_string(); + assert!(receipt_id(&r).is_err()); + let mut r = sample(); + r.output_digest = "zz".to_string(); + assert!(receipt_id(&r).is_err()); + let mut r = sample(); + r.dependencies = vec!["nope".to_string()]; + assert!(receipt_id(&r).is_err()); + } + + #[test] + fn test_only_signer_cannot_mint_production() { + let mut r = sample(); + r.tier = Tier::Production; + r.env_class = "PRODUCTION".to_string(); + r.authority = "test-only lab signer".to_string(); + assert!(receipt_id(&r).unwrap_err().contains("TEST_ONLY")); + r.authority = String::new(); + assert!(receipt_id(&r).is_err()); + } + + #[test] + fn observed_beyond_declared_fails() { + let mut r = sample(); + r.tier = Tier::Machine1Mutating; + r.env_class = "MACHINE1_MUTATING".to_string(); + r.declared_mutation = Mutation::VolatileOnly; + r.observed_mutation = Mutation::BootConfigurationChange; + assert!(receipt_id(&r).unwrap_err().contains("exceeds declared")); + } + + #[test] + fn read_only_run_cannot_claim_mutation() { + let mut r = sample(); + r.tier = Tier::Machine1ReadOnly; + r.env_class = "MACHINE1_READ_ONLY".to_string(); + r.declared_mutation = Mutation::BootConfigurationChange; + r.observed_mutation = Mutation::BootConfigurationChange; + assert!(receipt_id(&r).is_err()); + } + + #[test] + fn hardware_receipt_without_lease_is_incomplete() { + let mut r = sample(); + r.tier = Tier::Machine1Attended; + r.env_class = "MACHINE1_ATTENDED".to_string(); + let r = sealed(r); + let text = serde_json::to_vec(&r).unwrap(); + let (_, report) = verify_bytes(&text).unwrap(); + assert_eq!(report.status, Verdict::Incomplete); + } + + #[test] + fn duplicate_id_with_different_bytes_fails() { + let r = sealed(sample()); + let mut tampered = r.clone(); + tampered.assertions[0].observed = "tampered".to_string(); + // Keep the original ID on different bytes. + let text = serde_json::to_vec(&tampered).unwrap(); + // Rewriting the ID field back to the original still fails identity. + let mut value: serde_json::Value = serde_json::from_slice(&text).unwrap(); + value["id"] = serde_json::Value::String(r.id.clone()); + let forged = serde_json::to_vec(&value).unwrap(); + assert!(verify_bytes(&forged).is_err()); + } + + #[test] + fn env_tier_contradiction_rejected() { + let mut r = sample(); + r.env_class = "MACHINE1_MUTATING".to_string(); + assert!(receipt_id(&r).unwrap_err().contains("contradicts")); + } + + #[test] + fn canonical_roundtrip() { + let r = sealed(sample()); + let bytes = canonical_bytes(&r).unwrap(); + let back = decode_canonical(&bytes).unwrap(); + assert_eq!(back, r); + } + + #[test] + fn malformed_canonical_encoding_fails() { + let r = sealed(sample()); + let bytes = canonical_bytes(&r).unwrap(); + // Truncated. + assert!(decode_canonical(&bytes[..bytes.len() - 5]).is_err()); + // Bad domain. + let mut bad = bytes.clone(); + bad[0] ^= 0xFF; + assert!(decode_canonical(&bad).is_err()); + // Trailing bytes. + let mut long = bytes.clone(); + long.push(0); + assert!(decode_canonical(&long).unwrap_err().contains("trailing")); + // Corruption inside a free form string still decodes structurally, + // but the identity changes, so tampering is always visible. + let mut kind_hit = bytes.clone(); + kind_hit[40] ^= 0x09; + let altered = decode_canonical(&kind_hit).unwrap(); + assert_ne!(altered.id, r.id); + assert_ne!(altered.kind, r.kind); + } + + #[test] + fn canonical_rejects_nonzero_reserved() { + let r = sealed(sample()); + let mut bytes = canonical_bytes(&r).unwrap(); + // Reserved is the final u32; set it nonzero. + let n = bytes.len(); + bytes[n - 1] = 1; + assert!(decode_canonical(&bytes).unwrap_err().contains("reserved")); + } +} diff --git a/crates/aien-proof/src/gate.rs b/crates/aien-proof/src/gate.rs new file mode 100644 index 00000000..0e6e2825 --- /dev/null +++ b/crates/aien-proof/src/gate.rs @@ -0,0 +1,1420 @@ +//! Gate manifests: small declarative descriptions of what closes a gate. +//! +//! The evidence system never decides architectural policy. It evaluates a +//! checked in manifest against stored receipts and reports exactly which +//! prerequisite is responsible for PASS, FAIL, BLOCKED, or INCOMPLETE. + +use serde::{Deserialize, Serialize}; +use std::collections::BTreeSet; +use std::path::Path; + +use crate::chain::tier_satisfies; +use crate::evidence::{list_receipts, load_receipt, Tier, Verdict}; + +/// Subdirectory of the proof store holding gate manifests. +pub const GATE_DIR: &str = "gates"; + +/// One prerequisite inside a gate manifest. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Requirement { + /// Human label used in status output, for example `SEED-0B-QEMU`. + pub name: String, + /// Receipt kind that satisfies this requirement, for example `m3`. + pub kind: String, + /// Optional nested gate requirement. When set, `kind` must be empty. + #[serde(default)] + pub gate_ref: Option, + /// Exact physical resource required for hardware evidence and its hold. + #[serde(default)] + pub resource: Option, + /// Exact repository identity when the prerequisite belongs to another repo. + #[serde(default)] + pub repo: Option, + /// Exact machine/resource identity for non-hardware tiers. + #[serde(default)] + pub machine: Option, + /// Required substring in the procedure identity, often carrying the test script version. + #[serde(default)] + pub procedure_contains: Option, + /// Minimum count of input artifact digests required on the receipt. + #[serde(default)] + pub min_input_artifacts: usize, + /// Required receipt kinds reachable through this receipt's verified chain. + #[serde(default)] + pub dependency_kinds: Vec, + /// Minimum qualification tier. A QEMU receipt never satisfies a + /// Machine 1 requirement. + #[serde(default = "default_tier")] + pub min_tier: Tier, + /// Assertion IDs that must exist and pass on the chosen receipt. + #[serde(default)] + pub assertions: Vec, + /// Optional source constraints for assertions whose origin matters. + #[serde(default)] + pub assertion_sources: Vec, + /// Exact mutation class required from the receipt, when specified. + #[serde(default)] + pub mutation: Option, + /// When true, the satisfying receipt must come from a clean tree. + #[serde(default)] + pub require_clean: bool, + /// Status used when no satisfying receipt, or a required assertion on + /// it, exists in the store. + #[serde(default)] + pub missing_as: MissingAs, + /// Named external condition behind a known BLOCKED prerequisite. + #[serde(default)] + pub missing_reason: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AssertionSource { + pub id: String, + pub source: String, +} + +/// Status reported when required proof is absent from the store. +/// BLOCKED names a known prerequisite that prevents the run from proceeding +/// legally or procedurally, for example the owner trust chain. +/// INCOMPLETE names proof that is simply absent so far. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +pub enum MissingAs { + #[serde(rename = "BLOCKED")] + #[default] + Blocked, + #[serde(rename = "INCOMPLETE")] + Incomplete, +} + +impl MissingAs { + fn verdict(self) -> Verdict { + match self { + MissingAs::Blocked => Verdict::Blocked, + MissingAs::Incomplete => Verdict::Incomplete, + } + } +} + +fn default_tier() -> Tier { + Tier::HostTest +} + +/// A named gate: the set of prerequisites that close it. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Gate { + pub gate: String, + #[serde(default)] + pub description: String, + pub requires: Vec, +} + +impl Gate { + /// Reject malformed manifests at load: unnamed or duplicated + /// requirements, requirements naming both or neither of gate and kind, + /// and source constraints on assertions the manifest never requires. + pub fn validate(&self) -> Result<(), String> { + if self.gate.trim().is_empty() { + return Err("gate manifest has no gate name".to_string()); + } + let mut names = BTreeSet::new(); + for req in &self.requires { + if req.name.trim().is_empty() { + return Err(format!("gate {} has an unnamed requirement", self.gate)); + } + if req + .gate_ref + .as_ref() + .is_some_and(|name| name.trim().is_empty()) + { + return Err(format!( + "gate {} requirement {:?} has an empty gate reference", + self.gate, req.name + )); + } + if !names.insert(req.name.clone()) { + return Err(format!( + "gate {} lists requirement {:?} twice", + self.gate, req.name + )); + } + match (&req.gate_ref, req.kind.trim().is_empty()) { + (Some(_), false) => { + return Err(format!( + "gate {} requirement {:?} names both a gate and a receipt kind", + self.gate, req.name + )); + } + (None, true) => { + return Err(format!( + "gate {} requirement {:?} names neither a gate nor a receipt kind", + self.gate, req.name + )); + } + _ => {} + } + for constrained in &req.assertion_sources { + if !req.assertions.iter().any(|a| a == &constrained.id) { + return Err(format!( + "gate {} requirement {:?} constrains source of assertion {:?} it never requires", + self.gate, req.name, constrained.id + )); + } + } + if req.gate_ref.is_some() && !req.dependency_kinds.is_empty() { + return Err(format!( + "gate {} nested gate requirement {:?} cannot declare receipt dependency kinds", + self.gate, req.name + )); + } + } + Ok(()) + } +} + +/// Per requirement outcome. +#[derive(Debug, Clone)] +pub struct GateLine { + pub name: String, + pub status: Verdict, + pub detail: String, +} + +/// Whole gate outcome plus the responsible prerequisite lines. +#[derive(Debug, Clone)] +pub struct GateReport { + pub gate: String, + pub status: Verdict, + pub lines: Vec, +} + +fn worse(a: Verdict, b: Verdict) -> Verdict { + fn rank(v: Verdict) -> u8 { + match v { + Verdict::Fail => 0, + Verdict::Blocked => 1, + Verdict::Incomplete => 2, + Verdict::Skipped => 3, + Verdict::Pass => 4, + } + } + if rank(a) <= rank(b) { + a + } else { + b + } +} + +/// Pick the best stored receipt of `kind`: PASS first, then highest tier. +pub fn best_candidate(store: &Path, kind: &str) -> Option { + let mut best: Option = None; + for id in list_receipts(store) { + let receipt = load_receipt(store, &id).ok()?; + if receipt.kind != kind { + continue; + } + let take = match &best { + None => true, + Some(current) => { + let rank = |r: &crate::evidence::Receipt| { + (r.result == Verdict::Pass, r.tier.rank(), r.timestamp) + }; + rank(&receipt) > rank(current) + } + }; + if take { + best = Some(receipt); + } + } + best +} + +/// Evaluate one requirement against the store. +fn eval_requirement(store: &Path, req: &Requirement, stack: &mut Vec) -> GateLine { + if let Some(child_name) = &req.gate_ref { + if !req.kind.is_empty() { + return GateLine { + name: req.name.clone(), + status: Verdict::Fail, + detail: "manifest requirement cannot name both a gate and receipt kind".into(), + }; + } + if stack.contains(child_name) { + return GateLine { + name: req.name.clone(), + status: Verdict::Fail, + detail: format!("gate dependency cycle through {child_name}"), + }; + } + let child = match load_manifest(store, child_name, None) { + Ok(g) => g, + Err(e) => { + return GateLine { + name: req.name.clone(), + status: Verdict::Blocked, + detail: format!("BLOCKED {child_name}: {e}"), + } + } + }; + stack.push(child_name.clone()); + let report = evaluate_inner(&child, store, stack); + stack.pop(); + let summary = report + .lines + .iter() + .filter(|l| l.status != Verdict::Pass) + .map(|l| format!("{}: {}", l.name, l.detail)) + .collect::>() + .join("; "); + let summary = if summary.is_empty() { + format!("all {} requirements PASS", report.lines.len()) + } else { + summary + }; + return GateLine { + name: req.name.clone(), + status: report.status, + detail: format!("{}: {} ({})", child_name, report.status.as_str(), summary), + }; + } + if req.kind.is_empty() { + return GateLine { + name: req.name.clone(), + status: Verdict::Fail, + detail: "manifest requirement has neither gate_ref nor receipt kind".into(), + }; + } + let receipt = match best_candidate(store, &req.kind) { + None => { + let detail = req.missing_reason.as_ref().map_or_else( + || format!("MISSING: no receipt of kind {:?} in store", req.kind), + |reason| format!("MISSING: {reason}"), + ); + return GateLine { + name: req.name.clone(), + status: req.missing_as.verdict(), + detail, + }; + } + Some(r) => r, + }; + if receipt.result != Verdict::Pass { + return GateLine { + name: req.name.clone(), + status: receipt.result, + detail: format!( + "{}: receipt {} records {}", + req.kind, + &receipt.id[..16], + receipt.result.as_str() + ), + }; + } + if !tier_satisfies(req.min_tier, receipt.tier) { + return GateLine { + name: req.name.clone(), + status: Verdict::Blocked, + detail: format!( + "{}: receipt tier {} cannot satisfy required {}", + req.kind, + receipt.tier.as_str(), + req.min_tier.as_str() + ), + }; + } + if let Some(resource) = &req.resource { + if receipt.machine != *resource + || receipt + .lease + .as_ref() + .is_none_or(|lease| lease.resource != *resource) + { + return GateLine { + name: req.name.clone(), + status: Verdict::Incomplete, + detail: format!( + "{}: receipt and exclusive hold must bind resource {:?}", + req.kind, resource + ), + }; + } + } + if req.repo.as_ref().is_some_and(|repo| receipt.repo != *repo) { + return GateLine { + name: req.name.clone(), + status: Verdict::Fail, + detail: format!( + "{}: repository identity does not match required {:?}", + req.kind, + req.repo.as_deref().unwrap_or_default() + ), + }; + } + if req + .machine + .as_ref() + .is_some_and(|machine| receipt.machine != *machine) + { + return GateLine { + name: req.name.clone(), + status: Verdict::Fail, + detail: format!( + "{}: machine identity does not match required {:?}", + req.kind, + req.machine.as_deref().unwrap_or_default() + ), + }; + } + if req + .procedure_contains + .as_ref() + .is_some_and(|needle| !receipt.procedure.contains(needle)) + { + return GateLine { + name: req.name.clone(), + status: Verdict::Fail, + detail: format!( + "{}: procedure identity must include {:?}", + req.kind, + req.procedure_contains.as_deref().unwrap_or_default() + ), + }; + } + if receipt.input_artifacts.len() < req.min_input_artifacts { + return GateLine { + name: req.name.clone(), + status: req.missing_as.verdict(), + detail: format!( + "{}: requires at least {} input artifact digests, receipt has {}", + req.kind, + req.min_input_artifacts, + receipt.input_artifacts.len() + ), + }; + } + if req.require_clean && receipt.dirty { + return GateLine { + name: req.name.clone(), + status: Verdict::Blocked, + detail: format!( + "{}: gate requires a clean source tree but receipt {} is dirty", + req.kind, + &receipt.id[..16] + ), + }; + } + let mut assertion_problems = Vec::new(); + let mut assertion_status = Verdict::Pass; + for wanted in &req.assertions { + match receipt.assertions.iter().find(|a| &a.id == wanted) { + Some(a) if a.pass => {} + Some(_) => { + assertion_status = Verdict::Fail; + assertion_problems.push(format!("assertion {wanted:?} failed")); + } + None => { + if assertion_status != Verdict::Fail { + assertion_status = req.missing_as.verdict(); + } + assertion_problems.push(format!("assertion {wanted:?} missing")); + } + } + } + for wanted in &req.assertion_sources { + match receipt.assertions.iter().find(|a| a.id == wanted.id) { + Some(a) if a.pass && a.source == wanted.source => {} + Some(a) if !a.pass => { + assertion_status = Verdict::Fail; + assertion_problems.push(format!("assertion {:?} failed", wanted.id)); + } + Some(a) => { + assertion_status = Verdict::Fail; + assertion_problems.push(format!( + "assertion {:?} source {:?} does not match required {:?}", + wanted.id, a.source, wanted.source + )); + } + None => { + if assertion_status != Verdict::Fail { + assertion_status = req.missing_as.verdict(); + } + assertion_problems.push(format!("assertion {:?} missing", wanted.id)); + } + } + } + if !assertion_problems.is_empty() { + return GateLine { + name: req.name.clone(), + status: assertion_status, + detail: format!("{}: {}", req.kind, assertion_problems.join("; ")), + }; + } + if let Some(mutation) = req.mutation { + if receipt.declared_mutation != mutation || receipt.observed_mutation != mutation { + return GateLine { + name: req.name.clone(), + status: Verdict::Fail, + detail: format!( + "{}: declared/observed mutation must both be {}", + req.kind, + mutation.as_str() + ), + }; + } + } + if receipt.tier.is_hardware() { + match crate::lease::lease_status(&receipt, store) { + Some(r) if r.status != Verdict::Pass => { + return GateLine { + name: req.name.clone(), + status: if r.status == Verdict::Fail { + Verdict::Fail + } else { + Verdict::Blocked + }, + detail: format!("{}: {}", req.kind, r.reasons.join("; ")), + }; + } + _ => {} + } + } + let chain_path = store + .join(crate::evidence::RECEIPT_DIR) + .join(format!("{}.json", receipt.id)); + match crate::chain::verify_chain(&chain_path, store) { + Ok(chain) if chain.status == Verdict::Pass => {} + Ok(chain) => { + return GateLine { + name: req.name.clone(), + status: chain.status, + detail: format!( + "{}: receipt dependency chain {}: {}", + req.kind, + chain.status.as_str(), + chain.reasons.join("; ") + ), + }; + } + Err(e) => { + return GateLine { + name: req.name.clone(), + status: Verdict::Incomplete, + detail: format!("{}: cannot verify receipt dependency chain: {e}", req.kind), + }; + } + } + if !req.dependency_kinds.is_empty() { + let chain = match crate::chain::verify_chain(&chain_path, store) { + Ok(chain) => chain, + Err(e) => { + return GateLine { + name: req.name.clone(), + status: Verdict::Incomplete, + detail: format!("{}: cannot resolve receipt dependencies: {e}", req.kind), + } + } + }; + let missing: Vec<&str> = req + .dependency_kinds + .iter() + .filter(|kind| !chain.lines.iter().any(|line| &line.kind == *kind)) + .map(String::as_str) + .collect(); + if !missing.is_empty() { + return GateLine { + name: req.name.clone(), + status: req.missing_as.verdict(), + detail: format!( + "{}: required receipt dependency kinds missing from verified chain: {}", + req.kind, + missing.join(", ") + ), + }; + } + } + GateLine { + name: req.name.clone(), + status: Verdict::Pass, + detail: format!( + "{}: receipt {} tier {}", + req.kind, + &receipt.id[..16], + receipt.tier.as_str() + ), + } +} + +/// Evaluate a gate manifest against the store. +pub fn evaluate(manifest: &Gate, store: &Path) -> GateReport { + evaluate_inner(manifest, store, &mut vec![manifest.gate.clone()]) +} + +fn evaluate_inner(manifest: &Gate, store: &Path, stack: &mut Vec) -> GateReport { + let mut status = Verdict::Pass; + let mut lines = Vec::new(); + for req in &manifest.requires { + let line = eval_requirement(store, req, stack); + status = worse(status, line.status); + lines.push(line); + } + // No requirements means nothing is proven. + if manifest.requires.is_empty() { + status = Verdict::Incomplete; + } + GateReport { + gate: manifest.gate.clone(), + status, + lines, + } +} + +/// Load a manifest by gate name: explicit path first, then the store's +/// gate directory. +pub fn load_manifest(store: &Path, gate: &str, explicit: Option<&Path>) -> Result { + if let Some(path) = explicit { + let text = + std::fs::read_to_string(path).map_err(|e| format!("cannot read gate file: {e}"))?; + let manifest: Gate = + serde_json::from_str(&text).map_err(|e| format!("gate manifest invalid: {e}"))?; + if manifest.gate != gate { + return Err(format!( + "gate manifest name {:?} does not match requested {gate:?}", + manifest.gate + )); + } + manifest.validate()?; + return Ok(manifest); + } + let text = if let Some(text) = embedded_manifest(gate) { + text.to_string() + } else { + let path = store.join(GATE_DIR).join(format!("{gate}.json")); + std::fs::read_to_string(&path) + .map_err(|_| format!("no manifest for gate {gate:?}: pass --gate "))? + }; + let manifest: Gate = + serde_json::from_str(&text).map_err(|e| format!("gate manifest invalid: {e}"))?; + if manifest.gate != gate { + return Err(format!( + "gate manifest name {:?} does not match requested {gate:?}", + manifest.gate + )); + } + manifest.validate()?; + Ok(manifest) +} + +/// Built in example manifests. These are examples of the manifest shape, +/// not claims that any gate has passed. +pub const SEED_0B_EXAMPLE: &str = include_str!("../gates/SEED-0B.json"); +pub const SEED_0B_QEMU: &str = include_str!("../gates/SEED0B_QEMU.json"); +pub const STORE_V1_FORMAT_PR_MERGE: &str = include_str!("../gates/STORE_V1_FORMAT_PR_MERGE.json"); +pub const P3_STORE_QEMU: &str = include_str!("../gates/P3_STORE_QEMU.json"); +pub const P3_STORE_MACHINE1: &str = include_str!("../gates/P3_STORE_MACHINE1.json"); +pub const P3_DEVELOPMENT_QEMU_ENTRY: &str = include_str!("../gates/P3_DEVELOPMENT_QEMU_ENTRY.json"); +pub const P3_MACHINE1_WRITE_ENTRY: &str = include_str!("../gates/P3_MACHINE1_WRITE_ENTRY.json"); + +fn embedded_manifest(gate: &str) -> Option<&'static str> { + match gate { + "SEED-0B" => Some(SEED_0B_EXAMPLE), + "SEED0B_QEMU" => Some(SEED_0B_QEMU), + "STORE_V1_FORMAT_PR_MERGE" => Some(STORE_V1_FORMAT_PR_MERGE), + "P3_STORE_QEMU" => Some(P3_STORE_QEMU), + "P3_STORE_MACHINE1" => Some(P3_STORE_MACHINE1), + "P3_DEVELOPMENT_QEMU_ENTRY" => Some(P3_DEVELOPMENT_QEMU_ENTRY), + "P3_MACHINE1_WRITE_ENTRY" => Some(P3_MACHINE1_WRITE_ENTRY), + _ => None, + } +} + +/// Materialize the example manifests into a directory. +pub fn write_examples(dir: &Path) -> Result, String> { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let mut out = Vec::new(); + for (name, text) in [ + ("SEED-0B.json", SEED_0B_EXAMPLE), + ("SEED0B_QEMU.json", SEED_0B_QEMU), + ("STORE_V1_FORMAT_PR_MERGE.json", STORE_V1_FORMAT_PR_MERGE), + ("P3_STORE_QEMU.json", P3_STORE_QEMU), + ("P3_STORE_MACHINE1.json", P3_STORE_MACHINE1), + ("P3_DEVELOPMENT_QEMU_ENTRY.json", P3_DEVELOPMENT_QEMU_ENTRY), + ("P3_MACHINE1_WRITE_ENTRY.json", P3_MACHINE1_WRITE_ENTRY), + ] { + // Validate the shipped shape before writing. + let manifest: Gate = + serde_json::from_str(text).map_err(|e| format!("built in manifest broken: {e}"))?; + manifest + .validate() + .map_err(|e| format!("built in manifest invalid: {e}"))?; + let path = dir.join(name); + std::fs::write(&path, text).map_err(|e| e.to_string())?; + out.push(path); + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evidence::fixtures::{sample, sealed}; + use crate::evidence::store_receipt; + + fn store_qemu(store: &Path, kind: &str, assertions: Vec<&str>) { + let mut r = sample(); + r.kind = kind.to_string(); + let ids = if assertions.is_empty() { + vec!["recorded"] + } else { + assertions + }; + r.assertions = ids + .into_iter() + .map(|id| crate::evidence::Assertion { + id: id.to_string(), + expected: "yes".to_string(), + observed: "yes".to_string(), + pass: true, + source: "example".to_string(), + note: String::new(), + }) + .collect(); + store_receipt(store, &sealed(r)).unwrap(); + } + + fn manifest() -> Gate { + Gate { + gate: "SEED-0B".to_string(), + description: "example".to_string(), + requires: vec![ + Requirement { + name: "M3".to_string(), + kind: "m3".to_string(), + gate_ref: None, + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier: Tier::HostTest, + assertions: vec![], + assertion_sources: vec![], + mutation: None, + require_clean: false, + missing_as: MissingAs::Blocked, + missing_reason: None, + }, + Requirement { + name: "SEED-0B-QEMU".to_string(), + kind: "seed-0b-qemu".to_string(), + gate_ref: None, + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier: Tier::Qemu, + assertions: vec!["artifact_signature_valid".to_string()], + assertion_sources: vec![], + mutation: None, + require_clean: true, + missing_as: MissingAs::Blocked, + missing_reason: None, + }, + Requirement { + name: "SEED-0B-MACHINE1".to_string(), + kind: "seed-0b-machine1".to_string(), + gate_ref: None, + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier: Tier::Machine1Attended, + assertions: vec![], + assertion_sources: vec![], + mutation: None, + require_clean: true, + missing_as: MissingAs::Blocked, + missing_reason: None, + }, + ], + } + } + + #[test] + fn gate_reports_missing() { + let store = crate::testutil::temp_dir("gate-missing"); + let report = evaluate(&manifest(), &store); + assert_eq!(report.status, Verdict::Blocked); + assert!(report.lines.iter().all(|l| l.status == Verdict::Blocked)); + assert!(report.lines[0].detail.contains("MISSING")); + } + + #[test] + fn qemu_receipt_cannot_satisfy_machine1_requirement() { + let store = crate::testutil::temp_dir("gate-tier"); + store_qemu(&store, "m3", vec![]); + store_qemu(&store, "seed-0b-qemu", vec!["artifact_signature_valid"]); + // A QEMU tier receipt filed under the machine1 kind must not close + // the physical requirement. + let mut r = sample(); + r.kind = "seed-0b-machine1".to_string(); + store_receipt(&store, &sealed(r)).unwrap(); + let report = evaluate(&manifest(), &store); + assert_eq!(report.status, Verdict::Blocked); + let line = report + .lines + .iter() + .find(|l| l.name == "SEED-0B-MACHINE1") + .unwrap(); + assert!(line.detail.contains("cannot satisfy")); + } + + #[test] + fn dirty_tree_fails_clean_requirement() { + let store = crate::testutil::temp_dir("gate-dirty"); + let mut r = sample(); + r.kind = "m3".to_string(); + store_receipt(&store, &sealed(r)).unwrap(); + let mut q = sample(); + q.kind = "seed-0b-qemu".to_string(); + q.dirty = true; + store_receipt(&store, &sealed(q)).unwrap(); + let report = evaluate(&manifest(), &store); + let line = report + .lines + .iter() + .find(|l| l.name == "SEED-0B-QEMU") + .unwrap(); + assert_eq!(line.status, Verdict::Blocked); + assert!(line.detail.contains("clean source tree")); + } + + #[test] + fn failed_assertion_fails_gate() { + let store = crate::testutil::temp_dir("gate-assert"); + store_qemu(&store, "m3", vec![]); + let mut q = sample(); + q.kind = "seed-0b-qemu".to_string(); + q.assertions[0].pass = false; + store_receipt(&store, &sealed(q)).unwrap(); + let report = evaluate(&manifest(), &store); + let line = report + .lines + .iter() + .find(|l| l.name == "SEED-0B-QEMU") + .unwrap(); + assert_eq!(line.status, Verdict::Fail); + } + + #[test] + fn blocked_receipt_cannot_satisfy_a_gate() { + let store = crate::testutil::temp_dir("gate-blocked-receipt"); + let mut r = sample(); + r.kind = "seed-0b-qemu".to_string(); + r.result = Verdict::Blocked; + store_receipt(&store, &sealed(r)).unwrap(); + let report = evaluate(&manifest(), &store); + let line = report + .lines + .iter() + .find(|l| l.name == "SEED-0B-QEMU") + .unwrap(); + assert_eq!(line.status, Verdict::Blocked); + } + + #[test] + fn qemu_bootnext_mock_source_cannot_prove_firmware_variable_behavior() { + let store = crate::testutil::temp_dir("gate-bootnext-source"); + let mut r = sample(); + r.kind = "rollback".to_string(); + r.assertions = vec![crate::evidence::Assertion { + id: "bootnext_consumed".into(), + expected: "unset".into(), + observed: "unset".into(), + pass: true, + source: "rollback_state_machine_mock".into(), + note: String::new(), + }]; + store_receipt(&store, &sealed(r)).unwrap(); + let gate = Gate { + gate: "rollback-source-test".into(), + description: String::new(), + requires: vec![Requirement { + name: "firmware BootNext".into(), + kind: "rollback".into(), + gate_ref: None, + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier: Tier::Qemu, + assertions: vec!["bootnext_consumed".into()], + assertion_sources: vec![AssertionSource { + id: "bootnext_consumed".into(), + source: "aavmf_variables".into(), + }], + mutation: None, + require_clean: true, + missing_as: MissingAs::Incomplete, + missing_reason: None, + }], + }; + assert_eq!(evaluate(&gate, &store).status, Verdict::Fail); + } + + #[test] + fn nested_gate_cycle_fails_closed() { + let store = crate::testutil::temp_dir("gate-cycle"); + let dir = store.join(GATE_DIR); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("A.json"), + r#"{"gate":"A","requires":[{"name":"B","kind":"","gate_ref":"B"}]}"#, + ) + .unwrap(); + std::fs::write( + dir.join("B.json"), + r#"{"gate":"B","requires":[{"name":"A","kind":"","gate_ref":"A"}]}"#, + ) + .unwrap(); + let a = load_manifest(&store, "A", None).unwrap(); + assert_eq!(evaluate(&a, &store).status, Verdict::Fail); + } + + #[test] + fn p3_gates_preserve_qemu_and_machine1_distinction() { + let store = crate::testutil::temp_dir("gate-p3-split"); + let qemu = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap(); + let physical = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap(); + let qemu_report = evaluate(&qemu, &store); + let physical_report = evaluate(&physical, &store); + assert_eq!(qemu_report.status, Verdict::Incomplete); + assert_eq!(physical_report.status, Verdict::Blocked); + let trust = physical_report + .lines + .iter() + .find(|line| line.name == "OWNER_SECURE_BOOT_TRUST_CHAIN") + .unwrap(); + assert_eq!(trust.status, Verdict::Blocked); + assert!(trust + .detail + .contains("HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN")); + let bounded = physical_report + .lines + .iter() + .find(|line| line.name == "BOUNDED_MACHINE1_STORE_REGION") + .unwrap(); + assert_eq!(bounded.status, Verdict::Incomplete); + assert_eq!( + physical.requires[0].gate_ref.as_deref(), + Some("P3_DEVELOPMENT_QEMU_ENTRY") + ); + } + + #[test] + fn checked_in_gate_cannot_be_substituted_by_store_copy() { + let store = crate::testutil::temp_dir("gate-no-substitution"); + let dir = store.join(GATE_DIR); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write( + dir.join("P3_DEVELOPMENT_QEMU_ENTRY.json"), + r#"{"gate":"P3_DEVELOPMENT_QEMU_ENTRY","requires":[]}"#, + ) + .unwrap(); + let manifest = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap(); + assert_eq!(manifest.requires.len(), 4); + } + + #[test] + fn narrow_store_format_merge_gate_does_not_require_seed_or_rollback() { + let store = crate::testutil::temp_dir("gate-format-merge"); + store_assertion_receipt( + &store, + "adr0015-format", + Tier::HostTest, + "host", + "scripts/check_adr0015.sh", + pass_assertions(&["adr0015_accepted_frozen"], "adr0015"), + ); + store_assertion_receipt( + &store, + "store-v1-format-golden-vectors", + Tier::HostTest, + "host", + "cargo test -p aien-system-store format_golden_vectors", + pass_assertions( + &["store_format_v1_valid", "store_golden_vectors_match"], + "store-format-tests", + ), + ); + store_assertion_receipt( + &store, + "strict-main-verification", + Tier::HostTest, + "host", + "scripts/verify_all.sh", + pass_assertions(&["strict_main_pass"], "verify-all"), + ); + let manifest = load_manifest(&store, "STORE_V1_FORMAT_PR_MERGE", None).unwrap(); + assert_eq!(evaluate(&manifest, &store).status, Verdict::Pass); + assert!(manifest.requires.iter().all(|requirement| { + requirement.kind != "seed0b-qemu" && requirement.kind != "m0-native-rollback-qemu" + })); + } + + #[test] + fn gate_rejects_receipt_with_missing_chain_dependency() { + let store = crate::testutil::temp_dir("gate-missing-chain"); + let mut r = sample(); + r.kind = "m3".to_string(); + r.dependencies = vec!["f".repeat(64)]; + store_receipt(&store, &sealed(r)).unwrap(); + let manifest = Gate { + gate: "CHAIN-DEMO".to_string(), + description: String::new(), + requires: vec![req("M3", "m3", Tier::HostTest, vec![], MissingAs::Blocked)], + }; + assert_eq!(evaluate(&manifest, &store).status, Verdict::Incomplete); + } + + #[test] + fn mutation_class_mismatch_fails_gate() { + use crate::evidence::Mutation; + let store = crate::testutil::temp_dir("gate-mutation-mismatch"); + store_qemu(&store, "store-qemu", vec!["store_previous_or_new_only"]); + let mut requirement = req( + "Store QEMU", + "store-qemu", + Tier::Qemu, + vec!["store_previous_or_new_only"], + MissingAs::Incomplete, + ); + requirement.mutation = Some(Mutation::BoundedTestRegionWrite); + let report = evaluate( + &Gate { + gate: "MUTATION-DEMO".into(), + description: String::new(), + requires: vec![requirement], + }, + &store, + ); + assert_eq!(report.status, Verdict::Fail); + assert!(report.lines[0] + .detail + .contains("declared/observed mutation")); + } + + #[test] + fn hardware_gate_requires_the_machine1_hold() { + let store = crate::testutil::temp_dir("gate-no-hold"); + store_assertion_receipt( + &store, + "machine-run", + Tier::Machine1Attended, + "machine-1", + "scripts/qualify.sh", + pass_assertions(&["operator_attended"], "operator"), + ); + let mut requirement = req( + "Machine 1 run", + "machine-run", + Tier::Machine1Attended, + vec!["operator_attended"], + MissingAs::Incomplete, + ); + requirement.resource = Some("machine-1".into()); + let report = evaluate( + &Gate { + gate: "MACHINE-HOLD-DEMO".into(), + description: String::new(), + requires: vec![requirement], + }, + &store, + ); + assert_eq!(report.status, Verdict::Incomplete); + assert!(report.lines[0].detail.contains("exclusive hold")); + } + + fn req( + name: &str, + kind: &str, + min_tier: Tier, + assertions: Vec<&str>, + missing_as: MissingAs, + ) -> Requirement { + Requirement { + name: name.to_string(), + kind: kind.to_string(), + gate_ref: None, + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier, + assertions: assertions.into_iter().map(str::to_string).collect(), + assertion_sources: vec![], + mutation: None, + require_clean: false, + missing_as, + missing_reason: None, + } + } + + fn assertion(id: &str, source: &str, pass: bool) -> crate::evidence::Assertion { + crate::evidence::Assertion { + id: id.to_string(), + expected: "yes".to_string(), + observed: "yes".to_string(), + pass, + source: source.to_string(), + note: String::new(), + } + } + + /// Materialize the embedded P3 manifests into a fresh store. + fn p3_store(tag: &str) -> std::path::PathBuf { + let store = crate::testutil::temp_dir(tag); + write_examples(&store.join(GATE_DIR)).unwrap(); + store + } + + #[test] + fn machine1_gate_names_its_blockers_on_an_empty_store() { + let store = p3_store("gate-m1-empty"); + let manifest = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap(); + let report = evaluate(&manifest, &store); + assert_eq!(report.status, Verdict::Blocked); + let trust = report + .lines + .iter() + .find(|l| l.name == "OWNER_SECURE_BOOT_TRUST_CHAIN") + .unwrap(); + assert_eq!(trust.status, Verdict::Blocked); + assert!(trust + .detail + .contains("HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN")); + let rollback = report + .lines + .iter() + .find(|l| l.name == "M0_NATIVE_ROLLBACK_MACHINE1") + .unwrap(); + assert_eq!(rollback.status, Verdict::Blocked); + // The bounded region is proof simply absent so far, not a known + // procedural block. + let region = report + .lines + .iter() + .find(|l| l.name == "BOUNDED_MACHINE1_STORE_REGION") + .unwrap(); + assert_eq!(region.status, Verdict::Incomplete); + } + + fn store_assertion_receipt( + store: &Path, + kind: &str, + tier: Tier, + machine: &str, + procedure: &str, + assertions: Vec, + ) { + let mut r = sample(); + r.kind = kind.to_string(); + r.tier = tier; + r.env_class = tier.as_str().to_string(); + r.machine = machine.to_string(); + r.procedure = procedure.to_string(); + r.input_artifacts = vec![ + "blake3:".to_string() + &"b".repeat(64), + "sha256:".to_string() + &"c".repeat(64), + ]; + r.assertions = assertions; + store_receipt(store, &sealed(r)).unwrap(); + } + + const ROLLBACK_BRANCHES: &[&str] = &[ + "rollback_harness_version_recorded", + "qemu_aavmf_environment_recorded", + "rollback_normal_pass", + "rollback_fault_pass", + "rollback_timeout_pass", + "rollback_rejected_pass", + "rollback_absent_pass", + "rollback_repeat_boot_pass", + "m0_native_rollback_qemu_pass", + ]; + + const ROLLBACK_MACHINE: &str = "qemu-aarch64-aavmf"; + const ROLLBACK_PROCEDURE: &str = "scripts/qemu_native_rollback_test.sh@0.9.1"; + + fn pass_assertions(ids: &[&str], source: &str) -> Vec { + ids.iter().map(|id| assertion(id, source, true)).collect() + } + + /// Satisfy the QEMU development gate with real stored receipts, then + /// prove the Machine 1 gate still reports BLOCKED for the trust chain. + /// This is the done condition distinction in one test. + #[test] + fn qemu_gate_passes_while_machine1_gate_stays_blocked() { + let store = p3_store("gate-qemu-vs-m1"); + store_assertion_receipt( + &store, + "m0-native-rollback-qemu", + Tier::Qemu, + ROLLBACK_MACHINE, + ROLLBACK_PROCEDURE, + [ + pass_assertions(ROLLBACK_BRANCHES, "rollback-verify"), + vec![ + assertion("bootnext_consumed", "aavmf_variables", true), + assertion("default_boot_unchanged", "aavmf_variables", true), + ], + ] + .concat(), + ); + store_assertion_receipt( + &store, + "seed0b-qemu", + Tier::Qemu, + "qemu-virt-aarch64", + "scripts/qemu_seed0b.sh", + pass_assertions( + &[ + "seed0b_signature_valid", + "granted_subset_requested", + "unauthorized_write_denied", + "forged_handle_denied", + "all_task_frames_reclaimed", + ], + "seed0b-qemu", + ), + ); + store_assertion_receipt( + &store, + "adr0015-format", + Tier::HostTest, + "host", + "scripts/check_adr0015.sh", + pass_assertions(&["adr0015_accepted_frozen"], "adr0015"), + ); + store_assertion_receipt( + &store, + "strict-main-verification", + Tier::HostTest, + "host", + "scripts/verify_all.sh", + pass_assertions(&["strict_main_pass"], "verify-all"), + ); + let qemu = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap(); + let qemu_report = evaluate(&qemu, &store); + assert_eq!(qemu_report.status, Verdict::Pass, "{qemu_report:?}"); + let m1 = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap(); + let m1_report = evaluate(&m1, &store); + assert_eq!(m1_report.status, Verdict::Blocked); + let sub = m1_report + .lines + .iter() + .find(|l| l.name == "P3_DEVELOPMENT_QEMU_ENTRY") + .unwrap(); + assert_eq!(sub.status, Verdict::Pass); + let trust = m1_report + .lines + .iter() + .find(|l| l.name == "OWNER_SECURE_BOOT_TRUST_CHAIN") + .unwrap(); + assert_eq!(trust.status, Verdict::Blocked); + } + + #[test] + fn mock_source_cannot_prove_firmware_bootnext() { + let store = p3_store("gate-mock"); + store_assertion_receipt( + &store, + "m0-native-rollback-qemu", + Tier::Qemu, + ROLLBACK_MACHINE, + ROLLBACK_PROCEDURE, + [ + pass_assertions(ROLLBACK_BRANCHES, "rollback-verify"), + vec![ + assertion("bootnext_consumed", "state-machine-mock", true), + assertion("default_boot_unchanged", "aavmf_variables", true), + ], + ] + .concat(), + ); + let manifest = load_manifest(&store, "P3_DEVELOPMENT_QEMU_ENTRY", None).unwrap(); + let report = evaluate(&manifest, &store); + let line = report + .lines + .iter() + .find(|l| l.name == "M0_NATIVE_ROLLBACK_QEMU") + .unwrap(); + assert_eq!(line.status, Verdict::Fail); + assert!(line.detail.contains("aavmf_variables")); + } + + #[test] + fn blocked_receipt_cannot_satisfy_a_requirement() { + let store = crate::testutil::temp_dir("gate-blocked"); + let mut r = sample(); + r.kind = "m3".to_string(); + r.result = Verdict::Blocked; + r.assertions = vec![assertion("recorded", "example", true)]; + let r = sealed(r); + // BLOCKED receipts carry no chain burden here; store then evaluate. + store_receipt(&store, &r).unwrap(); + let manifest = Gate { + gate: "BLOCKED-DEMO".to_string(), + description: String::new(), + requires: vec![req("M3", "m3", Tier::HostTest, vec![], MissingAs::Blocked)], + }; + let report = evaluate(&manifest, &store); + assert_eq!(report.status, Verdict::Blocked); + assert!(report.lines[0].detail.contains("records BLOCKED")); + } + + #[test] + fn qemu_receipt_cannot_pose_as_machine1_rollback() { + let store = p3_store("gate-rollback-tier"); + store_assertion_receipt( + &store, + "m0-native-rollback-machine1", + Tier::Qemu, + "machine-1", + "scripts/rollback_machine1.sh", + pass_assertions(&["secure_boot_unchanged"], "rollback-verify"), + ); + let manifest = load_manifest(&store, "P3_MACHINE1_WRITE_ENTRY", None).unwrap(); + let report = evaluate(&manifest, &store); + let line = report + .lines + .iter() + .find(|l| l.name == "M0_NATIVE_ROLLBACK_MACHINE1") + .unwrap(); + assert_eq!(line.status, Verdict::Blocked); + assert!(line.detail.contains("cannot satisfy")); + } + + #[test] + fn manifest_cycles_fail_closed() { + let store = crate::testutil::temp_dir("gate-cycle"); + let dir = store.join(GATE_DIR); + std::fs::create_dir_all(&dir).unwrap(); + for (name, child) in [("GATE-A", "GATE-B"), ("GATE-B", "GATE-A")] { + let manifest = Gate { + gate: name.to_string(), + description: String::new(), + requires: vec![Requirement { + name: format!("child {child}"), + kind: String::new(), + gate_ref: Some(child.to_string()), + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier: Tier::HostTest, + assertions: vec![], + assertion_sources: vec![], + mutation: None, + require_clean: false, + missing_as: MissingAs::Blocked, + missing_reason: None, + }], + }; + std::fs::write( + dir.join(format!("{name}.json")), + serde_json::to_string_pretty(&manifest).unwrap(), + ) + .unwrap(); + } + let manifest = load_manifest(&store, "GATE-A", None).unwrap(); + let report = evaluate(&manifest, &store); + assert_eq!(report.status, Verdict::Fail); + assert!(report.lines[0].detail.contains("cycle")); + } + + #[test] + fn malformed_manifests_rejected_at_load() { + let both = Gate { + gate: "BAD".to_string(), + description: String::new(), + requires: vec![Requirement { + name: "x".to_string(), + kind: "m3".to_string(), + gate_ref: Some("OTHER".to_string()), + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier: Tier::HostTest, + assertions: vec![], + assertion_sources: vec![], + mutation: None, + require_clean: false, + missing_as: MissingAs::Blocked, + missing_reason: None, + }], + }; + assert!(both.validate().is_err()); + let stray_source = Gate { + gate: "BAD".to_string(), + description: String::new(), + requires: vec![Requirement { + name: "x".to_string(), + kind: "m3".to_string(), + gate_ref: None, + resource: None, + repo: None, + machine: None, + procedure_contains: None, + min_input_artifacts: 0, + dependency_kinds: vec![], + min_tier: Tier::HostTest, + assertions: vec!["a".to_string()], + assertion_sources: vec![AssertionSource { + id: "b".to_string(), + source: "mock".to_string(), + }], + mutation: None, + require_clean: false, + missing_as: MissingAs::Blocked, + missing_reason: None, + }], + }; + assert!(stray_source.validate().is_err()); + } + + #[test] + fn shipped_examples_parse() { + let seed: Gate = serde_json::from_str(SEED_0B_EXAMPLE).unwrap(); + assert_eq!(seed.gate, "SEED-0B"); + assert!(!seed.requires.is_empty()); + let seed_qemu: Gate = serde_json::from_str(SEED_0B_QEMU).unwrap(); + assert_eq!(seed_qemu.gate, "SEED0B_QEMU"); + let format: Gate = serde_json::from_str(STORE_V1_FORMAT_PR_MERGE).unwrap(); + assert_eq!(format.gate, "STORE_V1_FORMAT_PR_MERGE"); + let p3_qemu: Gate = serde_json::from_str(P3_STORE_QEMU).unwrap(); + assert_eq!(p3_qemu.gate, "P3_STORE_QEMU"); + let p3_machine: Gate = serde_json::from_str(P3_STORE_MACHINE1).unwrap(); + assert_eq!(p3_machine.gate, "P3_STORE_MACHINE1"); + let p3: Gate = serde_json::from_str(P3_DEVELOPMENT_QEMU_ENTRY).unwrap(); + assert_eq!(p3.gate, "P3_DEVELOPMENT_QEMU_ENTRY"); + assert!(!p3.requires.is_empty()); + let physical: Gate = serde_json::from_str(P3_MACHINE1_WRITE_ENTRY).unwrap(); + assert_eq!(physical.gate, "P3_MACHINE1_WRITE_ENTRY"); + } +} diff --git a/crates/aien-proof/src/import.rs b/crates/aien-proof/src/import.rs new file mode 100644 index 00000000..416c9639 --- /dev/null +++ b/crates/aien-proof/src/import.rs @@ -0,0 +1,381 @@ +//! Import external qualification output as receipts. +//! +//! Other repositories (SEED-0B runs, rollback verifiers, Store v1 crash +//! tests) emit a small machine readable assertion file. `import` turns that +//! file plus explicit source, artifact, and dependency references into a +//! sealed EvidenceReceiptV1. Prose is never parsed; the input contract is +//! JSON and any deviation fails closed. + +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +use crate::evidence::{ + check_commit, Assertion, LeaseRef, LedgerRef, Mutation, Receipt, Tier, Verdict, SCHEMA, + SCHEMA_VERSION, +}; +use crate::lease::check_resource_name; + +/// Machine readable assertion file produced by each test setup. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AssertionFile { + pub assertions: Vec, + /// Optional top level result. When absent it is derived from the + /// assertions. A claimed PASS with a failing assertion is refused. + #[serde(default)] + pub result: Option, +} + +/// One assertion line in the input file. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields)] +pub struct AssertionInput { + pub id: String, + #[serde(default)] + pub expected: String, + #[serde(default)] + pub observed: String, + pub result: AssertionResult, + #[serde(default)] + pub source: String, + #[serde(default)] + pub note: String, +} + +/// Accepts `pass`/`fail` strings or booleans. +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(untagged)] +pub enum AssertionResult { + Bool(bool), + Word(String), +} + +impl AssertionResult { + fn pass(&self) -> Result { + match self { + AssertionResult::Bool(b) => Ok(*b), + AssertionResult::Word(w) => match w.to_ascii_lowercase().as_str() { + "pass" => Ok(true), + "fail" => Ok(false), + _ => Err(format!("assertion result must be pass or fail, got {w:?}")), + }, + } + } +} + +/// All inputs needed to mint a receipt from external output. +#[derive(Debug, Clone, Default)] +pub struct ImportRequest { + pub repo: String, + pub commit: String, + pub dirty: bool, + pub kind: String, + pub tier: String, + pub toolchain: String, + pub procedure: String, + pub machine: String, + pub input_artifacts: Vec, + pub output_artifacts: Vec, + pub dependencies: Vec, + pub declared_mutation: Option, + pub observed_mutation: Option, + pub authority: String, + pub output_digest: Option, + pub output_file: Option, + pub external_refs: Vec, + pub ledger_index: Option, + pub ledger_hash: Option, + pub lease_hold: Option, + pub lease_resource: Option, + pub timestamp: Option, +} + +fn now() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +/// Parse and validate the assertion file. Never sniffs prose. +pub fn read_assertion_file(path: &Path) -> Result<(Vec, Verdict), String> { + let text = + std::fs::read_to_string(path).map_err(|e| format!("cannot read assertion file: {e}"))?; + let file: AssertionFile = + serde_json::from_str(&text).map_err(|e| format!("assertion file invalid: {e}"))?; + if file.assertions.is_empty() { + return Err("assertion file must carry at least one assertion".to_string()); + } + let mut out = Vec::with_capacity(file.assertions.len()); + for input in &file.assertions { + if input.id.trim().is_empty() { + return Err("assertion id must not be empty".to_string()); + } + out.push(Assertion { + id: input.id.clone(), + expected: input.expected.clone(), + observed: input.observed.clone(), + pass: input.result.pass()?, + source: input.source.clone(), + note: input.note.clone(), + }); + } + let derived = if out.iter().all(|a| a.pass) { + Verdict::Pass + } else { + Verdict::Fail + }; + if let Some(claimed) = file.result { + let verdict = Verdict::parse(&claimed).ok_or_else(|| format!("bad result {claimed:?}"))?; + if verdict == Verdict::Pass && derived != Verdict::Pass { + return Err("assertion file claims PASS but an assertion failed".to_string()); + } + // A setup may only downgrade (BLOCKED, INCOMPLETE, SKIPPED), never + // upgrade a failing run. FAIL stays FAIL. + if derived == Verdict::Fail && verdict == Verdict::Pass { + return Err("cannot upgrade a failing run to PASS".to_string()); + } + if derived == Verdict::Pass && verdict == Verdict::Fail { + return Err("file claims FAIL but every assertion passed".to_string()); + } + Ok((out, verdict)) + } else { + Ok((out, derived)) + } +} + +/// Build a sealed receipt from validated inputs. Hardware tiers require an +/// explicit declared mutation and a lease reference; PASS receipts require +/// an output digest (direct hex or hashed from an output file). +pub fn build_receipt( + req: &ImportRequest, + assertions: Vec, + result: Verdict, +) -> Result { + let tier = Tier::parse(&req.tier) + .ok_or_else(|| format!("unknown qualification tier {:?}", req.tier))?; + check_commit(&req.commit)?; + if req.repo.trim().is_empty() { + return Err("repo must not be empty".to_string()); + } + if req.kind.trim().is_empty() { + return Err("gate/kind must not be empty".to_string()); + } + if req.procedure.trim().is_empty() { + return Err("procedure identity must not be empty".to_string()); + } + if req.machine.trim().is_empty() { + return Err("machine identity must not be empty".to_string()); + } + for dep in &req.dependencies { + let low = dep.to_ascii_lowercase(); + if low.len() != 64 || !low.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(format!("dependency {dep:?} is not a 64 digit receipt hash")); + } + } + let declared = match &req.declared_mutation { + Some(s) => Mutation::parse(s).ok_or_else(|| format!("unknown mutation class {s:?}"))?, + None => { + if tier.is_hardware() { + return Err("hardware receipts require --declared-mutation".to_string()); + } + Mutation::None + } + }; + let observed = match &req.observed_mutation { + Some(s) => Mutation::parse(s).ok_or_else(|| format!("unknown mutation class {s:?}"))?, + None => declared, + }; + let output_digest = match (&req.output_digest, &req.output_file) { + (Some(hex), _) => { + if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("output digest must be 64 hex digits (BLAKE3)".to_string()); + } + hex.to_ascii_lowercase() + } + (None, Some(path)) => { + let bytes = std::fs::read(path).map_err(|e| format!("cannot read output file: {e}"))?; + blake3::hash(&bytes).to_hex().to_string() + } + (None, None) => { + if result == Verdict::Pass { + return Err("PASS receipts require --output-digest or --output-file".to_string()); + } + "0".repeat(64) + } + }; + let ledger = match (req.ledger_index, &req.ledger_hash) { + (Some(index), Some(hash)) => { + if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("ledger hash must be 64 hex digits".to_string()); + } + Some(LedgerRef { + index, + hash: hash.to_ascii_lowercase(), + }) + } + (None, None) => None, + _ => return Err("ledger reference needs both index and hash".to_string()), + }; + let lease = match (&req.lease_hold, &req.lease_resource) { + (Some(hold), Some(resource)) => { + check_resource_name(resource)?; + if hold.len() != 64 || !hold.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err("lease hold id must be 64 hex digits".to_string()); + } + Some(LeaseRef { + hold_id: hold.to_ascii_lowercase(), + resource: resource.clone(), + }) + } + (None, None) => None, + _ => return Err("lease binding needs both hold id and resource".to_string()), + }; + if tier.is_hardware() && lease.is_none() { + return Err("hardware receipts require --lease-hold and --lease-resource".to_string()); + } + let mut receipt = Receipt { + schema: SCHEMA.to_string(), + version: SCHEMA_VERSION, + id: String::new(), + kind: req.kind.clone(), + tier, + result, + timestamp: req.timestamp.unwrap_or_else(now), + repo: req.repo.clone(), + commit: req.commit.to_ascii_lowercase(), + dirty: req.dirty, + toolchain: req.toolchain.clone(), + procedure: req.procedure.clone(), + machine: req.machine.clone(), + env_class: tier.as_str().to_string(), + input_artifacts: req.input_artifacts.clone(), + output_artifacts: req.output_artifacts.clone(), + assertions, + dependencies: req + .dependencies + .iter() + .map(|d| d.to_ascii_lowercase()) + .collect(), + declared_mutation: declared, + observed_mutation: observed, + authority: req.authority.clone(), + output_digest, + external_refs: req.external_refs.clone(), + ledger, + lease, + required_features: vec![], + reserved: String::new(), + }; + let id = crate::evidence::receipt_id(&receipt)?; + receipt.id = id; + // Final self check: identity plus consistency, fail closed. + let text = serde_json::to_vec(&receipt).map_err(|e| e.to_string())?; + let (_, report) = crate::evidence::verify_bytes(&text)?; + if report.status == Verdict::Fail { + return Err(format!( + "built receipt fails self check: {}", + report.reasons.join("; ") + )); + } + Ok(receipt) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evidence::{store_receipt, verify_bytes}; + + fn write(path: &Path, text: &str) { + std::fs::write(path, text).unwrap(); + } + + fn req() -> ImportRequest { + ImportRequest { + repo: "https://github.com/aien-dev/aienos".to_string(), + commit: "a".repeat(40), + dirty: false, + kind: "seed-0b-qemu".to_string(), + tier: "QEMU".to_string(), + toolchain: "rustc 1.90.0".to_string(), + procedure: "scripts/qemu_seed0b.sh".to_string(), + machine: "qemu-virt-aarch64".to_string(), + input_artifacts: vec!["blake3:".to_string() + &"b".repeat(64)], + output_digest: Some("c".repeat(64)), + ..Default::default() + } + } + + #[test] + fn import_roundtrip() { + let dir = crate::testutil::temp_dir("import-ok"); + let file = dir.join("assert.json"); + write( + &file, + r#"{"assertions": [{"id": "artifact_signature_valid", "expected": "valid", "observed": "valid", "result": "pass", "source": "qemu"}]}"#, + ); + let (assertions, result) = read_assertion_file(&file).unwrap(); + assert_eq!(result, Verdict::Pass); + let receipt = build_receipt(&req(), assertions, result).unwrap(); + let store = crate::testutil::temp_dir("import-store"); + let id = store_receipt(&store, &receipt).unwrap(); + assert_eq!(id, receipt.id); + let text = std::fs::read(store.join("receipts").join(format!("{id}.json"))).unwrap(); + let (_, report) = verify_bytes(&text).unwrap(); + assert_eq!(report.status, Verdict::Pass); + } + + #[test] + fn prose_is_never_parsed() { + let dir = crate::testutil::temp_dir("import-prose"); + let file = dir.join("assert.json"); + write(&file, "all tests passed, trust me"); + assert!(read_assertion_file(&file).is_err()); + } + + #[test] + fn claimed_pass_with_failed_assertion_refused() { + let dir = crate::testutil::temp_dir("import-liar"); + let file = dir.join("assert.json"); + write( + &file, + r#"{"result": "PASS", "assertions": [{"id": "x", "result": "fail"}]}"#, + ); + assert!(read_assertion_file(&file).is_err()); + } + + #[test] + fn hardware_import_needs_mutation_and_lease() { + let dir = crate::testutil::temp_dir("import-hw"); + let file = dir.join("assert.json"); + write(&file, r#"{"assertions": [{"id": "x", "result": "pass"}]}"#); + let (assertions, result) = read_assertion_file(&file).unwrap(); + let mut r = req(); + r.tier = "MACHINE1_ATTENDED".to_string(); + r.machine = "machine-1".to_string(); + assert!(build_receipt(&r, assertions.clone(), result).is_err()); + r.declared_mutation = Some("REMOVABLE_MEDIA_ONLY".to_string()); + assert!(build_receipt(&r, assertions.clone(), result).is_err()); + r.lease_hold = Some("e".repeat(64)); + r.lease_resource = Some("machine-1".to_string()); + r.procedure = "scripts/seed0b_machine1.sh".to_string(); + let receipt = build_receipt(&r, assertions, result).unwrap(); + assert_eq!(receipt.env_class, "MACHINE1_ATTENDED"); + let _ = dir; + } + + #[test] + fn unknown_tier_and_mutation_refused() { + let dir = crate::testutil::temp_dir("import-bad-enum"); + let file = dir.join("assert.json"); + write(&file, r#"{"assertions": [{"id": "x", "result": "pass"}]}"#); + let (assertions, result) = read_assertion_file(&file).unwrap(); + let mut r = req(); + r.tier = "REAL_HARDWARE".to_string(); + assert!(build_receipt(&r, assertions.clone(), result).is_err()); + r.tier = "QEMU".to_string(); + r.declared_mutation = Some("FORMAT_EVERYTHING".to_string()); + assert!(build_receipt(&r, assertions, result).is_err()); + let _ = dir; + } +} diff --git a/crates/aien-proof/src/lease.rs b/crates/aien-proof/src/lease.rs new file mode 100644 index 00000000..c6cdcc4f --- /dev/null +++ b/crates/aien-proof/src/lease.rs @@ -0,0 +1,311 @@ +//! Exclusive resource lease binding for evidence receipts. +//! +//! Hardware runs go through the merged coordination machinery: +//! `Board::hold` runs the command while holding its exclusive keys, seals an +//! `audit` event into the Crumb ledger, and stores a hold record under +//! `holds/`. Receipts reference the hold by its audit event hash; this +//! module checks the record, the ledger event, and the output digest. +//! Nothing here invents a second lock: all exclusion lives in `board`. + +use std::fs; +use std::path::Path; + +use crate::board::{valid_resource, Record}; +use crate::evidence::{Receipt, Report, Verdict}; +use crate::ledger; + +/// Subdirectory of the proof board root holding hold records. +pub const HOLD_DIR: &str = "holds"; +/// Ledger action used for hold audit events. +pub const HOLD_ACTION: &str = "audit"; + +/// Resource names follow the board rule: path components of lowercase +/// letters, digits, and dashes, at most 64 bytes. +pub fn check_resource_name(name: &str) -> Result<(), String> { + if valid_resource(name) { + Ok(()) + } else { + Err(format!( + "invalid resource name {name:?}: use lowercase letters, digits, dashes" + )) + } +} + +/// Find the hold record whose audit event hash is `hold_id`. +pub fn load_hold(store: &Path, hold_id: &str) -> Result { + let normalized = hold_id.to_ascii_lowercase(); + if normalized.len() != 64 || !normalized.bytes().all(|b| b.is_ascii_hexdigit()) { + return Err(format!("hold id {hold_id:?} is not a 64 digit hash")); + } + let dir = store.join(HOLD_DIR); + let entries = fs::read_dir(&dir) + .map_err(|_| format!("hold record {normalized} not found: no holds in store"))?; + for entry in entries.flatten() { + let text = match fs::read(entry.path()) { + Ok(t) => t, + Err(_) => continue, + }; + if let Ok(record) = serde_json::from_slice::(&text) { + if record.ledger_hash.to_ascii_lowercase() == normalized { + return Ok(record); + } + } + } + Err(format!("missing hold record {normalized}")) +} + +/// Resources named in a hold audit intent (`... resources=a,b`). +fn intent_resources(intent: &str) -> Vec { + intent + .rsplit_once("resources=") + .map(|(_, list)| { + list.split(',') + .map(|s| s.trim().to_string()) + .filter(|s| !s.is_empty()) + .collect() + }) + .unwrap_or_default() +} + +/// Check a receipt's lease reference against the hold store and ledger. +/// Returns `None` when the receipt claims no lease. `Ok(Some(report))` is +/// the binding verdict; `Err` means the store itself is unreadable. +pub fn check_lease_ref(receipt: &Receipt, store: &Path) -> Result, String> { + let lease = match &receipt.lease { + Some(l) => l, + None => return Ok(None), + }; + let record = + load_hold(store, &lease.hold_id).map_err(|e| format!("lease binding broken: {e}"))?; + let mut problems = Vec::new(); + // The hold audit event must exist in the ledger with a matching hash. + let event = ledger::read_event(&store.join(ledger::LEDGER_FILE), record.ledger_index)? + .ok_or_else(|| { + format!( + "lease binding broken: ledger event {} is missing", + record.ledger_index + ) + })?; + if ledger::hex(&event.hash) != record.ledger_hash.to_ascii_lowercase() + || ledger::hex(&event.hash) != lease.hold_id.to_ascii_lowercase() + { + problems.push("hold record does not match its ledger audit event".to_string()); + } + if event.action != HOLD_ACTION { + problems.push(format!( + "ledger event {} is not a hold audit event", + record.ledger_index + )); + } + if !intent_resources(&event.intent) + .iter() + .any(|r| r == &lease.resource) + { + problems.push(format!( + "hold {} never covered resource {:?}", + lease.hold_id, lease.resource + )); + } + if receipt.machine != lease.resource { + problems.push(format!( + "receipt machine {:?} does not match leased resource {:?}", + receipt.machine, lease.resource + )); + } + if receipt.procedure != record.cmd.join(" ") { + problems.push(format!( + "receipt procedure {:?} does not match held command {:?}", + receipt.procedure, + record.cmd.join(" ") + )); + } + if !receipt + .output_digest + .eq_ignore_ascii_case(&ledger::hex(&event.payload_hash)) + { + problems.push("receipt output digest does not match the held run output".to_string()); + } + if receipt.result == Verdict::Pass && record.exit_code != 0 { + problems.push(format!( + "receipt claims PASS but the held run exited with {}", + record.exit_code + )); + } + if problems.is_empty() { + Ok(Some(Report::pass("lease binding checks out"))) + } else { + Ok(Some(Report::fail(problems))) + } +} + +/// Require a lease for hardware tiers. Called by chain and gate evaluation +/// so a Machine 1 qualification without a lease never reads as PASS. +pub fn lease_status(receipt: &Receipt, store: &Path) -> Option { + if !receipt.tier.is_hardware() { + return None; + } + match &receipt.lease { + None => Some(Report::closed( + Verdict::Incomplete, + vec!["Machine 1 qualification has no exclusive hardware lease".to_string()], + )), + Some(_) => match check_lease_ref(receipt, store) { + Ok(Some(r)) => Some(r), + Ok(None) => None, + Err(e) => Some(Report::fail(vec![e])), + }, + } +} + +/// Run a held command through the board and return its record plus the +/// output digest. Test helper that exercises the real exclusion path. +#[cfg(test)] +pub fn test_hold( + store: &Path, + base: &Path, + resource: &str, + holder: &str, + cmd: &[String], +) -> (Record, String) { + use crate::board::{Board, Job}; + let board = Board { + root: store.to_path_buf(), + cpu_slots: 4, + min_free_bytes: 0, + mem_wait: std::time::Duration::from_secs(1), + quiet: true, + }; + let job = Job { + name: format!("test-hold-{resource}"), + agent: holder.to_string(), + base: base.to_path_buf(), + inputs: vec![], + cmd: cmd.to_vec(), + gpu: false, + resources: vec![resource.to_string()], + toolchain: String::new(), + }; + let record = board.hold(&job).unwrap(); + let event = ledger::read_event(&store.join(ledger::LEDGER_FILE), record.ledger_index) + .unwrap() + .unwrap(); + let digest = ledger::hex(&event.payload_hash); + (record, digest) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evidence::fixtures::{sample, sealed}; + use crate::evidence::{store_receipt, LeaseRef, Mutation, Tier, Verdict}; + + fn machine_receipt( + resource: &str, + procedure: &str, + lease: Option, + output: &str, + ) -> Receipt { + let mut r = sample(); + r.tier = Tier::Machine1Attended; + r.env_class = "MACHINE1_ATTENDED".to_string(); + r.machine = resource.to_string(); + r.procedure = procedure.to_string(); + r.declared_mutation = Mutation::RemovableMediaOnly; + r.observed_mutation = Mutation::RemovableMediaOnly; + r.output_digest = output.to_string(); + r.lease = lease; + sealed(r) + } + + fn held_run(tag: &str) -> (std::path::PathBuf, (Record, String)) { + let store = crate::testutil::temp_dir(tag); + let base = crate::testutil::temp_dir(&format!("{tag}-base")); + let cmd = vec![ + "sh".to_string(), + "-c".to_string(), + "printf held-output".to_string(), + ]; + let held = test_hold(&store, &base, "machine-1", "tester", &cmd); + (store, held) + } + + #[test] + fn resource_names_follow_the_board_rule() { + assert!(check_resource_name("machine-1").is_ok()); + assert!(check_resource_name("machine_1").is_err()); + assert!(check_resource_name("Machine-1").is_err()); + assert!(check_resource_name("").is_err()); + } + + #[test] + fn lease_binding_verifies_end_to_end() { + let (store, (record, digest)) = held_run("lease-ok"); + let r = machine_receipt( + "machine-1", + &record.cmd.join(" "), + Some(LeaseRef { + hold_id: record.ledger_hash.clone(), + resource: "machine-1".to_string(), + }), + &digest, + ); + store_receipt(&store, &r).unwrap(); + let report = check_lease_ref(&r, &store).unwrap().unwrap(); + assert_eq!(report.status, Verdict::Pass); + } + + #[test] + fn hardware_receipt_without_hold_is_incomplete() { + let store = crate::testutil::temp_dir("lease-missing"); + let r = machine_receipt("machine-1", "scripts/x.sh", None, &"c".repeat(64)); + let report = lease_status(&r, &store).unwrap(); + assert_eq!(report.status, Verdict::Incomplete); + } + + #[test] + fn output_digest_mismatch_fails_binding() { + let (store, (record, _)) = held_run("lease-digest"); + let r = machine_receipt( + "machine-1", + &record.cmd.join(" "), + Some(LeaseRef { + hold_id: record.ledger_hash.clone(), + resource: "machine-1".to_string(), + }), + &"d".repeat(64), + ); + let report = check_lease_ref(&r, &store).unwrap().unwrap(); + assert_eq!(report.status, Verdict::Fail); + } + + #[test] + fn wrong_resource_fails_binding() { + let (store, (record, digest)) = held_run("lease-resource"); + let r = machine_receipt( + "machine-2", + &record.cmd.join(" "), + Some(LeaseRef { + hold_id: record.ledger_hash.clone(), + resource: "machine-2".to_string(), + }), + &digest, + ); + let report = check_lease_ref(&r, &store).unwrap().unwrap(); + assert_eq!(report.status, Verdict::Fail); + } + + #[test] + fn missing_hold_record_fails_closed() { + let store = crate::testutil::temp_dir("lease-gone"); + let r = machine_receipt( + "machine-1", + "scripts/x.sh", + Some(LeaseRef { + hold_id: "e".repeat(64), + resource: "machine-1".to_string(), + }), + &"c".repeat(64), + ); + assert!(check_lease_ref(&r, &store).is_err()); + } +} diff --git a/crates/aien-proof/src/ledger.rs b/crates/aien-proof/src/ledger.rs index 21cd632b..6ab972b4 100644 --- a/crates/aien-proof/src/ledger.rs +++ b/crates/aien-proof/src/ledger.rs @@ -187,6 +187,23 @@ pub fn hex(bytes: &[u8; 32]) -> String { bytes.iter().map(|b| format!("{b:02x}")).collect() } +/// Read the event at `index`, or `Ok(None)` when the ledger is shorter. +pub fn read_event(path: &Path, index: u64) -> Result, String> { + let text = match fs::read_to_string(path) { + Ok(t) => t, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(e.to_string()), + }; + for (n, line) in text.lines().filter(|l| !l.trim().is_empty()).enumerate() { + let e: LedgerEvent = + serde_json::from_str(line).map_err(|err| format!("line {}: {err}", n + 1))?; + if e.index == index { + return Ok(Some(e)); + } + } + Ok(None) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/aien-proof/src/ledger_bind.rs b/crates/aien-proof/src/ledger_bind.rs new file mode 100644 index 00000000..1cf84ddb --- /dev/null +++ b/crates/aien-proof/src/ledger_bind.rs @@ -0,0 +1,98 @@ +//! Crumb ledger cross checks for evidence receipts. +//! +//! The ledger remains the append only operational audit stream. Receipts +//! reference relevant ledger event IDs and digests instead of duplicating +//! the ledger, and verification confirms the chain, the referenced event, +//! and the output hash match. + +use std::path::Path; + +use crate::evidence::Receipt; +use crate::ledger; + +/// Check a receipt's ledger reference. Returns `Ok(None)` when the receipt +/// carries no reference, `Ok(Some(problem))` with a fail closed reason when +/// the reference does not check out. +pub fn check_ledger_ref(receipt: &Receipt, store: &Path) -> Result, String> { + let reference = match &receipt.ledger { + Some(r) => r, + None => return Ok(None), + }; + let path = store.join(ledger::LEDGER_FILE); + ledger::verify(&path).map_err(|e| format!("ledger chain broken: {e}"))?; + let event = ledger::read_event(&path, reference.index)?.ok_or_else(|| { + format!( + "receipt references ledger event {} which does not exist", + reference.index + ) + })?; + if ledger::hex(&event.hash) != reference.hash.to_ascii_lowercase() { + return Ok(Some(format!( + "receipt ledger hash does not match event {}", + reference.index + ))); + } + if ledger::hex(&event.payload_hash) != receipt.output_digest.to_ascii_lowercase() { + return Ok(Some( + "receipt output digest does not match the ledger payload hash".to_string(), + )); + } + Ok(None) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::evidence::fixtures::{sample, sealed}; + use crate::evidence::{LedgerRef, Tier, Verdict}; + + #[test] + fn matching_ledger_ref_passes() { + let store = crate::testutil::temp_dir("ledgerbind-ok"); + let output = b"seed output"; + let event = ledger::append(&store, "tester", "seed-0b", "pass exit=0", output).unwrap(); + let mut r = sample(); + r.output_digest = ledger::hex(&event.payload_hash); + r.ledger = Some(LedgerRef { + index: event.index, + hash: ledger::hex(&event.hash), + }); + let r = sealed(r); + assert_eq!(check_ledger_ref(&r, &store).unwrap(), None); + } + + #[test] + fn output_digest_mismatch_fails_closed() { + let store = crate::testutil::temp_dir("ledgerbind-digest"); + let event = ledger::append(&store, "tester", "seed-0b", "pass exit=0", b"real").unwrap(); + let mut r = sample(); + r.output_digest = "d".repeat(64); + r.ledger = Some(LedgerRef { + index: event.index, + hash: ledger::hex(&event.hash), + }); + let r = sealed(r); + assert!(check_ledger_ref(&r, &store).unwrap().is_some()); + } + + #[test] + fn missing_event_fails_closed() { + let store = crate::testutil::temp_dir("ledgerbind-missing"); + ledger::append(&store, "tester", "seed-0b", "pass exit=0", b"real").unwrap(); + let mut r = sample(); + r.ledger = Some(LedgerRef { + index: 7, + hash: "e".repeat(64), + }); + let r = sealed(r); + assert!(check_ledger_ref(&r, &store) + .unwrap_err() + .contains("does not exist")); + } + + #[test] + fn tier_and_verdict_reexports_used() { + assert_eq!(Tier::Qemu.as_str(), "QEMU"); + assert_eq!(Verdict::Pass.as_str(), "PASS"); + } +} diff --git a/crates/aien-proof/src/lib.rs b/crates/aien-proof/src/lib.rs index c4535b02..6eb8b992 100644 --- a/crates/aien-proof/src/lib.rs +++ b/crates/aien-proof/src/lib.rs @@ -10,8 +10,14 @@ //! with the run's full output as the payload. pub mod board; +pub mod chain; +pub mod evidence; pub mod fingerprint; +pub mod gate; +pub mod import; +pub mod lease; pub mod ledger; +pub mod ledger_bind; pub mod lock; pub mod workspace; diff --git a/crates/aien-proof/src/main.rs b/crates/aien-proof/src/main.rs index 356b3a8d..02b49d1d 100644 --- a/crates/aien-proof/src/main.rs +++ b/crates/aien-proof/src/main.rs @@ -5,9 +5,17 @@ //! aien-proof crates [--dir WORKSPACE] [--agent ID] [--gpu-crate NAME]... [--only NAME]... [-- CARGO_TEST_ARGS...] //! aien-proof verify //! aien-proof status +//! aien-proof receipt show [--store DIR] +//! aien-proof receipt verify [--store DIR] +//! aien-proof receipt import [options] --assert FILE [--store DIR] +//! aien-proof qualify [same options as receipt import] +//! aien-proof verify-chain [--store DIR] +//! aien-proof gate status [--store DIR] [--gate FILE] +//! aien-proof gate explain [--store DIR] [--gate FILE] +//! aien-proof gate examples [--out DIR] use aien_proof::board::{mem_available, Board, Job, Outcome}; -use aien_proof::{ledger, workspace}; +use aien_proof::{chain, evidence, gate, import, ledger, workspace}; use std::path::PathBuf; use std::process::{exit, Command}; use std::time::Instant; @@ -17,12 +25,21 @@ const USAGE: &str = "usage: aien-proof hold --resource NAME... [--job NAME] [--agent ID] -- CMD... aien-proof crates [--dir WORKSPACE] [--agent ID] [--gpu-crate NAME]... [--only NAME]... [-- CARGO_TEST_ARGS...] aien-proof verify - aien-proof status"; + aien-proof status + aien-proof receipt show [--store DIR] + aien-proof receipt verify [--store DIR] + aien-proof receipt import --repo URL --commit SHA --gate KIND --tier TIER --procedure PROC --machine MACH --assert FILE [--store DIR] [options] + aien-proof qualify --repo URL --commit SHA --gate KIND --tier TIER --procedure PROC --machine MACH --assert FILE [--store DIR] [options] + aien-proof verify-chain [--store DIR] + aien-proof gate status [--store DIR] [--gate FILE] + aien-proof gate explain [--store DIR] [--gate FILE] + aien-proof gate examples [--out DIR]"; struct Flags { values: Vec<(String, String)>, switches: Vec, rest: Vec, + positionals: Vec, } impl Flags { @@ -31,6 +48,7 @@ impl Flags { values: vec![], switches: vec![], rest: vec![], + positionals: vec![], }; let mut i = 0; while i < args.len() { @@ -43,9 +61,11 @@ impl Flags { } else if a.starts_with("--") && i + 1 < args.len() { f.values.push((a.clone(), args[i + 1].clone())); i += 1; - } else { - eprintln!("unexpected argument: {a}\n{USAGE}"); + } else if a.starts_with("--") { + eprintln!("option {a} needs a value\n{USAGE}"); exit(2); + } else { + f.positionals.push(a.clone()); } i += 1; } @@ -67,6 +87,10 @@ impl Flags { .map(|(_, v)| v.clone()) .collect() } + + fn has(&self, name: &str) -> bool { + self.switches.iter().any(|s| s == name) + } } fn agent(flags: &Flags) -> String { @@ -96,7 +120,7 @@ fn toolchain() -> String { fn cmd_run(args: &[String]) -> i32 { let flags = Flags::parse(args, &["--gpu"]); - if flags.rest.is_empty() { + if flags.rest.is_empty() || !flags.positionals.is_empty() { eprintln!("{USAGE}"); return 2; } @@ -128,6 +152,10 @@ fn cmd_run(args: &[String]) -> i32 { fn cmd_crates(args: &[String]) -> i32 { let flags = Flags::parse(args, &[]); + if !flags.positionals.is_empty() { + eprintln!("{USAGE}"); + return 2; + } let here = flags .get("--dir") .map(PathBuf::from) @@ -227,7 +255,7 @@ fn cmd_verify() -> i32 { fn cmd_hold(args: &[String]) -> i32 { let flags = Flags::parse(args, &[]); let resources = flags.all("--resource"); - if flags.rest.is_empty() || resources.is_empty() { + if flags.rest.is_empty() || resources.is_empty() || !flags.positionals.is_empty() { eprintln!("{USAGE}"); return 2; } @@ -254,6 +282,9 @@ fn cmd_hold(args: &[String]) -> i32 { rec.exit_code, rec.ledger_index ); + // The audit event hash on stdout is the hold ID that evidence + // receipts bind with `--lease-hold`. + println!("{}", rec.ledger_hash); rec.exit_code } Err(e) => { @@ -272,6 +303,8 @@ fn cmd_status() -> i32 { println!("board: {}", b.root.display()); println!("stamps: {}", count(b.root.join("stamps"))); println!("failures: {}", count(b.root.join("fails"))); + println!("receipts: {}", count(b.root.join(evidence::RECEIPT_DIR))); + println!("holds: {}", count(b.root.join("holds"))); println!("cpu slots: {}", b.cpu_slots); println!("memory gate:{} GiB free required", b.min_free_bytes >> 30); if let Some(free) = mem_available() { @@ -283,6 +316,384 @@ fn cmd_status() -> i32 { cmd_verify() } +fn store_dir(flags: &Flags) -> PathBuf { + flags + .get("--store") + .map(PathBuf::from) + .unwrap_or_else(|| Board::from_env().root) +} + +fn verdict_code(v: evidence::Verdict) -> i32 { + match v { + evidence::Verdict::Pass => 0, + evidence::Verdict::Fail => 1, + evidence::Verdict::Blocked => 2, + evidence::Verdict::Incomplete => 3, + evidence::Verdict::Skipped => 4, + } +} + +const IMPORT_USAGE: &str = "usage: + aien-proof receipt import --repo URL --commit SHA --gate KIND --tier TIER --procedure PROC --machine MACH --assert FILE [options] +options: + --toolchain TEXT build/toolchain identity (default: rustc -vV) + --artifact DIGEST input artifact digest, repeatable + --output-artifact DIGEST output artifact digest, repeatable + --dep RECEIPT_ID dependency receipt ID, repeatable + --declared-mutation CLASS required for hardware tiers + --observed-mutation CLASS defaults to declared + --authority REF approval reference; required for PRODUCTION + --output-digest HEX BLAKE3 of complete captured output + --output-file PATH hashed for the output digest + --external-ref REF external evidence reference, repeatable + --ledger INDEX:HASH Crumb ledger event reference + --lease-hold HOLD_ID audit event hash from `aien-proof hold` + --lease-resource NAME resource the hold covered + --dirty mark the source tree dirty + --out PATH also write the receipt file here + --store DIR receipt store (default: proof board dir)"; + +fn cmd_receipt(args: &[String]) -> i32 { + let (sub, rest) = match args.split_first() { + Some((s, r)) => (s.as_str(), r), + None => { + eprintln!("{USAGE}"); + return 2; + } + }; + match sub { + "show" => cmd_receipt_show(rest), + "verify" => cmd_receipt_verify(rest), + "import" => cmd_receipt_import(rest), + _ => { + eprintln!("unknown receipt subcommand {sub}\n{USAGE}"); + 2 + } + } +} + +fn cmd_receipt_show(args: &[String]) -> i32 { + let flags = Flags::parse(args, &[]); + let store = store_dir(&flags); + let id = match flags.positionals.first() { + Some(id) => id.clone(), + None => { + eprintln!("usage: aien-proof receipt show [--store DIR]"); + return 2; + } + }; + match evidence::load_receipt(&store, &id) { + Ok(receipt) => { + println!("{}", serde_json::to_string_pretty(&receipt).unwrap()); + 0 + } + Err(e) => { + eprintln!("[aien-proof] {e}"); + 1 + } + } +} + +fn cmd_receipt_verify(args: &[String]) -> i32 { + let flags = Flags::parse(args, &[]); + let store = store_dir(&flags); + let path = match flags.positionals.first() { + Some(p) => PathBuf::from(p), + None => { + eprintln!("usage: aien-proof receipt verify [--store DIR]"); + return 2; + } + }; + let text = match std::fs::read(&path) { + Ok(t) => t, + Err(e) => { + eprintln!("[aien-proof] cannot read {}: {e}", path.display()); + return 2; + } + }; + match evidence::verify_with_store(&text, &store) { + Ok((receipt, report)) => { + println!("receipt {}: {}", receipt.id, report.status.as_str()); + for reason in &report.reasons { + println!(" - {reason}"); + } + verdict_code(report.status) + } + Err(e) => { + println!("receipt BROKEN: {e}"); + 1 + } + } +} + +fn cmd_receipt_import(args: &[String]) -> i32 { + let flags = Flags::parse(args, &["--dirty"]); + let assert_path = match flags.get("--assert") { + Some(p) => PathBuf::from(p), + None => { + eprintln!("{IMPORT_USAGE}"); + return 2; + } + }; + for required in [ + "--repo", + "--commit", + "--gate", + "--tier", + "--procedure", + "--machine", + ] { + if flags.get(required).is_none() { + eprintln!("missing {required}\n{IMPORT_USAGE}"); + return 2; + } + } + let store = store_dir(&flags); + let (assertions, result) = match import::read_assertion_file(&assert_path) { + Ok(v) => v, + Err(e) => { + eprintln!("[aien-proof] {e}"); + return 2; + } + }; + let (ledger_index, ledger_hash) = match flags.get("--ledger") { + Some(pair) => match pair.split_once(':') { + Some((index, hash)) => match index.parse::() { + Ok(i) => (Some(i), Some(hash.to_string())), + Err(_) => { + eprintln!("[aien-proof] bad --ledger value, want INDEX:HASH"); + return 2; + } + }, + None => { + eprintln!("[aien-proof] bad --ledger value, want INDEX:HASH"); + return 2; + } + }, + None => (None, None), + }; + let req = import::ImportRequest { + repo: flags.get("--repo").unwrap().to_string(), + commit: flags.get("--commit").unwrap().to_string(), + dirty: flags.has("--dirty"), + kind: flags.get("--gate").unwrap().to_string(), + tier: flags.get("--tier").unwrap().to_string(), + toolchain: flags + .get("--toolchain") + .map(str::to_string) + .unwrap_or_else(toolchain), + procedure: flags.get("--procedure").unwrap().to_string(), + machine: flags.get("--machine").unwrap().to_string(), + input_artifacts: flags.all("--artifact"), + output_artifacts: flags.all("--output-artifact"), + dependencies: flags.all("--dep"), + declared_mutation: flags.get("--declared-mutation").map(str::to_string), + observed_mutation: flags.get("--observed-mutation").map(str::to_string), + authority: flags + .get("--authority") + .map(str::to_string) + .unwrap_or_default(), + output_digest: flags.get("--output-digest").map(str::to_string), + output_file: flags.get("--output-file").map(str::to_string), + external_refs: flags.all("--external-ref"), + ledger_index, + ledger_hash, + lease_hold: flags.get("--lease-hold").map(str::to_string), + lease_resource: flags.get("--lease-resource").map(str::to_string), + timestamp: None, + }; + let receipt = match import::build_receipt(&req, assertions, result) { + Ok(r) => r, + Err(e) => { + eprintln!("[aien-proof] import refused: {e}"); + return 1; + } + }; + // Warn about dependencies that cannot be resolved yet. They stay + // missing, and verification reports INCOMPLETE, never PASS. + for dep in &receipt.dependencies { + if evidence::load_receipt(&store, dep).is_err() { + eprintln!("[aien-proof] warning: dependency {dep} not in store yet"); + } + } + match evidence::store_receipt(&store, &receipt) { + Ok(id) => { + println!("{id}"); + if let Some(out) = flags.get("--out") { + let text = serde_json::to_string_pretty(&receipt).unwrap(); + if let Err(e) = std::fs::write(out, format!("{text}\n")) { + eprintln!("[aien-proof] stored as {id} but --out failed: {e}"); + return 1; + } + } + 0 + } + Err(e) => { + eprintln!("[aien-proof] cannot store receipt: {e}"); + 1 + } + } +} + +fn cmd_verify_chain(args: &[String]) -> i32 { + let flags = Flags::parse(args, &[]); + let store = store_dir(&flags); + let path = match flags.positionals.first() { + Some(p) => PathBuf::from(p), + None => { + eprintln!("usage: aien-proof verify-chain [--store DIR]"); + return 2; + } + }; + match chain::verify_chain(&path, &store) { + Ok(report) => { + println!("chain {}: {}", report.root, report.status.as_str()); + for line in &report.lines { + println!( + " {} {:<24} {:<18} {} {}", + line.status.as_str(), + line.kind, + line.tier.as_str(), + &line.id[..16.min(line.id.len())], + line.note + ); + } + for reason in &report.reasons { + println!(" - {reason}"); + } + verdict_code(report.status) + } + Err(e) => { + println!("chain BROKEN: {e}"); + 1 + } + } +} + +fn cmd_gate(args: &[String]) -> i32 { + let (sub, rest) = match args.split_first() { + Some((s, r)) => (s.as_str(), r), + None => { + eprintln!("{USAGE}"); + return 2; + } + }; + match sub { + "status" => cmd_gate_status(rest, false), + "explain" => cmd_gate_status(rest, true), + "examples" => cmd_gate_examples(rest), + _ => { + eprintln!("unknown gate subcommand {sub}\n{USAGE}"); + 2 + } + } +} + +fn cmd_gate_status(args: &[String], verbose: bool) -> i32 { + let flags = Flags::parse(args, &[]); + let store = store_dir(&flags); + let name = match flags.positionals.first() { + Some(n) => n.clone(), + None => { + eprintln!("usage: aien-proof gate status [--store DIR] [--gate FILE]"); + return 2; + } + }; + let explicit = flags.get("--gate").map(PathBuf::from); + let manifest = match gate::load_manifest(&store, &name, explicit.as_deref()) { + Ok(m) => m, + Err(e) => { + eprintln!("[aien-proof] {e}"); + return 2; + } + }; + let report = gate::evaluate(&manifest, &store); + println!("{}: {}", report.gate, report.status.as_str()); + for line in &report.lines { + let word = match line.status { + evidence::Verdict::Pass => "PASS", + evidence::Verdict::Fail => "FAIL", + _ => line.status.as_str(), + }; + println!("{word:<7} {} {}", line.name, line.detail); + if verbose { + explain_requirement(&store, &manifest, line, 1); + } + } + verdict_code(report.status) +} + +/// Verbose `explain` detail for one gate line: sub gate lines recurse with +/// indentation, receipt matches show their assertion table. +fn explain_requirement( + store: &std::path::Path, + manifest: &gate::Gate, + line: &gate::GateLine, + depth: usize, +) { + if depth > 12 { + println!( + "{}gate explanation depth limit reached", + " ".repeat(depth * 2) + ); + return; + } + let pad = " ".repeat(depth * 2); + let req = match manifest.requires.iter().find(|r| r.name == line.name) { + Some(r) => r, + None => return, + }; + if let Some(child) = &req.gate_ref { + match gate::load_manifest(store, child, None) { + Ok(child_manifest) => { + let report = gate::evaluate(&child_manifest, store); + for subline in &report.lines { + println!( + "{pad}{} {} {}", + subline.status.as_str(), + subline.name, + subline.detail + ); + explain_requirement(store, &child_manifest, subline, depth + 1); + } + } + Err(e) => println!("{pad}BLOCKED {child}: {e}"), + } + return; + } + if let Some(receipt) = gate::best_candidate(store, &req.kind) { + println!("{pad}id {} tier {}", receipt.id, receipt.tier.as_str()); + for a in &receipt.assertions { + println!( + "{pad}[{}] {} expected={:?} observed={:?} source={:?}", + if a.pass { "x" } else { " " }, + a.id, + a.expected, + a.observed, + a.source + ); + } + } +} + +fn cmd_gate_examples(args: &[String]) -> i32 { + let flags = Flags::parse(args, &[]); + let default = Board::from_env().root.join(gate::GATE_DIR); + let out = flags.get("--out").map(PathBuf::from).unwrap_or(default); + match gate::write_examples(&out) { + Ok(paths) => { + for p in paths { + println!("{}", p.display()); + } + 0 + } + Err(e) => { + eprintln!("[aien-proof] {e}"); + 1 + } + } +} + fn main() { let args: Vec = std::env::args().skip(1).collect(); let code = match args.first().map(String::as_str) { @@ -291,6 +702,10 @@ fn main() { Some("hold") => cmd_hold(&args[1..]), Some("verify") => cmd_verify(), Some("status") => cmd_status(), + Some("receipt") => cmd_receipt(&args[1..]), + Some("qualify") => cmd_receipt_import(&args[1..]), + Some("verify-chain") => cmd_verify_chain(&args[1..]), + Some("gate") => cmd_gate(&args[1..]), _ => { eprintln!("{USAGE}"); 2 diff --git a/docs/EVIDENCE_RECEIPT_ADAPTER.md b/docs/EVIDENCE_RECEIPT_ADAPTER.md new file mode 100644 index 00000000..e3a5c08b --- /dev/null +++ b/docs/EVIDENCE_RECEIPT_ADAPTER.md @@ -0,0 +1,336 @@ +# Evidence Receipt Adapter Specification for `aienos` + +Scope: how `aienos` test setups emit machine readable qualification results +that `aien-proof` turns into sealed evidence receipts. This document is an +input contract only. Every JSON block marked EXAMPLE is a shape example, not +evidence. No gate has passed unless `aien-proof gate status` says PASS over +real stored receipts. + +You never need to edit `aien-proof` or depend on its Rust internals. You need +only: + +1. a built `aien-proof` binary on PATH (or `cargo run -p aien-proof --`), +2. a shared receipt store (the proof board dir, `AIEN_PROOF_DIR`), +3. an assertion file your test setup writes, +4. one `aien-proof receipt import` (alias: `aien-proof qualify`) call per run, +5. for Machine 1 runs, a `hold` lease around the run. + +## 1. Assertion file contract + +Your setup writes one JSON file per run. Prose is never parsed. The file +must match this shape exactly (unknown fields are refused): + +```json +{ + "assertions": [ + { + "id": "artifact_signature_valid", + "expected": "valid", + "observed": "valid", + "result": "pass", + "source": "scripts/qemu_seed0b.sh", + "note": "" + } + ], + "result": "PASS" +} +``` + +Rules: + +- `id` is stable across runs (`secure_boot_unchanged`, `boot_order_unchanged`, + `artifact_signature_valid`, `granted_subset_requested`, + `w_x_never_simultaneous`, `unauthorized_write_denied`, + `all_task_frames_reclaimed`, `store_previous_or_new_only`, + `root_graph_valid`, `machine_returned_to_linux`). +- `result` per assertion is `pass` or `fail` (or boolean true/false). +- Top level `result` is optional. When absent it is derived (all pass gives + PASS, else FAIL). A claimed PASS with any failing assertion is refused. + A failing run can never be upgraded to PASS at import. +- At least one assertion is required for a PASS receipt. +- Assertion `source` is part of the canonical receipt identity. For hardware + topology and ownership claims, use one stable provenance category as the + source: `linux_observed`, `uefi_observed`, `native_aienos_observed`, + `qemu_synthetic`, `derived`, or `unknown`. Put collector/tool identity and + detail in `note` and bind its output as an artifact. A Linux-observed + topology assertion cannot satisfy a gate that source-pins + `native_aienos_observed`. + +## 2. Import command contract + +EXAMPLE (SEED-0B QEMU run): + +```sh +aien-proof receipt import \ + --repo https://github.com/aien-dev/aienos \ + --commit 3fa4c8e2b1d04f7a9c6e5b8d2a1f4c7e9b0d3f21 \ + --gate seed-0b-qemu \ + --tier QEMU \ + --procedure "scripts/qemu_seed0b.sh" \ + --machine qemu-virt-aarch64 \ + --toolchain "$(rustc -vV)" \ + --assert /tmp/seed0b-assert.json \ + --artifact blake3: \ + --output-file /tmp/seed0b-output.log \ + --dep \ + --dep +``` + +Field notes: + +- `--commit` is the exact 40 digit lowercase git SHA (64 digits accepted). +- `--tier` is one of `HOST_TEST QEMU QEMU_SECURITY MACHINE1_READ_ONLY + MACHINE1_ATTENDED MACHINE1_MUTATING TEST_ONLY_TRUST PRODUCTION`. + The environment label always equals the tier, so a QEMU run can never be + filed as physical qualification. +- `--artifact` digests are `:` with algo `blake3`, `sha256`, or + `sha512` (repeatable). +- `--output-file` is hashed to the receipt output digest. Prefer it over + `--output-digest`. +- `--dep` lists prerequisite receipt IDs (repeatable). Missing deps stay + missing: verification reports INCOMPLETE, never PASS. +- `--dirty` marks uncommitted source changes. Gates that require clean + sources block dirty receipts. +- On success the command prints the receipt ID (the BLAKE3 of the canonical + encoding) and stores `/receipts/.json`. + +## 3. Machine 1 runs: the `hold` lease + +Every `MACHINE1_*` receipt must bind an exclusive hold from the existing +coordination machinery. No second lock exists. Wrap the run: + +```sh +HOLD=$(aien-proof hold --resource machine-1 --job seed-0b-machine1 -- \ + scripts/seed0b_machine1.sh 2>/dev/null | tail -n 1) +``` + +`hold` always runs (no fingerprint, stamp, or reuse), holds every +`--resource` key plus the holder record for the whole run, seals an `audit` +event into the Crumb ledger with the full output as payload, and stores +`holds/.json`. The audit event hash printed on stdout is the hold ID. +Resource names are lowercase letters, digits, and dashes only. `run +--resource` takes the same keys, so test-board runs and holds exclude each +other on one machine. + +Then import with: + +```sh + --tier MACHINE1_ATTENDED \ + --machine machine-1 \ + --procedure "scripts/seed0b_machine1.sh" \ + --declared-mutation REMOVABLE_MEDIA_ONLY \ + --lease-hold "$HOLD" \ + --lease-resource machine-1 \ + --output-file +``` + +Rules: + +- `--procedure` must equal the held command line exactly. +- `--machine` must equal the leased resource. +- `--output-file` (or digest) must equal the held run output digest. +- `--declared-mutation` is required for hardware tiers. Allowed classes: + `NONE VOLATILE_ONLY REMOVABLE_MEDIA_ONLY ONE_TIME_BOOT_SELECTION + BOUNDED_TEST_REGION_WRITE BOOT_CONFIGURATION_CHANGE TRUST_ROOT_CHANGE + TPM_POLICY_CHANGE DESTRUCTIVE_STORAGE`. +- A read-only run (`MACHINE1_READ_ONLY`) cannot claim more than + `REMOVABLE_MEDIA_ONLY`. Observed mutation beyond declared mutation fails. +- A Machine 1 receipt without a matching exclusive hold verifies as + INCOMPLETE, never PASS. + +## 4. EXAMPLE input contracts per gate input + +All values below are placeholders. Replace them with measured values. + +### 4.1 SEED-0B QEMU (owner: SEED-0B completion lane) + +EXAMPLE assertion file: + +```json +{ + "assertions": [ + {"id": "artifact_identity", "expected": "", "observed": "", "result": "pass", "source": "scripts/qemu_seed0b.sh"}, + {"id": "artifact_signature_valid", "expected": "valid", "observed": "valid", "result": "pass", "source": "scripts/qemu_seed0b.sh"}, + {"id": "granted_subset_requested", "expected": "subset", "observed": "subset", "result": "pass", "source": "admission-check"}, + {"id": "authorized_op_permitted", "expected": "permit", "observed": "permit", "result": "pass", "source": "admission-check"}, + {"id": "unauthorized_write_denied", "expected": "deny", "observed": "deny", "result": "pass", "source": "admission-check"}, + {"id": "all_task_frames_reclaimed", "expected": "0 live", "observed": "0 live", "result": "pass", "source": "cleanup-check"}, + {"id": "machine_returned_to_linux", "expected": "linux", "observed": "linux", "result": "pass", "source": "cleanup-check"} + ] +} +``` + +Import with `--gate seed-0b-qemu --tier QEMU`, plus `--dep` on the M3 +receipt and the recovery media receipt IDs. The hostile input matrix is a +separate import with `--gate seed-0b-hostile-matrix --tier QEMU`. + +### 4.2 M0 rollback QEMU and Machine 1 are different facts (owner: M0 rollback lane) + +EXAMPLE assertion file: + +```json +{ + "assertions": [ + {"id": "rollback_harness_version_recorded", "expected": "version in procedure identity", "observed": "exact harness version", "result": "pass", "source": "rollback_harness"}, + {"id": "qemu_aavmf_environment_recorded", "expected": "QEMU and AAVMF identities", "observed": "exact QEMU/AAVMF versions and firmware digests", "result": "pass", "source": "qemu_environment_collector"}, + {"id": "rollback_normal_pass", "expected": "pass", "observed": "pass", "result": "pass", "source": "aavmf_serial_output"}, + {"id": "rollback_fault_pass", "expected": "pass", "observed": "pass", "result": "pass", "source": "aavmf_serial_output"}, + {"id": "rollback_timeout_pass", "expected": "pass", "observed": "pass", "result": "pass", "source": "aavmf_serial_output"}, + {"id": "rollback_rejected_pass", "expected": "pass", "observed": "pass", "result": "pass", "source": "aavmf_serial_output"}, + {"id": "rollback_absent_pass", "expected": "pass", "observed": "pass", "result": "pass", "source": "aavmf_serial_output"}, + {"id": "rollback_repeat_boot_pass", "expected": "pass", "observed": "pass", "result": "pass", "source": "aavmf_serial_output"}, + {"id": "bootnext_consumed", "expected": "unset in AAVMF NVRAM after one-time boot", "observed": "unset", "result": "pass", "source": "aavmf_variables"}, + {"id": "default_boot_unchanged", "expected": "default entry selected after candidate", "observed": "default entry selected", "result": "pass", "source": "aavmf_variables"}, + {"id": "m0_native_rollback_qemu_pass", "expected": "all required branches pass", "observed": "all required branches pass", "result": "pass", "source": "rollback_harness_summary"} + ] +} +``` + +Import the QEMU run under `--gate m0-native-rollback-qemu --tier QEMU`. +Bind the exact `aienos` commit, harness version in `--procedure`, QEMU/AAVMF +identity in `--machine` and input artifact digests, and complete captured +output with `--output-file`. If the run also includes a pure state machine +mock, emit its observations with source `rollback_state_machine_mock`; firmware +variable observations must use source `aavmf_variables`. A mock result alone +cannot satisfy `bootnext_consumed`. + +Do not import a Machine 1 rollback receipt until the owner trust chain permits +the attended run. That future receipt must prove Secure Boot stayed on, +permanent BootOrder stayed unchanged, BootNext was consumed, Linux/default boot +returned, root and ESP UUIDs stayed unchanged, expected mounts are healthy, and +the exact candidate digest and source commit were recorded. It must use +`MACHINE1_ATTENDED`, declare `ONE_TIME_BOOT_SELECTION`, and reference the +existing `aien-proof hold --resource machine-1 -- ...` event. QEMU rollback +evidence never satisfies this receipt. + +### 4.3 System Store v1 crash consistency (owner: System Store lane) + +EXAMPLE assertion file: + +```json +{ + "assertions": [ + {"id": "store_previous_or_new_only", "expected": "no torn writes", "observed": "no torn writes", "result": "pass", "source": "crash-qualify.sh"}, + {"id": "store_graph_valid", "expected": "valid", "observed": "valid", "result": "pass", "source": "crash-qualify.sh"}, + {"id": "store_nospace_zero_writes", "expected": "zero writes", "observed": "zero writes", "result": "pass", "source": "crash-qualify.sh"}, + {"id": "store_io_error_not_fallback", "expected": "no silent fallback", "observed": "no silent fallback", "result": "pass", "source": "crash-qualify.sh"}, + {"id": "w_x_never_simultaneous", "expected": "never", "observed": "never", "result": "pass", "source": "crash-qualify.sh"} + ] +} +``` + +Import with `--gate store-v1-crash --tier QEMU` (or the tier the lane +declares), with `--dep` on the ADR 0015 acceptance receipt once it exists. + +The checked-in `P3_STORE_QEMU` manifest consumes separate Store format, +crash-consistency, and QEMU block-device receipts. Crash consistency must link +to the exact format qualification receipt. The block-device receipt must link +to both the exact format and crash-consistency receipts. Required structured +assertions are `store_previous_or_new_only`, `store_graph_valid`, +`store_nospace_zero_writes`, and `store_io_error_not_fallback`. This adapter +records observations; it does not define Store v1 semantics. + +`P3_STORE_MACHINE1` additionally requires an exact bounded-region receipt, +exact-region provisioning authority, and an attended Machine 1 execution +receipt. The execution receipt must be `MACHINE1_MUTATING`, bind the existing +`machine-1` hold, depend on the target and provisioning receipts, and declare +and observe only `BOUNDED_TEST_REGION_WRITE`. A read-only Machine 1 receipt +cannot prove persistent writes. +Store v1 format tests, mount validation, and the QEMU block-device suite +follow the same shape with their own `--gate` kinds. Muse never defines +Store v1 wire or recovery behavior; the Store lane emits structured +observations and Muse verifies, chains, and evaluates them. + +### 4.4 Admission Receipts (owner: SEED-0B admission lane) + +Claude's Admission Receipt v0 stays where it is. It is the +subsystem-specific proof of artifact verification, admission, and execution. +It is not moved into `aien-proof`. An EvidenceReceipt references or digests +it without conflating the two layers: + +- pass the admission receipt digest as an `--artifact` input digest, and/or +- record its location or identifier in `--external-ref`. + +The EvidenceReceipt then proves the qualification procedure ran and its +required assertions and dependencies hold; the Admission Receipt proves what +the admission subsystem checked. Either layer can fail independently. + +### 4.5 Provenance tags for characterization evidence + +Characterization observations (for example GB10 topology facts) must carry +their provenance in the assertion `source` field using this vocabulary: + +- `linux-observed` +- `uefi-observed` +- `native-aienos-observed` +- `qemu-synthetic` +- `derived` +- `unknown` + +EXAMPLE source value: `gb10-topology:linux-observed`. Gate manifests pin the +required origin per assertion with `assertion_sources`, so Linux-observed +topology can never satisfy a native-AIENOS hardware-ownership claim and a +pure state-machine mock can never prove firmware variable behavior. When a +manifest is silent about origin, any recorded source is accepted, but the +source string is still part of the canonical receipt identity. + +## 5. Verification commands (read only) + +```sh +aien-proof receipt verify +aien-proof verify-chain +aien-proof gate status SEED-0B +aien-proof gate explain P3_DEVELOPMENT_QEMU_ENTRY +aien-proof gate explain P3_MACHINE1_WRITE_ENTRY +aien-proof gate explain STORE_V1_FORMAT_PR_MERGE +``` + +`gate explain` reports each checked-in manifest prerequisite. Missing ordinary +proof is `INCOMPLETE`. A known procedural blocker can declare `BLOCKED` and +name it explicitly. Example current physical state: + +```text +P3_DEVELOPMENT_QEMU_ENTRY: INCOMPLETE +INCOMPLETE M0_NATIVE_ROLLBACK_QEMU ... +INCOMPLETE SEED0B_QEMU ... +INCOMPLETE ADR0015 ... +INCOMPLETE STRICT_MAIN ... + +P3_MACHINE1_WRITE_ENTRY: BLOCKED +BLOCKED P3_DEVELOPMENT_QEMU_ENTRY ... +BLOCKED OWNER_SECURE_BOOT_TRUST_CHAIN MISSING: HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN +BLOCKED M0_NATIVE_ROLLBACK_MACHINE1 MISSING: HARDWARE_QUALIFICATION_BLOCKED_BY_TRUST_CHAIN +INCOMPLETE BOUNDED_MACHINE1_STORE_REGION ... +``` + +`STORE_V1_FORMAT_PR_MERGE` is intentionally narrower. It requires ADR 0015, +pure Store v1 format/golden-vector assertions, and strict main. It can pass +without full SEED-0B completion. It does not authorize P3 QEMU qualification +or any Machine 1 mutation. `P3_DEVELOPMENT_QEMU_ENTRY` requires all four of +M0_NATIVE_ROLLBACK_QEMU, SEED0B_QEMU, ADR 0015, and strict main to pass. + +The tier ordering is explicit: `TEST_ONLY_TRUST`, `HOST_TEST`, `QEMU`, +`QEMU_SECURITY`, `MACHINE1_READ_ONLY`, `MACHINE1_ATTENDED`, +`MACHINE1_MUTATING`, `PRODUCTION`. Test-only trust satisfies only itself. +Physical requirements reject all QEMU tiers. The read-only Machine 1 tier +cannot satisfy attended mutation requirements, and `PRODUCTION` cannot rely on +test-only trust ancestry. + +Materialize the checked in example manifests with: + +```sh +aien-proof gate examples --out /gates +``` + +## 6. What the evidence lane will not do + +- Change store, boot, artifact, admission, Secure Boot, TPM, trust root, + native boot, or SEED-0B execution behavior. +- Infer completion from issue status or prose. If your run lacks a required + input, the receipt schema or verification reports the gap instead. +- Upgrade failing runs, satisfy physical requirements with QEMU receipts, + or close gates on BLOCKED runs. +- Move Claude's Admission Receipt format into `aien-proof`. An Admission + Receipt proves artifact admission/execution inside its subsystem. An + EvidenceReceipt proves a cross-repository qualification run and may bind an + Admission Receipt by digest/reference.