interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

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

1250 lines · 42883 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Canonical evidence receipts (EvidenceReceiptV1).
17//!
18//! A receipt is a structured proof object: exact source, exact artifacts,
19//! exact machine, structured assertions, and links to earlier receipts, to
20//! Crumb ledger events, and to the resource lease that protected the run.
21//!
22//! Identity rule: the receipt ID is the BLAKE3 hash of an explicit canonical
23//! byte encoding defined in [`canonical_bytes`]. The human readable JSON
24//! rendering is not canonical. Map ordering, local paths, string timestamp
25//! formats, and Rust struct layout never affect the ID, because the canonical
26//! form uses fixed field order, length prefixed strings, and big endian
27//! integers throughout.
28
29use serde::{Deserialize, Serialize};
30use std::collections::BTreeSet;
31use std::fs;
32use std::path::Path;
33
34pub const SCHEMA: &str = "EvidenceReceiptV1";
35pub const SCHEMA_VERSION: u32 = 1;
36/// Domain separator for the canonical encoding.
37pub const DOMAIN: &[u8] = b"AIEN_EVIDENCE_RECEIPT_V1";
38/// Features a receipt may require. Verification rejects anything else.
39const KNOWN_FEATURES: &[&str] = &["v1-base"];
40/// Subdirectory of the proof board root holding receipts.
41pub const RECEIPT_DIR: &str = "receipts";
42
43/// Final result of a receipt. Missing data never collapses into `Pass`.
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[serde(rename_all = "UPPERCASE")]
46pub enum Verdict {
47 Pass,
48 Fail,
49 Blocked,
50 Incomplete,
51 Skipped,
52}
53
54impl Verdict {
55 pub fn parse(s: &str) -> Option<Self> {
56 match s.to_ascii_uppercase().as_str() {
57 "PASS" => Some(Verdict::Pass),
58 "FAIL" => Some(Verdict::Fail),
59 "BLOCKED" => Some(Verdict::Blocked),
60 "INCOMPLETE" => Some(Verdict::Incomplete),
61 "SKIPPED" => Some(Verdict::Skipped),
62 _ => None,
63 }
64 }
65
66 pub fn as_str(self) -> &'static str {
67 match self {
68 Verdict::Pass => "PASS",
69 Verdict::Fail => "FAIL",
70 Verdict::Blocked => "BLOCKED",
71 Verdict::Incomplete => "INCOMPLETE",
72 Verdict::Skipped => "SKIPPED",
73 }
74 }
75
76 fn code(self) -> u8 {
77 match self {
78 Verdict::Pass => 0,
79 Verdict::Fail => 1,
80 Verdict::Blocked => 2,
81 Verdict::Incomplete => 3,
82 Verdict::Skipped => 4,
83 }
84 }
85
86 fn from_code(b: u8) -> Option<Self> {
87 match b {
88 0 => Some(Verdict::Pass),
89 1 => Some(Verdict::Fail),
90 2 => Some(Verdict::Blocked),
91 3 => Some(Verdict::Incomplete),
92 4 => Some(Verdict::Skipped),
93 _ => None,
94 }
95 }
96}
97
98/// Qualification tier. A QEMU proof is never physical qualification.
99#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
100pub enum Tier {
101 #[serde(rename = "TEST_ONLY_TRUST")]
102 TestOnlyTrust,
103 #[serde(rename = "HOST_TEST")]
104 HostTest,
105 #[serde(rename = "QEMU")]
106 Qemu,
107 #[serde(rename = "QEMU_SECURITY")]
108 QemuSecurity,
109 #[serde(rename = "MACHINE1_READ_ONLY")]
110 Machine1ReadOnly,
111 #[serde(rename = "MACHINE1_ATTENDED")]
112 Machine1Attended,
113 #[serde(rename = "MACHINE1_MUTATING")]
114 Machine1Mutating,
115 #[serde(rename = "PRODUCTION")]
116 Production,
117}
118
119impl Tier {
120 pub fn parse(s: &str) -> Option<Self> {
121 match s {
122 "TEST_ONLY_TRUST" => Some(Tier::TestOnlyTrust),
123 "HOST_TEST" => Some(Tier::HostTest),
124 "QEMU" => Some(Tier::Qemu),
125 "QEMU_SECURITY" => Some(Tier::QemuSecurity),
126 "MACHINE1_READ_ONLY" => Some(Tier::Machine1ReadOnly),
127 "MACHINE1_ATTENDED" => Some(Tier::Machine1Attended),
128 "MACHINE1_MUTATING" => Some(Tier::Machine1Mutating),
129 "PRODUCTION" => Some(Tier::Production),
130 _ => None,
131 }
132 }
133
134 pub fn as_str(self) -> &'static str {
135 match self {
136 Tier::TestOnlyTrust => "TEST_ONLY_TRUST",
137 Tier::HostTest => "HOST_TEST",
138 Tier::Qemu => "QEMU",
139 Tier::QemuSecurity => "QEMU_SECURITY",
140 Tier::Machine1ReadOnly => "MACHINE1_READ_ONLY",
141 Tier::Machine1Attended => "MACHINE1_ATTENDED",
142 Tier::Machine1Mutating => "MACHINE1_MUTATING",
143 Tier::Production => "PRODUCTION",
144 }
145 }
146
147 /// Rank used for minimum tier checks. Higher means stronger evidence.
148 pub fn rank(self) -> u8 {
149 match self {
150 Tier::TestOnlyTrust => 0,
151 Tier::HostTest => 1,
152 Tier::Qemu => 2,
153 Tier::QemuSecurity => 3,
154 Tier::Machine1ReadOnly => 4,
155 Tier::Machine1Attended => 5,
156 Tier::Machine1Mutating => 6,
157 Tier::Production => 7,
158 }
159 }
160
161 pub fn is_hardware(self) -> bool {
162 matches!(
163 self,
164 Tier::Machine1ReadOnly | Tier::Machine1Attended | Tier::Machine1Mutating
165 )
166 }
167
168 pub fn is_physical(self) -> bool {
169 self.is_hardware() || self == Tier::Production
170 }
171}
172
173/// Hardware mutation classification. Descriptive, not authorization.
174#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
175pub enum Mutation {
176 #[serde(rename = "NONE")]
177 None,
178 #[serde(rename = "VOLATILE_ONLY")]
179 VolatileOnly,
180 #[serde(rename = "REMOVABLE_MEDIA_ONLY")]
181 RemovableMediaOnly,
182 #[serde(rename = "ONE_TIME_BOOT_SELECTION")]
183 OneTimeBootSelection,
184 #[serde(rename = "BOUNDED_TEST_REGION_WRITE")]
185 BoundedTestRegionWrite,
186 #[serde(rename = "BOOT_CONFIGURATION_CHANGE")]
187 BootConfigurationChange,
188 #[serde(rename = "TRUST_ROOT_CHANGE")]
189 TrustRootChange,
190 #[serde(rename = "TPM_POLICY_CHANGE")]
191 TpmPolicyChange,
192 #[serde(rename = "DESTRUCTIVE_STORAGE")]
193 DestructiveStorage,
194}
195
196impl Mutation {
197 pub fn parse(s: &str) -> Option<Self> {
198 match s {
199 "NONE" => Some(Mutation::None),
200 "VOLATILE_ONLY" => Some(Mutation::VolatileOnly),
201 "REMOVABLE_MEDIA_ONLY" => Some(Mutation::RemovableMediaOnly),
202 "ONE_TIME_BOOT_SELECTION" => Some(Mutation::OneTimeBootSelection),
203 "BOUNDED_TEST_REGION_WRITE" => Some(Mutation::BoundedTestRegionWrite),
204 "BOOT_CONFIGURATION_CHANGE" => Some(Mutation::BootConfigurationChange),
205 "TRUST_ROOT_CHANGE" => Some(Mutation::TrustRootChange),
206 "TPM_POLICY_CHANGE" => Some(Mutation::TpmPolicyChange),
207 "DESTRUCTIVE_STORAGE" => Some(Mutation::DestructiveStorage),
208 _ => None,
209 }
210 }
211
212 pub fn as_str(self) -> &'static str {
213 match self {
214 Mutation::None => "NONE",
215 Mutation::VolatileOnly => "VOLATILE_ONLY",
216 Mutation::RemovableMediaOnly => "REMOVABLE_MEDIA_ONLY",
217 Mutation::OneTimeBootSelection => "ONE_TIME_BOOT_SELECTION",
218 Mutation::BoundedTestRegionWrite => "BOUNDED_TEST_REGION_WRITE",
219 Mutation::BootConfigurationChange => "BOOT_CONFIGURATION_CHANGE",
220 Mutation::TrustRootChange => "TRUST_ROOT_CHANGE",
221 Mutation::TpmPolicyChange => "TPM_POLICY_CHANGE",
222 Mutation::DestructiveStorage => "DESTRUCTIVE_STORAGE",
223 }
224 }
225
226 fn severity(self) -> u8 {
227 match self {
228 Mutation::None => 0,
229 Mutation::VolatileOnly => 1,
230 Mutation::RemovableMediaOnly => 2,
231 Mutation::OneTimeBootSelection => 3,
232 Mutation::BoundedTestRegionWrite => 4,
233 Mutation::BootConfigurationChange => 5,
234 Mutation::TrustRootChange => 6,
235 Mutation::TpmPolicyChange => 6,
236 Mutation::DestructiveStorage => 7,
237 }
238 }
239
240 fn code(self) -> u8 {
241 match self {
242 Mutation::None => 0,
243 Mutation::VolatileOnly => 1,
244 Mutation::RemovableMediaOnly => 2,
245 Mutation::OneTimeBootSelection => 3,
246 Mutation::BoundedTestRegionWrite => 4,
247 Mutation::BootConfigurationChange => 5,
248 Mutation::TrustRootChange => 6,
249 Mutation::TpmPolicyChange => 7,
250 Mutation::DestructiveStorage => 8,
251 }
252 }
253
254 fn from_code(b: u8) -> Option<Self> {
255 match b {
256 0 => Some(Mutation::None),
257 1 => Some(Mutation::VolatileOnly),
258 2 => Some(Mutation::RemovableMediaOnly),
259 3 => Some(Mutation::OneTimeBootSelection),
260 4 => Some(Mutation::BoundedTestRegionWrite),
261 5 => Some(Mutation::BootConfigurationChange),
262 6 => Some(Mutation::TrustRootChange),
263 7 => Some(Mutation::TpmPolicyChange),
264 8 => Some(Mutation::DestructiveStorage),
265 _ => None,
266 }
267 }
268}
269
270/// One structured assertion. Console lines may exist, but this record is the
271/// proof: stable ID, expected and observed values, outcome, and source.
272#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
273#[serde(deny_unknown_fields)]
274pub struct Assertion {
275 pub id: String,
276 #[serde(default)]
277 pub expected: String,
278 #[serde(default)]
279 pub observed: String,
280 pub pass: bool,
281 #[serde(default)]
282 pub source: String,
283 #[serde(default)]
284 pub note: String,
285}
286
287/// Reference to a Crumb ledger event recorded for the run.
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289#[serde(deny_unknown_fields)]
290pub struct LedgerRef {
291 pub index: u64,
292 /// Hex of the ledger event hash.
293 pub hash: String,
294}
295
296/// Binding to the exclusive resource lease that protected a hardware run.
297#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(deny_unknown_fields)]
299pub struct LeaseRef {
300 /// Hold ID (hex of the hold audit event hash).
301 pub hold_id: String,
302 /// Resource the lease covered, for example `machine-1`.
303 pub resource: String,
304}
305
306/// Canonical evidence receipt, version 1.
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
308#[serde(deny_unknown_fields)]
309pub struct Receipt {
310 pub schema: String,
311 pub version: u32,
312 /// BLAKE3 hex of the canonical encoding. Must recompute exactly.
313 pub id: String,
314 /// Free form procedure class, for example `seed-0b-qemu`.
315 pub kind: String,
316 pub tier: Tier,
317 pub result: Verdict,
318 /// Unix seconds. Metadata only; stored as an integer so no string
319 /// clock format can affect identity.
320 pub timestamp: u64,
321 pub repo: String,
322 /// Exact source commit, lowercase hex, 40 or 64 digits.
323 pub commit: String,
324 /// True when the source tree had uncommitted changes.
325 pub dirty: bool,
326 /// Compiler and flag identity, for example `rustc -vV` output.
327 pub toolchain: String,
328 /// Command or procedure identity, for example the joined command line.
329 pub procedure: String,
330 /// Machine or resource identity, for example `machine-1`.
331 pub machine: String,
332 /// Environment classification. Must equal the tier string, so a QEMU
333 /// run can never be labeled as physical qualification.
334 pub env_class: String,
335 pub input_artifacts: Vec<String>,
336 pub output_artifacts: Vec<String>,
337 pub assertions: Vec<Assertion>,
338 /// Immutable receipt IDs (hashes) this receipt depends on.
339 pub dependencies: Vec<String>,
340 pub declared_mutation: Mutation,
341 pub observed_mutation: Mutation,
342 #[serde(default)]
343 pub authority: String,
344 /// BLAKE3 hex of the complete captured output.
345 pub output_digest: String,
346 #[serde(default)]
347 pub external_refs: Vec<String>,
348 #[serde(default)]
349 pub ledger: Option<LedgerRef>,
350 #[serde(default)]
351 pub lease: Option<LeaseRef>,
352 /// Features the verifier must understand. Unknown entries fail closed.
353 #[serde(default)]
354 pub required_features: Vec<String>,
355 /// Must stay empty. Any content fails verification.
356 #[serde(default)]
357 pub reserved: String,
358}
359
360/// Verification outcome for one receipt or chain.
361#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct Report {
363 pub status: Verdict,
364 pub reasons: Vec<String>,
365}
366
367impl Report {
368 pub fn pass(reason: &str) -> Self {
369 Report {
370 status: Verdict::Pass,
371 reasons: vec![reason.to_string()],
372 }
373 }
374
375 pub fn fail(reasons: Vec<String>) -> Self {
376 Report {
377 status: Verdict::Fail,
378 reasons,
379 }
380 }
381
382 pub fn closed(status: Verdict, reasons: Vec<String>) -> Self {
383 Report { status, reasons }
384 }
385
386 pub fn ok(&self) -> bool {
387 self.status == Verdict::Pass
388 }
389}
390
391fn is_hex(s: &str) -> bool {
392 !s.is_empty() && s.bytes().all(|b| b.is_ascii_hexdigit())
393}
394
395fn is_lower_hex(s: &str) -> bool {
396 !s.is_empty()
397 && s.bytes()
398 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
399}
400
401fn hex_to_bytes(s: &str) -> Option<Vec<u8>> {
402 if !s.len().is_multiple_of(2) || !is_hex(s) {
403 return None;
404 }
405 let mut out = Vec::with_capacity(s.len() / 2);
406 let bytes = s.as_bytes();
407 let mut i = 0;
408 while i < bytes.len() {
409 let hi = char::from(bytes[i]).to_digit(16)?;
410 let lo = char::from(bytes[i + 1]).to_digit(16)?;
411 out.push(((hi << 4) | lo) as u8);
412 i += 2;
413 }
414 Some(out)
415}
416
417pub fn check_commit(commit: &str) -> Result<(), String> {
418 if (commit.len() == 40 || commit.len() == 64) && is_lower_hex(commit) {
419 Ok(())
420 } else {
421 Err(format!(
422 "commit must be 40 or 64 lowercase hex digits, got {commit:?}"
423 ))
424 }
425}
426
427fn check_digest_list(name: &str, items: &[String]) -> Result<(), String> {
428 for item in items {
429 if let Some((algo, hex)) = item.split_once(':') {
430 match algo {
431 "blake3" | "sha256" | "sha512" => {}
432 _ => return Err(format!("{name}: unknown digest algo in {item:?}")),
433 }
434 if hex.len() < 32 || hex.len() % 2 != 0 || !is_hex(hex) {
435 return Err(format!("{name}: bad digest hex in {item:?}"));
436 }
437 } else if item.len() == 64 && is_hex(item) {
438 // Bare 64 digit hex, read as BLAKE3.
439 } else {
440 return Err(format!(
441 "{name}: digest must be <algo>:<hex> or 64 hex digits, got {item:?}"
442 ));
443 }
444 }
445 Ok(())
446}
447
448fn push_str(out: &mut Vec<u8>, s: &str) {
449 out.extend_from_slice(&(s.len() as u64).to_be_bytes());
450 out.extend_from_slice(s.as_bytes());
451}
452
453fn push_u32(out: &mut Vec<u8>, v: u32) {
454 out.extend_from_slice(&v.to_be_bytes());
455}
456
457fn push_u64(out: &mut Vec<u8>, v: u64) {
458 out.extend_from_slice(&v.to_be_bytes());
459}
460
461fn sorted_unique(items: &[String]) -> Vec<String> {
462 let set: BTreeSet<&str> = items.iter().map(String::as_str).collect();
463 set.into_iter().map(str::to_string).collect()
464}
465
466/// Build the canonical byte encoding. Every format violation is an error,
467/// so malformed input fails closed before any hash is compared.
468pub fn canonical_bytes(r: &Receipt) -> Result<Vec<u8>, String> {
469 if r.schema != SCHEMA {
470 return Err(format!("unknown receipt schema {:?}", r.schema));
471 }
472 if r.version != SCHEMA_VERSION {
473 return Err(format!("unsupported receipt version {}", r.version));
474 }
475 for f in &r.required_features {
476 if !KNOWN_FEATURES.contains(&f.as_str()) {
477 return Err(format!("unknown required receipt feature {f:?}"));
478 }
479 }
480 if !r.reserved.is_empty() {
481 return Err("reserved field must be empty".to_string());
482 }
483 if r.kind.is_empty() {
484 return Err("receipt kind must not be empty".to_string());
485 }
486 if r.repo.is_empty() {
487 return Err("repo must not be empty".to_string());
488 }
489 check_commit(&r.commit)?;
490 if r.procedure.is_empty() {
491 return Err("procedure identity must not be empty".to_string());
492 }
493 if r.machine.is_empty() {
494 return Err("machine identity must not be empty".to_string());
495 }
496 if r.env_class != r.tier.as_str() {
497 return Err(format!(
498 "env_class {:?} contradicts tier {:?}",
499 r.env_class,
500 r.tier.as_str()
501 ));
502 }
503 check_digest_list("input_artifacts", &r.input_artifacts)?;
504 check_digest_list("output_artifacts", &r.output_artifacts)?;
505 if r.output_digest.len() != 64 || !is_hex(&r.output_digest) {
506 return Err("output_digest must be 64 hex digits (BLAKE3)".to_string());
507 }
508 let output_digest = hex_to_bytes(&r.output_digest).ok_or("bad output_digest")?;
509 if r.assertions.is_empty() && r.result == Verdict::Pass {
510 return Err("PASS receipts must carry at least one assertion".to_string());
511 }
512 let mut seen_assertions = BTreeSet::new();
513 for a in &r.assertions {
514 if a.id.is_empty() {
515 return Err("assertion id must not be empty".to_string());
516 }
517 if !seen_assertions.insert(a.id.clone()) {
518 return Err(format!("duplicate assertion id {:?}", a.id));
519 }
520 }
521 for d in &r.dependencies {
522 if d.len() != 64 || !is_hex(d) {
523 return Err(format!("dependency {d:?} is not a 64 digit receipt hash"));
524 }
525 }
526 if r.observed_mutation.severity() > r.declared_mutation.severity() {
527 return Err(format!(
528 "observed mutation {} exceeds declared mutation {}",
529 r.observed_mutation.as_str(),
530 r.declared_mutation.as_str()
531 ));
532 }
533 check_tier_mutation(r.tier, r.observed_mutation)?;
534 if r.tier == Tier::Production {
535 let low = r.authority.to_ascii_lowercase();
536 if r.authority.trim().is_empty() {
537 return Err("PRODUCTION receipts require an authority reference".to_string());
538 }
539 if low.contains("test-only") || low.contains("test_only") || low.contains("testonly") {
540 return Err("a TEST_ONLY signer cannot produce a PRODUCTION receipt".to_string());
541 }
542 }
543 if r.tier.is_hardware() && r.lease.is_none() {
544 // Not a canonical encoding failure; verification reports INCOMPLETE.
545 }
546 if let Some(ledger) = &r.ledger {
547 if ledger.hash.len() != 64 || !is_hex(&ledger.hash) {
548 return Err("ledger hash must be 64 hex digits".to_string());
549 }
550 }
551 if let Some(lease) = &r.lease {
552 if lease.hold_id.len() != 64 || !is_hex(&lease.hold_id) {
553 return Err("lease hold_id must be 64 hex digits".to_string());
554 }
555 if lease.resource.trim().is_empty() {
556 return Err("lease resource must not be empty".to_string());
557 }
558 }
559
560 let mut out = Vec::new();
561 out.extend_from_slice(DOMAIN);
562 push_u32(&mut out, SCHEMA_VERSION);
563 push_str(&mut out, &r.kind);
564 push_str(&mut out, r.tier.as_str());
565 out.push(r.result.code());
566 push_str(&mut out, &r.repo);
567 push_str(&mut out, &r.commit);
568 out.push(u8::from(r.dirty));
569 push_str(&mut out, &r.toolchain);
570 push_str(&mut out, &r.procedure);
571 push_str(&mut out, &r.machine);
572 push_str(&mut out, &r.env_class);
573 let inputs = sorted_unique(&r.input_artifacts);
574 push_u32(&mut out, inputs.len() as u32);
575 for item in &inputs {
576 push_str(&mut out, item);
577 }
578 let outputs = sorted_unique(&r.output_artifacts);
579 push_u32(&mut out, outputs.len() as u32);
580 for item in &outputs {
581 push_str(&mut out, item);
582 }
583 let mut assertions = r.assertions.clone();
584 assertions.sort_by(|a, b| a.id.cmp(&b.id));
585 push_u32(&mut out, assertions.len() as u32);
586 for a in &assertions {
587 push_str(&mut out, &a.id);
588 push_str(&mut out, &a.expected);
589 push_str(&mut out, &a.observed);
590 out.push(u8::from(a.pass));
591 push_str(&mut out, &a.source);
592 push_str(&mut out, &a.note);
593 }
594 let deps = sorted_unique(&r.dependencies);
595 push_u32(&mut out, deps.len() as u32);
596 for d in &deps {
597 let raw = hex_to_bytes(d).ok_or("bad dependency hash")?;
598 out.extend_from_slice(&raw);
599 }
600 out.push(r.declared_mutation.code());
601 out.push(r.observed_mutation.code());
602 push_str(&mut out, &r.authority);
603 out.extend_from_slice(&output_digest);
604 let refs = sorted_unique(&r.external_refs);
605 push_u32(&mut out, refs.len() as u32);
606 for item in &refs {
607 push_str(&mut out, item);
608 }
609 match &r.ledger {
610 Some(ledger) => {
611 out.push(1);
612 push_u64(&mut out, ledger.index);
613 let raw = hex_to_bytes(&ledger.hash).ok_or("bad ledger hash")?;
614 out.extend_from_slice(&raw);
615 }
616 None => out.push(0),
617 }
618 match &r.lease {
619 Some(lease) => {
620 out.push(1);
621 let normalized = lease.hold_id.to_ascii_lowercase();
622 let raw = hex_to_bytes(&normalized).ok_or("bad hold id")?;
623 out.extend_from_slice(&raw);
624 push_str(&mut out, &lease.resource);
625 }
626 None => out.push(0),
627 }
628 push_u64(&mut out, r.timestamp);
629 let feats = sorted_unique(&r.required_features);
630 push_u32(&mut out, feats.len() as u32);
631 for f in &feats {
632 push_str(&mut out, f);
633 }
634 push_u32(&mut out, 0);
635 Ok(out)
636}
637
638/// Maximum observed hardware mutation allowed per tier.
639fn check_tier_mutation(tier: Tier, observed: Mutation) -> Result<(), String> {
640 let max = match tier {
641 Tier::Machine1ReadOnly => Mutation::RemovableMediaOnly.severity(),
642 Tier::Machine1Attended => Mutation::BootConfigurationChange.severity(),
643 Tier::Machine1Mutating | Tier::Production => u8::MAX,
644 _ => Mutation::BoundedTestRegionWrite.severity(),
645 };
646 if observed.severity() > max {
647 return Err(format!(
648 "tier {} cannot claim observed mutation {}",
649 tier.as_str(),
650 observed.as_str()
651 ));
652 }
653 if tier == Tier::Machine1ReadOnly
654 && matches!(
655 observed,
656 Mutation::BoundedTestRegionWrite
657 | Mutation::BootConfigurationChange
658 | Mutation::TrustRootChange
659 | Mutation::TpmPolicyChange
660 | Mutation::DestructiveStorage
661 )
662 {
663 return Err(format!(
664 "a read-only Machine 1 run cannot claim mutation {}",
665 observed.as_str()
666 ));
667 }
668 Ok(())
669}
670
671/// Compute the canonical receipt ID.
672pub fn receipt_id(r: &Receipt) -> Result<String, String> {
673 let bytes = canonical_bytes(r)?;
674 Ok(blake3::hash(&bytes).to_hex().to_string())
675}
676
677struct Cursor<'a> {
678 bytes: &'a [u8],
679 pos: usize,
680}
681
682impl<'a> Cursor<'a> {
683 fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
684 let end = self.pos.saturating_add(n);
685 if end > self.bytes.len() {
686 return Err("canonical encoding truncated".to_string());
687 }
688 let slice = &self.bytes[self.pos..end];
689 self.pos = end;
690 Ok(slice)
691 }
692
693 fn byte(&mut self) -> Result<u8, String> {
694 Ok(self.take(1)?[0])
695 }
696
697 fn u32_be(&mut self) -> Result<u32, String> {
698 let b = self.take(4)?;
699 Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
700 }
701
702 fn u64_be(&mut self) -> Result<u64, String> {
703 let b = self.take(8)?;
704 Ok(u64::from_be_bytes([
705 b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7],
706 ]))
707 }
708
709 fn text(&mut self) -> Result<String, String> {
710 let len = self.u64_be()? as usize;
711 if len > 16 * 1024 * 1024 {
712 return Err("canonical string too long".to_string());
713 }
714 let raw = self.take(len)?;
715 String::from_utf8(raw.to_vec()).map_err(|_| "canonical string not UTF-8".to_string())
716 }
717
718 fn count(&mut self) -> Result<usize, String> {
719 let n = self.u32_be()? as usize;
720 if n > 100_000 {
721 return Err("canonical list too long".to_string());
722 }
723 Ok(n)
724 }
725
726 fn hash_hex(&mut self) -> Result<String, String> {
727 let raw = self.take(32)?;
728 Ok(raw.iter().map(|b| format!("{b:02x}")).collect())
729 }
730}
731
732/// Strictly decode canonical bytes back to a receipt. Anything malformed,
733/// truncated, extended with trailing bytes, carrying unknown enum codes,
734/// unknown features, or nonzero reserved content fails closed. The decoded
735/// receipt's ID is recomputed from the bytes.
736pub fn decode_canonical(bytes: &[u8]) -> Result<Receipt, String> {
737 let mut c = Cursor { bytes, pos: 0 };
738 if c.take(DOMAIN.len())? != DOMAIN {
739 return Err("bad canonical domain separator".to_string());
740 }
741 if c.u32_be()? != SCHEMA_VERSION {
742 return Err("unsupported canonical version".to_string());
743 }
744 let kind = c.text()?;
745 let tier = Tier::parse(&c.text()?).ok_or("unknown tier in canonical encoding")?;
746 let result = Verdict::from_code(c.byte()?).ok_or("unknown result in canonical encoding")?;
747 let repo = c.text()?;
748 let commit = c.text()?;
749 let dirty = match c.byte()? {
750 0 => false,
751 1 => true,
752 _ => return Err("bad dirty flag in canonical encoding".to_string()),
753 };
754 let toolchain = c.text()?;
755 let procedure = c.text()?;
756 let machine = c.text()?;
757 let env_class = c.text()?;
758 let mut input_artifacts = Vec::new();
759 for _ in 0..c.count()? {
760 input_artifacts.push(c.text()?);
761 }
762 let mut output_artifacts = Vec::new();
763 for _ in 0..c.count()? {
764 output_artifacts.push(c.text()?);
765 }
766 let mut assertions = Vec::new();
767 for _ in 0..c.count()? {
768 assertions.push(Assertion {
769 id: c.text()?,
770 expected: c.text()?,
771 observed: c.text()?,
772 pass: match c.byte()? {
773 0 => false,
774 1 => true,
775 _ => return Err("bad assertion result in canonical encoding".to_string()),
776 },
777 source: c.text()?,
778 note: c.text()?,
779 });
780 }
781 let mut dependencies = Vec::new();
782 for _ in 0..c.count()? {
783 dependencies.push(c.hash_hex()?);
784 }
785 let declared_mutation =
786 Mutation::from_code(c.byte()?).ok_or("unknown mutation in canonical encoding")?;
787 let observed_mutation =
788 Mutation::from_code(c.byte()?).ok_or("unknown mutation in canonical encoding")?;
789 let authority = c.text()?;
790 let output_digest = c.hash_hex()?;
791 let mut external_refs = Vec::new();
792 for _ in 0..c.count()? {
793 external_refs.push(c.text()?);
794 }
795 let ledger = match c.byte()? {
796 0 => None,
797 1 => Some(LedgerRef {
798 index: c.u64_be()?,
799 hash: c.hash_hex()?,
800 }),
801 _ => return Err("bad ledger flag in canonical encoding".to_string()),
802 };
803 let lease = match c.byte()? {
804 0 => None,
805 1 => {
806 let hold_id = c.hash_hex()?;
807 let resource = c.text()?;
808 Some(LeaseRef { hold_id, resource })
809 }
810 _ => return Err("bad lease flag in canonical encoding".to_string()),
811 };
812 let timestamp = c.u64_be()?;
813 let mut required_features = Vec::new();
814 for _ in 0..c.count()? {
815 required_features.push(c.text()?);
816 }
817 if c.u32_be()? != 0 {
818 return Err("reserved field must be zero".to_string());
819 }
820 if c.pos != bytes.len() {
821 return Err("trailing bytes after canonical encoding".to_string());
822 }
823 let mut receipt = Receipt {
824 schema: SCHEMA.to_string(),
825 version: SCHEMA_VERSION,
826 id: String::new(),
827 kind,
828 tier,
829 result,
830 timestamp,
831 repo,
832 commit,
833 dirty,
834 toolchain,
835 procedure,
836 machine,
837 env_class,
838 input_artifacts,
839 output_artifacts,
840 assertions,
841 dependencies,
842 declared_mutation,
843 observed_mutation,
844 authority,
845 output_digest,
846 external_refs,
847 ledger,
848 lease,
849 required_features,
850 reserved: String::new(),
851 };
852 // Re-encode to confirm the bytes were canonical and to mint the ID.
853 // Canonical encoding also re-applies every semantic check.
854 let reencoded = canonical_bytes(&receipt)?;
855 if reencoded != bytes {
856 return Err("canonical encoding not in canonical order".to_string());
857 }
858 receipt.id = blake3::hash(bytes).to_hex().to_string();
859 Ok(receipt)
860}
861
862/// Parse receipt JSON and check identity plus internal consistency.
863/// Ledger and lease stores are checked separately by [`verify_with_store`].
864pub fn verify_bytes(text: &[u8]) -> Result<(Receipt, Report), String> {
865 let receipt: Receipt =
866 serde_json::from_slice(text).map_err(|e| format!("receipt JSON invalid: {e}"))?;
867 let computed = receipt_id(&receipt)?;
868 if receipt.id.to_ascii_lowercase() != computed {
869 return Err(format!(
870 "receipt id mismatch: file claims {}, canonical identity is {}",
871 receipt.id, computed
872 ));
873 }
874 Ok((receipt.clone(), check_consistency(&receipt)))
875}
876
877/// Consistency rules that need no store access.
878fn check_consistency(r: &Receipt) -> Report {
879 let mut problems = Vec::new();
880 if r.result == Verdict::Pass {
881 if r.assertions.iter().any(|a| !a.pass) {
882 problems.push("result is PASS but a structured assertion failed".to_string());
883 }
884 if r.tier.is_hardware() && r.lease.is_none() {
885 return Report::closed(
886 Verdict::Incomplete,
887 vec![
888 "hardware receipt has no resource lease binding; run under `aien-proof hold` and reference the hold".to_string(),
889 ],
890 );
891 }
892 }
893 if r.result == Verdict::Blocked && r.tier.is_physical() {
894 problems.push("a run marked BLOCKED cannot close a gate".to_string());
895 }
896 if problems.is_empty() {
897 match r.result {
898 Verdict::Pass => Report::pass("identity matches, assertions all pass"),
899 Verdict::Fail => {
900 Report::closed(Verdict::Fail, vec!["receipt records FAIL".to_string()])
901 }
902 Verdict::Blocked => Report::closed(
903 Verdict::Blocked,
904 vec!["receipt records BLOCKED".to_string()],
905 ),
906 Verdict::Incomplete => Report::closed(
907 Verdict::Incomplete,
908 vec!["receipt records INCOMPLETE".to_string()],
909 ),
910 Verdict::Skipped => Report::closed(
911 Verdict::Skipped,
912 vec!["receipt records SKIPPED".to_string()],
913 ),
914 }
915 } else {
916 Report::fail(problems)
917 }
918}
919
920/// Full single receipt verification against a proof store root:
921/// identity, consistency, ledger event, and lease binding.
922pub fn verify_with_store(text: &[u8], store: &Path) -> Result<(Receipt, Report), String> {
923 let (receipt, mut report) = verify_bytes(text)?;
924 if report.status == Verdict::Fail {
925 return Ok((receipt, report));
926 }
927 if let Some(problem) = crate::ledger_bind::check_ledger_ref(&receipt, store)? {
928 return Ok((receipt, Report::fail(vec![problem])));
929 }
930 if let Some(report2) = crate::lease::check_lease_ref(&receipt, store)? {
931 if report2.status != Verdict::Pass {
932 return Ok((receipt, report2));
933 }
934 }
935 if report.status == Verdict::Pass {
936 // Recompute the consistency PASS line with store checks included.
937 report = Report::pass("identity, ledger, and lease bindings check out");
938 if receipt.result != Verdict::Pass {
939 report = check_consistency(&receipt);
940 }
941 }
942 Ok((receipt, report))
943}
944
945/// Load a receipt from the store by ID. A file whose bytes hash to a
946/// different ID is a duplicate ID collision and fails closed.
947pub fn load_receipt(store: &Path, id: &str) -> Result<Receipt, String> {
948 let normalized = id.to_ascii_lowercase();
949 if normalized.len() != 64 || !is_hex(&normalized) {
950 return Err(format!("receipt id {id:?} is not a 64 digit hash"));
951 }
952 let path = store.join(RECEIPT_DIR).join(format!("{normalized}.json"));
953 let text = fs::read(&path).map_err(|_| format!("missing dependency receipt {normalized}"))?;
954 let (receipt, _) = verify_bytes(&text)?;
955 if receipt.id.to_ascii_lowercase() != normalized {
956 return Err(format!(
957 "receipt file {normalized} holds bytes for receipt {}",
958 receipt.id
959 ));
960 }
961 Ok(receipt)
962}
963
964/// Write a receipt into the store under its canonical ID.
965pub fn store_receipt(store: &Path, receipt: &Receipt) -> Result<String, String> {
966 let computed = receipt_id(receipt)?;
967 if receipt.id.to_ascii_lowercase() != computed {
968 return Err(format!(
969 "refusing to store: id {} does not match canonical {computed}",
970 receipt.id
971 ));
972 }
973 let dir = store.join(RECEIPT_DIR);
974 fs::create_dir_all(&dir).map_err(|e| e.to_string())?;
975 let path = dir.join(format!("{computed}.json"));
976 let mut owned = receipt.clone();
977 owned.id = computed.clone();
978 let text = serde_json::to_string_pretty(&owned).map_err(|e| e.to_string())?;
979 fs::write(&path, format!("{text}\n")).map_err(|e| e.to_string())?;
980 Ok(computed)
981}
982
983/// List all receipt IDs present in the store.
984pub fn list_receipts(store: &Path) -> Vec<String> {
985 let mut ids = Vec::new();
986 let dir = store.join(RECEIPT_DIR);
987 let entries = fs::read_dir(dir).into_iter().flatten().flatten();
988 for entry in entries {
989 let name = entry.file_name().to_string_lossy().into_owned();
990 if let Some(id) = name.strip_suffix(".json") {
991 if id.len() == 64 && is_hex(id) {
992 ids.push(id.to_ascii_lowercase());
993 }
994 }
995 }
996 ids.sort();
997 ids
998}
999
1000#[cfg(test)]
1001pub(crate) mod fixtures {
1002 use super::*;
1003
1004 pub fn sample() -> Receipt {
1005 Receipt {
1006 schema: SCHEMA.to_string(),
1007 version: SCHEMA_VERSION,
1008 id: String::new(),
1009 kind: "seed-0b-qemu".to_string(),
1010 tier: Tier::Qemu,
1011 result: Verdict::Pass,
1012 timestamp: 1_786_000_000,
1013 repo: "https://github.com/aien-dev/aienux".to_string(),
1014 commit: "a".repeat(40),
1015 dirty: false,
1016 toolchain: "rustc 1.90.0".to_string(),
1017 procedure: "scripts/qemu_seed0b.sh".to_string(),
1018 machine: "qemu-virt-aarch64".to_string(),
1019 env_class: "QEMU".to_string(),
1020 input_artifacts: vec!["blake3:".to_string() + &"b".repeat(64)],
1021 output_artifacts: vec![],
1022 assertions: vec![Assertion {
1023 id: "artifact_signature_valid".to_string(),
1024 expected: "valid".to_string(),
1025 observed: "valid".to_string(),
1026 pass: true,
1027 source: "qemu_seed0b.sh".to_string(),
1028 note: String::new(),
1029 }],
1030 dependencies: vec![],
1031 declared_mutation: Mutation::None,
1032 observed_mutation: Mutation::None,
1033 authority: String::new(),
1034 output_digest: "c".repeat(64),
1035 external_refs: vec![],
1036 ledger: None,
1037 lease: None,
1038 required_features: vec![],
1039 reserved: String::new(),
1040 }
1041 }
1042
1043 pub fn sealed(mut r: Receipt) -> Receipt {
1044 let id = receipt_id(&r).unwrap();
1045 r.id = id;
1046 r
1047 }
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052 use super::fixtures::{sample, sealed};
1053 use super::*;
1054
1055 #[test]
1056 fn identity_is_stable_and_order_independent() {
1057 let a = sealed(sample());
1058 let mut b = a.clone();
1059 b.input_artifacts
1060 .push("blake3:".to_string() + &"a".repeat(64));
1061 b.input_artifacts.swap(0, 1);
1062 b.assertions.push(Assertion {
1063 id: "aaa_first".to_string(),
1064 expected: "x".to_string(),
1065 observed: "x".to_string(),
1066 pass: true,
1067 source: "s".to_string(),
1068 note: String::new(),
1069 });
1070 let mut c = b.clone();
1071 c.assertions.swap(0, 1);
1072 // Different assertion sets differ; same set in any order matches.
1073 assert_ne!(receipt_id(&a).unwrap(), receipt_id(&b).unwrap());
1074 assert_eq!(receipt_id(&b).unwrap(), receipt_id(&c).unwrap());
1075 let _ = a;
1076 }
1077
1078 #[test]
1079 fn altered_bytes_fail_closed() {
1080 let r = sealed(sample());
1081 let mut text = serde_json::to_vec(&r).unwrap();
1082 text[60] ^= 0x01;
1083 assert!(verify_bytes(&text).is_err());
1084 }
1085
1086 #[test]
1087 fn changed_commit_changes_identity() {
1088 let mut r = sample();
1089 let before = receipt_id(&r).unwrap();
1090 r.commit = "d".repeat(40);
1091 assert_ne!(receipt_id(&r).unwrap(), before);
1092 }
1093
1094 #[test]
1095 fn changed_artifact_hash_changes_identity() {
1096 let mut r = sample();
1097 let before = receipt_id(&r).unwrap();
1098 r.input_artifacts = vec!["blake3:".to_string() + &"d".repeat(64)];
1099 assert_ne!(receipt_id(&r).unwrap(), before);
1100 }
1101
1102 #[test]
1103 fn changed_assertion_result_fails_pass_claim() {
1104 let mut r = sealed(sample());
1105 r.assertions[0].pass = false;
1106 // Identity changed, so reseal, then consistency must fail the PASS.
1107 let r = sealed(r);
1108 let text = serde_json::to_vec(&r).unwrap();
1109 let (_, report) = verify_bytes(&text).unwrap();
1110 assert_eq!(report.status, Verdict::Fail);
1111 }
1112
1113 #[test]
1114 fn pass_without_assertions_is_rejected() {
1115 let mut r = sample();
1116 r.assertions.clear();
1117 assert!(receipt_id(&r).is_err());
1118 }
1119
1120 #[test]
1121 fn unknown_required_feature_fails_closed() {
1122 let mut r = sample();
1123 r.required_features = vec!["v9-teleport".to_string()];
1124 assert!(receipt_id(&r).unwrap_err().contains("unknown required"));
1125 }
1126
1127 #[test]
1128 fn reserved_content_fails_closed() {
1129 let mut r = sample();
1130 r.reserved = "x".to_string();
1131 assert!(receipt_id(&r).unwrap_err().contains("reserved"));
1132 }
1133
1134 #[test]
1135 fn malformed_canonical_inputs_fail() {
1136 let mut r = sample();
1137 r.commit = "not-a-sha".to_string();
1138 assert!(receipt_id(&r).is_err());
1139 let mut r = sample();
1140 r.output_digest = "zz".to_string();
1141 assert!(receipt_id(&r).is_err());
1142 let mut r = sample();
1143 r.dependencies = vec!["nope".to_string()];
1144 assert!(receipt_id(&r).is_err());
1145 }
1146
1147 #[test]
1148 fn test_only_signer_cannot_mint_production() {
1149 let mut r = sample();
1150 r.tier = Tier::Production;
1151 r.env_class = "PRODUCTION".to_string();
1152 r.authority = "test-only lab signer".to_string();
1153 assert!(receipt_id(&r).unwrap_err().contains("TEST_ONLY"));
1154 r.authority = String::new();
1155 assert!(receipt_id(&r).is_err());
1156 }
1157
1158 #[test]
1159 fn observed_beyond_declared_fails() {
1160 let mut r = sample();
1161 r.tier = Tier::Machine1Mutating;
1162 r.env_class = "MACHINE1_MUTATING".to_string();
1163 r.declared_mutation = Mutation::VolatileOnly;
1164 r.observed_mutation = Mutation::BootConfigurationChange;
1165 assert!(receipt_id(&r).unwrap_err().contains("exceeds declared"));
1166 }
1167
1168 #[test]
1169 fn read_only_run_cannot_claim_mutation() {
1170 let mut r = sample();
1171 r.tier = Tier::Machine1ReadOnly;
1172 r.env_class = "MACHINE1_READ_ONLY".to_string();
1173 r.declared_mutation = Mutation::BootConfigurationChange;
1174 r.observed_mutation = Mutation::BootConfigurationChange;
1175 assert!(receipt_id(&r).is_err());
1176 }
1177
1178 #[test]
1179 fn hardware_receipt_without_lease_is_incomplete() {
1180 let mut r = sample();
1181 r.tier = Tier::Machine1Attended;
1182 r.env_class = "MACHINE1_ATTENDED".to_string();
1183 let r = sealed(r);
1184 let text = serde_json::to_vec(&r).unwrap();
1185 let (_, report) = verify_bytes(&text).unwrap();
1186 assert_eq!(report.status, Verdict::Incomplete);
1187 }
1188
1189 #[test]
1190 fn duplicate_id_with_different_bytes_fails() {
1191 let r = sealed(sample());
1192 let mut tampered = r.clone();
1193 tampered.assertions[0].observed = "tampered".to_string();
1194 // Keep the original ID on different bytes.
1195 let text = serde_json::to_vec(&tampered).unwrap();
1196 // Rewriting the ID field back to the original still fails identity.
1197 let mut value: serde_json::Value = serde_json::from_slice(&text).unwrap();
1198 value["id"] = serde_json::Value::String(r.id.clone());
1199 let forged = serde_json::to_vec(&value).unwrap();
1200 assert!(verify_bytes(&forged).is_err());
1201 }
1202
1203 #[test]
1204 fn env_tier_contradiction_rejected() {
1205 let mut r = sample();
1206 r.env_class = "MACHINE1_MUTATING".to_string();
1207 assert!(receipt_id(&r).unwrap_err().contains("contradicts"));
1208 }
1209
1210 #[test]
1211 fn canonical_roundtrip() {
1212 let r = sealed(sample());
1213 let bytes = canonical_bytes(&r).unwrap();
1214 let back = decode_canonical(&bytes).unwrap();
1215 assert_eq!(back, r);
1216 }
1217
1218 #[test]
1219 fn malformed_canonical_encoding_fails() {
1220 let r = sealed(sample());
1221 let bytes = canonical_bytes(&r).unwrap();
1222 // Truncated.
1223 assert!(decode_canonical(&bytes[..bytes.len() - 5]).is_err());
1224 // Bad domain.
1225 let mut bad = bytes.clone();
1226 bad[0] ^= 0xFF;
1227 assert!(decode_canonical(&bad).is_err());
1228 // Trailing bytes.
1229 let mut long = bytes.clone();
1230 long.push(0);
1231 assert!(decode_canonical(&long).unwrap_err().contains("trailing"));
1232 // Corruption inside a free form string still decodes structurally,
1233 // but the identity changes, so tampering is always visible.
1234 let mut kind_hit = bytes.clone();
1235 kind_hit[40] ^= 0x09;
1236 let altered = decode_canonical(&kind_hit).unwrap();
1237 assert_ne!(altered.id, r.id);
1238 assert_ne!(altered.kind, r.kind);
1239 }
1240
1241 #[test]
1242 fn canonical_rejects_nonzero_reserved() {
1243 let r = sealed(sample());
1244 let mut bytes = canonical_bytes(&r).unwrap();
1245 // Reserved is the final u32; set it nonzero.
1246 let n = bytes.len();
1247 bytes[n - 1] = 1;
1248 assert!(decode_canonical(&bytes).unwrap_err().contains("reserved"));
1249 }
1250}