aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#128 (code only)
Apply it
git checkout -b patch-24786deb23a049f4 a71969abaeae16dd0556178dad48e354999264f5 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/24786deb23a049f4.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
128
1f86c80129b12b7715d1a8fdde11b248e1cc4d9e
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":128,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/128","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:03Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aien-proof/gates/P3_STORE_QEMU.json b/crates/aien-proof/gates/P3_STORE_QEMU.json index 3be72d5f..5d6f572b 100644 --- a/crates/aien-proof/gates/P3_STORE_QEMU.json +++ b/crates/aien-proof/gates/P3_STORE_QEMU.json @@ -4,7 +4,7 @@ "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"} + {"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","store-v1-format","store-v1-host"],"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","store-v1-format","store-v1-qemu"],"mutation":"NONE","require_clean":true,"missing_as":"INCOMPLETE"} ] } diff --git a/crates/aien-proof/gates/STORE_V1_FORMAT.json b/crates/aien-proof/gates/STORE_V1_FORMAT.json new file mode 100644 index 00000000..5e04f7d5 --- /dev/null +++ b/crates/aien-proof/gates/STORE_V1_FORMAT.json @@ -0,0 +1,7 @@ +{ + "gate": "STORE_V1_FORMAT", + "description": "Store v1 on-disk format qualification on host tests. Defines the format receipt requirement only; the gate stays INCOMPLETE until a real receipt arrives.", + "requires": [ + {"name":"Store v1 format","kind":"store-v1-format","min_tier":"HOST_TEST","assertions":["store_format_valid","store_object_ids_valid","store_catalog_valid","store_commit_valid","store_full_graph_valid"],"require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/gates/STORE_V1_HOST.json b/crates/aien-proof/gates/STORE_V1_HOST.json new file mode 100644 index 00000000..d638688c --- /dev/null +++ b/crates/aien-proof/gates/STORE_V1_HOST.json @@ -0,0 +1,7 @@ +{ + "gate": "STORE_V1_HOST", + "description": "Store v1 host behavior suite. The host suite must chain to a verified format receipt. Defines the requirement only; stays INCOMPLETE until real receipts arrive.", + "requires": [ + {"name":"Store v1 host suite","kind":"store-v1-host","min_tier":"HOST_TEST","assertions":["store_previous_or_new_only","store_conflict_fail_closed","store_inconsistent_history_fail_closed","store_io_error_not_fallback","store_nospace_zero_writes","store_open_side_effect_free"],"dependency_kinds":["store-v1-format"],"require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/gates/STORE_V1_QEMU.json b/crates/aien-proof/gates/STORE_V1_QEMU.json new file mode 100644 index 00000000..6be843b1 --- /dev/null +++ b/crates/aien-proof/gates/STORE_V1_QEMU.json @@ -0,0 +1,7 @@ +{ + "gate": "STORE_V1_QEMU", + "description": "Store v1 QEMU persistence suite with reboot recovery. Must chain to a verified format receipt. Defines the requirement only; stays INCOMPLETE until real receipts arrive.", + "requires": [ + {"name":"Store v1 QEMU suite","kind":"store-v1-qemu","min_tier":"QEMU","assertions":["store_previous_or_new_only","store_full_graph_valid","store_qemu_reboot_recovered"],"dependency_kinds":["store-v1-format"],"require_clean":true,"missing_as":"INCOMPLETE"} + ] +} diff --git a/crates/aien-proof/src/gate.rs b/crates/aien-proof/src/gate.rs index 0e6e2825..f4156074 100644 --- a/crates/aien-proof/src/gate.rs +++ b/crates/aien-proof/src/gate.rs @@ -615,6 +615,9 @@ 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"); +pub const STORE_V1_FORMAT: &str = include_str!("../gates/STORE_V1_FORMAT.json"); +pub const STORE_V1_HOST: &str = include_str!("../gates/STORE_V1_HOST.json"); +pub const STORE_V1_QEMU: &str = include_str!("../gates/STORE_V1_QEMU.json"); fn embedded_manifest(gate: &str) -> Option<&'static str> { match gate { @@ -625,6 +628,9 @@ fn embedded_manifest(gate: &str) -> Option<&'static str> { "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), + "STORE_V1_FORMAT" => Some(STORE_V1_FORMAT), + "STORE_V1_HOST" => Some(STORE_V1_HOST), + "STORE_V1_QEMU" => Some(STORE_V1_QEMU), _ => None, } } @@ -641,6 +647,9 @@ pub fn write_examples(dir: &Path) -> Result<Vec<std::path::PathBuf>, String> { ("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), + ("STORE_V1_FORMAT.json", STORE_V1_FORMAT), + ("STORE_V1_HOST.json", STORE_V1_HOST), + ("STORE_V1_QEMU.json", STORE_V1_QEMU), ] { // Validate the shipped shape before writing. let manifest: Gate = @@ -1416,5 +1425,14 @@ mod tests { 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"); + let store_format: Gate = serde_json::from_str(STORE_V1_FORMAT).unwrap(); + assert_eq!(store_format.gate, "STORE_V1_FORMAT"); + store_format.validate().unwrap(); + let store_host: Gate = serde_json::from_str(STORE_V1_HOST).unwrap(); + assert_eq!(store_host.gate, "STORE_V1_HOST"); + store_host.validate().unwrap(); + let store_qemu: Gate = serde_json::from_str(STORE_V1_QEMU).unwrap(); + assert_eq!(store_qemu.gate, "STORE_V1_QEMU"); + store_qemu.validate().unwrap(); } } diff --git a/crates/aien-proof/src/import.rs b/crates/aien-proof/src/import.rs index 416c9639..5e20f6f3 100644 --- a/crates/aien-proof/src/import.rs +++ b/crates/aien-proof/src/import.rs @@ -144,6 +144,119 @@ pub fn read_assertion_file(path: &Path) -> Result<(Vec<Assertion>, Verdict), Str } } +// Canonical store assertion IDs live in store_assert.rs; this table only +// groups them per qualification kind. +use crate::store_assert::*; +fn store_required_assertions(kind: &str) -> Option<&'static [&'static str]> { + match kind { + "store-v1-format" => Some(&[ + STORE_FORMAT_VALID, + STORE_OBJECT_IDS_VALID, + STORE_CATALOG_VALID, + STORE_COMMIT_VALID, + STORE_FULL_GRAPH_VALID, + ]), + "store-v1-host" => Some(&[ + STORE_PREVIOUS_OR_NEW_ONLY, + STORE_CONFLICT_FAIL_CLOSED, + STORE_INCONSISTENT_HISTORY_FAIL_CLOSED, + STORE_IO_ERROR_NOT_FALLBACK, + STORE_NOSPACE_ZERO_WRITES, + STORE_OPEN_SIDE_EFFECT_FREE, + ]), + "store-v1-qemu" => Some(&[ + STORE_PREVIOUS_OR_NEW_ONLY, + STORE_FULL_GRAPH_VALID, + STORE_QEMU_REBOOT_RECOVERED, + ]), + _ => None, + } +} + +/// Store qualification profile for kinds starting with "store-". +/// Checks source identity, tier allow list, artifact and assertion +/// presence, assertion origin, PASS consistency, mutation allow list, +/// and the per-kind required assertion set. Output digest presence for +/// PASS stays enforced by `build_receipt`. +pub fn validate_store_profile( + req: &ImportRequest, + assertions: &[Assertion], + result: Verdict, +) -> Result<(), String> { + if req.repo.trim().is_empty() { + return Err("store qualification requires non-empty repo".to_string()); + } + check_commit(&req.commit)?; + if req.procedure.trim().is_empty() { + return Err("store qualification requires non-empty procedure".to_string()); + } + if req.procedure.trim() == "TBD" { + return Err("store qualification requires a named procedure, got \"TBD\"".to_string()); + } + let tier = Tier::parse(&req.tier).ok_or_else(|| { + format!( + "store qualification kind {:?} has unknown tier {:?}", + req.kind, req.tier + ) + })?; + match tier { + Tier::HostTest | Tier::Qemu | Tier::QemuSecurity => {} + _ => { + return Err(format!( + "store qualification kind {:?} refuses tier {:?}", + req.kind, + tier.as_str() + )); + } + } + if req.input_artifacts.is_empty() { + return Err("store qualification requires at least one input artifact digest".to_string()); + } + if assertions.is_empty() { + return Err("store qualification requires at least one assertion".to_string()); + } + for a in assertions { + if a.source.trim().is_empty() { + return Err(format!( + "store qualification requires assertion source for {:?}", + a.id + )); + } + } + if result == Verdict::Pass && assertions.iter().any(|a| !a.pass) { + return Err("store qualification claims PASS but an assertion failed".to_string()); + } + let declared = match &req.declared_mutation { + Some(s) => Mutation::parse(s).ok_or_else(|| format!("unknown mutation class {s:?}"))?, + None => Mutation::None, + }; + match declared { + Mutation::None + | Mutation::VolatileOnly + | Mutation::RemovableMediaOnly + | Mutation::BoundedTestRegionWrite => {} + _ => { + return Err(format!( + "store qualification kind {:?} refuses declared mutation {:?}", + req.kind, + declared.as_str() + )); + } + } + if let Some(required) = store_required_assertions(req.kind.as_str()) { + for id in required { + let ok = assertions.iter().any(|a| a.id == *id && a.pass); + if !ok { + return Err(format!( + "store qualification kind {:?} missing required passing assertion {:?}", + req.kind, id + )); + } + } + } + Ok(()) +} + /// 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). @@ -152,6 +265,9 @@ pub fn build_receipt( assertions: Vec<Assertion>, result: Verdict, ) -> Result<Receipt, String> { + if req.kind.starts_with("store-") { + validate_store_profile(req, &assertions, result)?; + } let tier = Tier::parse(&req.tier) .ok_or_else(|| format!("unknown qualification tier {:?}", req.tier))?; check_commit(&req.commit)?; @@ -378,4 +494,110 @@ mod tests { assert!(build_receipt(&r, assertions, result).is_err()); let _ = dir; } + + fn store_req(kind: &str, tier: &str) -> ImportRequest { + let mut r = req(); + r.kind = kind.to_string(); + r.tier = tier.to_string(); + r.procedure = "scripts/store_test.sh".to_string(); + r.machine = "store-test-runner".to_string(); + r + } + + fn store_assertion(id: &str) -> Assertion { + Assertion { + id: id.to_string(), + expected: String::new(), + observed: String::new(), + pass: true, + source: "store run log".to_string(), + note: String::new(), + } + } + + fn format_assertions() -> Vec<Assertion> { + vec![ + store_assertion("store_format_valid"), + store_assertion("store_object_ids_valid"), + store_assertion("store_catalog_valid"), + store_assertion("store_commit_valid"), + store_assertion("store_full_graph_valid"), + ] + } + + fn host_assertions() -> Vec<Assertion> { + vec![ + store_assertion("store_previous_or_new_only"), + store_assertion("store_conflict_fail_closed"), + store_assertion("store_inconsistent_history_fail_closed"), + store_assertion("store_io_error_not_fallback"), + store_assertion("store_nospace_zero_writes"), + store_assertion("store_open_side_effect_free"), + ] + } + + #[test] + fn store_format_valid_passes_profile() { + let r = store_req("store-v1-format", "HOST_TEST"); + let assertions = format_assertions(); + validate_store_profile(&r, &assertions, Verdict::Pass).unwrap(); + let receipt = build_receipt(&r, assertions, Verdict::Pass).unwrap(); + assert_eq!(receipt.kind, "store-v1-format"); + assert_eq!(receipt.tier, Tier::HostTest); + } + + #[test] + fn store_format_missing_required_refused() { + let r = store_req("store-v1-format", "HOST_TEST"); + let mut assertions = format_assertions(); + assertions.retain(|a| a.id != "store_commit_valid"); + let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err(); + assert!(err.contains("store_commit_valid"), "got: {err}"); + assert!(err.contains("store-v1-format"), "got: {err}"); + assert!(build_receipt(&r, assertions, Verdict::Pass).is_err()); + } + + #[test] + fn store_empty_source_refused() { + let r = store_req("store-v1-format", "QEMU"); + let mut assertions = format_assertions(); + assertions[0].source.clear(); + let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err(); + assert!(err.contains("source"), "got: {err}"); + assert!(err.contains("store_format_valid"), "got: {err}"); + assert!(build_receipt(&r, assertions, Verdict::Pass).is_err()); + } + + #[test] + fn store_host_machine1_tier_refused() { + let r = store_req("store-v1-host", "MACHINE1_ATTENDED"); + let assertions = host_assertions(); + let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err(); + assert!(err.contains("MACHINE1_ATTENDED"), "got: {err}"); + assert!(build_receipt(&r, assertions, Verdict::Pass).is_err()); + } + + #[test] + fn store_destructive_mutation_refused() { + let mut r = store_req("store-v1-format", "QEMU"); + r.declared_mutation = Some("DESTRUCTIVE_STORAGE".to_string()); + let assertions = format_assertions(); + let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err(); + assert!(err.contains("DESTRUCTIVE_STORAGE"), "got: {err}"); + assert!(build_receipt(&r, assertions, Verdict::Pass).is_err()); + } + + #[test] + fn store_future_unknown_subkind_has_no_required_set() { + assert!(store_required_assertions("store-v1-future").is_none()); + let r = store_req("store-v1-future", "QEMU"); + let assertions = vec![store_assertion("store_future_check")]; + validate_store_profile(&r, &assertions, Verdict::Pass).unwrap(); + let receipt = build_receipt(&r, assertions, Verdict::Pass).unwrap(); + assert_eq!(receipt.kind, "store-v1-future"); + let mut bad = store_req("store-v1-future", "QEMU"); + bad.procedure = "TBD".to_string(); + let assertions = vec![store_assertion("store_future_check")]; + assert!(build_receipt(&bad, assertions, Verdict::Pass).is_err()); + } } diff --git a/crates/aien-proof/src/lib.rs b/crates/aien-proof/src/lib.rs index 6eb8b992..c42ba276 100644 --- a/crates/aien-proof/src/lib.rs +++ b/crates/aien-proof/src/lib.rs @@ -19,6 +19,7 @@ pub mod lease; pub mod ledger; pub mod ledger_bind; pub mod lock; +pub mod store_assert; pub mod workspace; #[cfg(test)] diff --git a/crates/aien-proof/src/store_assert.rs b/crates/aien-proof/src/store_assert.rs new file mode 100644 index 00000000..6c614e85 --- /dev/null +++ b/crates/aien-proof/src/store_assert.rs @@ -0,0 +1,81 @@ +//! Stable Store qualification assertion IDs for evidence receipts. +//! +//! This module records the test that happened; it never defines Store +//! wire format rules. Each constant is the stable `Assertion.id` value +//! written into an `EvidenceReceiptV1`. + +/// Records that the observed store layout parsed as the expected format. +pub const STORE_FORMAT_VALID: &str = "store_format_valid"; +/// Records that observed object identifiers matched the expected shape. +pub const STORE_OBJECT_IDS_VALID: &str = "store_object_ids_valid"; +/// Records that the observed catalog listing matched the expected entries. +pub const STORE_CATALOG_VALID: &str = "store_catalog_valid"; +/// Records that the observed commit reference matched the expected value. +pub const STORE_COMMIT_VALID: &str = "store_commit_valid"; +/// Records that the observed full history graph traversal matched the expected result. +pub const STORE_FULL_GRAPH_VALID: &str = "store_full_graph_valid"; +/// Records that a conflicting write attempt was rejected without mutating state. +pub const STORE_CONFLICT_FAIL_CLOSED: &str = "store_conflict_fail_closed"; +/// Records that an inconsistent history input was rejected without mutating state. +pub const STORE_INCONSISTENT_HISTORY_FAIL_CLOSED: &str = "store_inconsistent_history_fail_closed"; +/// Records that an I/O error was reported instead of silent fallback content. +pub const STORE_IO_ERROR_NOT_FALLBACK: &str = "store_io_error_not_fallback"; +/// Records that a no-space condition left zero partial writes visible. +pub const STORE_NOSPACE_ZERO_WRITES: &str = "store_nospace_zero_writes"; +/// Records that after a write attempt only the previous or the new content was visible. +pub const STORE_PREVIOUS_OR_NEW_ONLY: &str = "store_previous_or_new_only"; +/// Records that opening the store produced no observable side effects. +pub const STORE_OPEN_SIDE_EFFECT_FREE: &str = "store_open_side_effect_free"; +/// Records that the store state observed after a QEMU reboot matched the expected committed state. +pub const STORE_QEMU_REBOOT_RECOVERED: &str = "store_qemu_reboot_recovered"; + +/// All 12 stable Store assertion IDs in canonical order. +pub fn store_assertion_ids() -> &'static [&'static str] { + &[ + STORE_FORMAT_VALID, + STORE_OBJECT_IDS_VALID, + STORE_CATALOG_VALID, + STORE_COMMIT_VALID, + STORE_FULL_GRAPH_VALID, + STORE_CONFLICT_FAIL_CLOSED, + STORE_INCONSISTENT_HISTORY_FAIL_CLOSED, + STORE_IO_ERROR_NOT_FALLBACK, + STORE_NOSPACE_ZERO_WRITES, + STORE_PREVIOUS_OR_NEW_ONLY, + STORE_OPEN_SIDE_EFFECT_FREE, + STORE_QEMU_REBOOT_RECOVERED, + ] +} + +/// Returns true when `id` is one of the 12 stable Store assertion IDs. +pub fn is_store_assertion(id: &str) -> bool { + store_assertion_ids().contains(&id) +} + +#[cfg(test)] +mod tests { + use super::*; + use std::collections::BTreeSet; + + #[test] + fn ids_are_non_empty_unique_and_stable() { + let ids = store_assertion_ids(); + assert_eq!(ids.len(), 12); + let mut seen = BTreeSet::new(); + for id in ids { + assert!(!id.is_empty(), "store assertion id must not be empty"); + assert!(seen.insert(*id), "duplicate store assertion id {id:?}"); + assert!( + is_store_assertion(id), + "is_store_assertion must accept {id:?}" + ); + } + assert_eq!(seen.len(), 12); + } + + #[test] + fn rejects_non_store_ids() { + assert!(!is_store_assertion("artifact_signature_valid")); + assert!(!is_store_assertion("")); + } +} diff --git a/crates/aien-proof/tests/store_qualification_adversarial.rs b/crates/aien-proof/tests/store_qualification_adversarial.rs new file mode 100644 index 00000000..c527fb8a --- /dev/null +++ b/crates/aien-proof/tests/store_qualification_adversarial.rs @@ -0,0 +1,332 @@ +use aien_proof::chain::verify_chain; +use aien_proof::evidence::{ + receipt_id, store_receipt, verify_bytes, verify_with_store, Assertion, LedgerRef, Mutation, + Receipt, Tier, Verdict, SCHEMA, SCHEMA_VERSION, +}; +use aien_proof::gate::{evaluate, AssertionSource, Gate, MissingAs, Requirement}; +use aien_proof::ledger; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +static N: AtomicUsize = AtomicUsize::new(0); + +fn temp_store(tag: &str) -> PathBuf { + loop { + let n = N.fetch_add(1, Ordering::SeqCst); + let dir = + std::env::temp_dir().join(format!("aien-proof-adv-{tag}-{}-{n}", std::process::id())); + match std::fs::create_dir(&dir) { + Ok(()) => return dir, + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("cannot create temp store: {e}"), + } + } +} + +fn pass_assertion(id: &str, source: &str) -> Assertion { + Assertion { + id: id.to_string(), + expected: "yes".to_string(), + observed: "yes".to_string(), + pass: true, + source: source.to_string(), + note: String::new(), + } +} + +fn sample_receipt() -> Receipt { + Receipt { + schema: SCHEMA.to_string(), + version: SCHEMA_VERSION, + id: String::new(), + kind: "store-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/store_qualify.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![pass_assertion("store_previous_or_new_only", "store-tests")], + 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(), + } +} + +fn sealed(mut r: Receipt) -> Receipt { + let id = receipt_id(&r).expect("sample receipt must seal"); + r.id = id; + r +} + +fn put(store: &Path, r: &Receipt) -> String { + store_receipt(store, r).expect("store_receipt must accept sealed receipt") +} + +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 gate(name: &str, requires: Vec<Requirement>) -> Gate { + Gate { + gate: name.to_string(), + description: String::new(), + requires, + } +} + +fn stored_path(store: &Path, id: &str) -> PathBuf { + store.join("receipts").join(format!("{id}.json")) +} + +#[test] +fn host_receipt_substituted_for_qemu_is_blocked() { + let store = temp_store("host-for-qemu"); + let mut r = sample_receipt(); + r.tier = Tier::HostTest; + r.env_class = "HOST_TEST".to_string(); + put(&store, &sealed(r)); + let manifest = gate( + "STORE-ADV", + vec![req( + "Store QEMU", + "store-qemu", + Tier::Qemu, + vec!["store_previous_or_new_only"], + MissingAs::Blocked, + )], + ); + let report = evaluate(&manifest, &store); + assert_ne!(report.status, Verdict::Pass); + let line = &report.lines[0]; + assert_eq!(line.status, Verdict::Blocked); + assert!( + line.detail.contains("cannot satisfy"), + "unexpected detail: {}", + line.detail + ); +} + +#[test] +fn different_commit_substituted_fails_identity() { + let r = sealed(sample_receipt()); + let mut value = serde_json::to_value(&r).expect("receipt serializes"); + value["commit"] = serde_json::Value::String("b".repeat(40)); + let bytes = serde_json::to_vec(&value).expect("forged bytes serialize"); + let err = verify_bytes(&bytes).expect_err("tampered commit must not verify"); + assert!(err.contains("id mismatch"), "unexpected error: {err}"); +} + +#[test] +fn dirty_source_substituted_is_blocked() { + let store = temp_store("dirty"); + let mut r = sample_receipt(); + r.dirty = true; + put(&store, &sealed(r)); + let mut requirement = req( + "Store QEMU", + "store-qemu", + Tier::Qemu, + vec!["store_previous_or_new_only"], + MissingAs::Blocked, + ); + requirement.require_clean = true; + let report = evaluate(&gate("STORE-ADV", vec![requirement]), &store); + assert_ne!(report.status, Verdict::Pass); + let line = &report.lines[0]; + assert_eq!(line.status, Verdict::Blocked); + assert!( + line.detail.to_ascii_lowercase().contains("clean"), + "unexpected detail: {}", + line.detail + ); +} + +#[test] +fn assertion_from_wrong_source_fails() { + let store = temp_store("wrong-source"); + let mut r = sample_receipt(); + r.assertions = vec![pass_assertion( + "store_previous_or_new_only", + "state-machine-mock", + )]; + put(&store, &sealed(r)); + let mut requirement = req( + "Store QEMU", + "store-qemu", + Tier::Qemu, + vec!["store_previous_or_new_only"], + MissingAs::Incomplete, + ); + requirement.assertion_sources = vec![AssertionSource { + id: "store_previous_or_new_only".to_string(), + source: "aavmf_variables".to_string(), + }]; + let report = evaluate(&gate("STORE-ADV", vec![requirement]), &store); + assert_ne!(report.status, Verdict::Pass); + let line = &report.lines[0]; + assert_eq!(line.status, Verdict::Fail); + assert!( + line.detail.contains("source"), + "unexpected detail: {}", + line.detail + ); +} + +#[test] +fn incomplete_crash_matrix_does_not_pass() { + let store = temp_store("crash-matrix"); + let mut r = sample_receipt(); + r.assertions = vec![pass_assertion("store_previous_or_new_only", "store-tests")]; + put(&store, &sealed(r)); + let manifest = gate( + "STORE-ADV", + vec![req( + "Store QEMU", + "store-qemu", + Tier::Qemu, + vec![ + "store_previous_or_new_only", + "store_conflict_fail_closed", + "store_nospace_zero_writes", + ], + MissingAs::Incomplete, + )], + ); + let report = evaluate(&manifest, &store); + assert_ne!(report.status, Verdict::Pass); + assert_ne!(report.lines[0].status, Verdict::Pass); +} + +#[test] +fn missing_dependency_yields_incomplete_chain() { + let store = temp_store("missing-dep"); + let mut r = sample_receipt(); + r.dependencies = vec!["f".repeat(64)]; + let sealed_r = sealed(r); + let id = put(&store, &sealed_r); + let report = verify_chain(&stored_path(&store, &id), &store).expect("chain verifies"); + assert_ne!(report.status, Verdict::Pass); + assert_eq!(report.status, Verdict::Incomplete); +} + +#[test] +fn altered_output_digest_against_ledger_ref_fails() { + let store = temp_store("digest-ledger"); + let event = ledger::append( + &store, + "tester", + "store-qemu", + "pass exit=0", + b"real-output", + ) + .expect("ledger append works"); + let mut r = sample_receipt(); + r.output_digest = "d".repeat(64); + r.ledger = Some(LedgerRef { + index: event.index, + hash: ledger::hex(&event.hash), + }); + let sealed_r = sealed(r); + let bytes = serde_json::to_vec(&sealed_r).expect("receipt serializes"); + let (_, report) = verify_with_store(&bytes, &store).expect("verify runs"); + assert_eq!(report.status, Verdict::Fail); + let joined = report.reasons.join("; ").to_ascii_lowercase(); + assert!( + joined.contains("digest") || joined.contains("payload") || joined.contains("ledger"), + "unexpected reasons: {}", + report.reasons.join("; ") + ); +} + +#[test] +fn machine1_claim_without_hold_is_incomplete() { + let mut r = sample_receipt(); + r.tier = Tier::Machine1Attended; + r.env_class = "MACHINE1_ATTENDED".to_string(); + r.machine = "machine-1".to_string(); + let sealed_r = sealed(r); + let bytes = serde_json::to_vec(&sealed_r).expect("receipt serializes"); + let (_, report) = verify_bytes(&bytes).expect("verify runs"); + assert_eq!(report.status, Verdict::Incomplete); +} + +#[test] +fn mutating_claim_with_wrong_mutation_class_fails() { + let store = temp_store("mutation"); + put(&store, &sealed(sample_receipt())); + 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("STORE-ADV", vec![requirement]), &store); + assert_ne!(report.status, Verdict::Pass); + let line = &report.lines[0]; + assert_eq!(line.status, Verdict::Fail); + assert!( + line.detail.to_ascii_lowercase().contains("mutation"), + "unexpected detail: {}", + line.detail + ); +} + +#[test] +fn blocked_receipt_used_as_pass_prerequisite_is_blocked() { + let store = temp_store("blocked-prereq"); + let mut r = sample_receipt(); + r.result = Verdict::Blocked; + put(&store, &sealed(r)); + let manifest = gate( + "STORE-ADV", + vec![req( + "Store QEMU", + "store-qemu", + Tier::Qemu, + vec!["store_previous_or_new_only"], + MissingAs::Blocked, + )], + ); + let report = evaluate(&manifest, &store); + assert_ne!(report.status, Verdict::Pass); + assert_eq!(report.lines[0].status, Verdict::Blocked); +}