Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/tools/aien-test/src/bundle.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / tools / aien-test / src / bundle.rs` 1399 lines ยท 53548 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 //! VerificationBundleV1 (ADR 0033 Decision 6): the signed, per-commit result 17 //! of AIEN Verification, and the independent verifier GitHub runs. 18 //! 19 //! A bundle is one canonical-JSON object (the EvidenceReceiptV1 encoding, 20 //! `evidence::canonical`) that names the repository, the commit, the graph of 21 //! checks the planner produced, one entry per check (receipt digest for a run, 22 //! resolution record for a cache hit, nothing for `not_run`/`blocked`), the 23 //! commit verdict, the executor, and an `ed25519` signature over the canonical 24 //! bytes of everything but the `signature` member. 25 //! 26 //! The verifier does not trust the file: it recomputes the canonical bytes, 27 //! checks the signature against the public key the repository committed, 28 //! checks repository and commit against the ones being gated, checks that the 29 //! executor id is the fingerprint of that key, that every required check is 30 //! present, and that the declared verdict is what the verdict algebra gives. 31 //! Any mismatch is a rejection with a code, never a PASS. 32 //! 33 //! `plan.scope` (signed with the rest) says what the worker planned: `full` 34 //! (every gate at HEAD, an Alpha qualification) or `changed` (the gates the 35 //! diff selects). A bundle without it is `changed`. `verify-bundle 36 //! --require-full` rejects (NOT_FULL_SCOPE) any bundle whose scope is not 37 //! `full`, and (NO_GPU_RECEIPT) any full bundle without a required check on 38 //! backend `gb10` that ran (or was resolved from cache): an Alpha is the 39 //! stage tested on the Spark's GPU, and a full-scope PASS of host gates alone 40 //! is not one (alpha/`20261024`.1: 34 checks, all host). A gb10 check that ran 41 //! and FAILed is a receipt: the bundle is then FAIL, not "no receipt". 42 //! 43 //! Verdict algebra (Decision 7, applied to a bundle): PASS only if every 44 //! `required` entry ran or was resolved from cache with verdict PASS; FAIL if 45 //! any required entry is FAIL; otherwise NOT_RUN. Entries with 46 //! `required: false` (every ADVISORY check, and optional checks) never change 47 //! the commit verdict. Nothing promotes NOT_RUN to PASS. 48 //! 49 //! Keys: the signing key is a 32-byte seed, hex, in a file the worker user 50 //! owns with mode 0600 (`keygen`). The public key is 32 bytes, hex, committed 51 //! at `.aien/verify.pub` in each verified repository. The executor id is 52 //! `sha256(pubkey bytes)`, hex, so a bundle names the key that must verify it 53 //! and the verifier can refuse an unknown executor before looking further. 54 55 use crate::evidence::{canonical, canonical_digest, sha256_hex}; 56 use `ed25519`_dalek::{Signature, Signer, SigningKey, VerifyingKey}; 57 use serde_json::{json, Map, Value}; 58 use std::fmt; 59 use std::fs; 60 use std::io::{Read, Write}; 61 use std::os::unix::fs::OpenOptionsExt; 62 use std::path::Path; 63 64 pub const SCHEMA: &str = "aien-verification-bundle/1"; 65 pub const SIG_ALG: &str = "`ed25519`"; 66 pub const RECEIPT_ID_SCHEMES: [&str; 2] = ["sha256-canonical-json", "aien-proof-blake3"]; 67 pub const STATUSES: [&str; 4] = ["run", "cached", "not_run", "blocked"]; 68 pub const VERDICTS: [&str; 6] = [ 69 "PASS", 70 "FAIL", 71 "NOT_RUN", 72 "BLOCKED_HARDWARE", 73 "BLOCKED_OPERATOR", 74 "MISSING_IMPLEMENTATION", 75 ]; 76 pub const EXACTNESS: [&str; 4] = ["EXACT", "BOUNDED", "APPROXIMATE", "ADVISORY"]; 77 /// `plan.scope`: every gate at HEAD (an Alpha qualification). 78 pub const SCOPE_FULL: &str = "full"; 79 /// `plan.scope`: the gates the diff selects. A bundle without the member (or 80 /// without a `plan`) is this scope. 81 pub const SCOPE_CHANGED: &str = "changed"; 82 pub const SCOPES: [&str; 2] = [SCOPE_FULL, SCOPE_CHANGED]; 83 84 /// Why a bundle was refused. The code is what the GitHub log and the operator 85 /// see; the text says which member. 86 #[derive(Debug, Clone, PartialEq, Eq)] 87 pub enum Reject { 88 /// Not a VerificationBundleV1: missing or malformed member. 89 Schema(String), 90 /// The bundle's public key is not the one the repository committed. 91 UnknownKey, 92 /// The signature does not verify over the canonical bytes. 93 BadSignature, 94 /// `repository` is not the repository being gated. 95 RepositoryMismatch { bundle: String, expected: String }, 96 /// `commit` is not the commit being gated. 97 CommitMismatch { bundle: String, expected: String }, 98 /// `executor.id` is not the fingerprint of the signing key. 99 UnknownExecutor, 100 /// A check the gate requires has no entry. 101 MissingRequiredCheck(String), 102 /// The declared `verdict` is not what the entries give. 103 VerdictInconsistent { declared: String, computed: String }, 104 /// `--require-full`: the signed plan scope is not `full`. 105 NotFullScope(String), 106 /// `--require-full`: no required `gb10` check ran. Carries the 107 /// backends the bundle has (`host=34`) and its gb10 checks with their 108 /// status and verdict (`none` when there is no gb10 check at all). 109 NoGpuReceipt { backends: String, gb10: String }, 110 } 111 112 impl Reject { 113 pub fn code(&self) -> &'static str { 114 match self { 115 Reject::Schema(_) => "SCHEMA", 116 Reject::UnknownKey => "UNKNOWN_KEY", 117 Reject::BadSignature => "BAD_SIGNATURE", 118 Reject::RepositoryMismatch { .. } => "REPOSITORY_MISMATCH", 119 Reject::CommitMismatch { .. } => "COMMIT_MISMATCH", 120 Reject::UnknownExecutor => "UNKNOWN_EXECUTOR", 121 Reject::MissingRequiredCheck(_) => "MISSING_REQUIRED_CHECK", 122 Reject::VerdictInconsistent { .. } => "VERDICT_INCONSISTENT", 123 Reject::NotFullScope(_) => "NOT_FULL_SCOPE", 124 Reject::NoGpuReceipt { .. } => "NO_GPU_RECEIPT", 125 } 126 } 127 } 128 129 impl fmt::Display for Reject { 130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 131 match self { 132 Reject::Schema(m) => write!(f, "SCHEMA: {m}"), 133 Reject::UnknownKey => { 134 write!(f, "UNKNOWN_KEY: bundle key is not the committed verify.pub") 135 } 136 Reject::BadSignature => write!( 137 f, 138 "BAD_SIGNATURE: signature does not verify over the canonical bytes" 139 ), 140 Reject::RepositoryMismatch { bundle, expected } => { 141 write!( 142 f, 143 "REPOSITORY_MISMATCH: bundle is for {bundle}, gating {expected}" 144 ) 145 } 146 Reject::CommitMismatch { bundle, expected } => { 147 write!( 148 f, 149 "COMMIT_MISMATCH: bundle is for {bundle}, gating {expected}" 150 ) 151 } 152 Reject::UnknownExecutor => write!( 153 f, 154 "UNKNOWN_EXECUTOR: executor.id is not the fingerprint of the signing key" 155 ), 156 Reject::MissingRequiredCheck(g) => write!(f, "MISSING_REQUIRED_CHECK: {g}"), 157 Reject::VerdictInconsistent { declared, computed } => { 158 write!( 159 f, 160 "VERDICT_INCONSISTENT: bundle says {declared}, entries give {computed}" 161 ) 162 } 163 Reject::NotFullScope(scope) => write!( 164 f, 165 "NOT_FULL_SCOPE: plan scope is {scope}, not a full-scope (Alpha) qualification" 166 ), 167 Reject::NoGpuReceipt { backends, gb10 } => write!( 168 f, 169 "NO_GPU_RECEIPT: an Alpha needs a required check on backend gb10 that ran on the \ 170 Spark's GPU, and this full-scope bundle has none (checks by backend: {backends}; \ 171 gb10 checks: {gb10})" 172 ), 173 } 174 } 175 } 176 177 /// What the verifier learned from a bundle it accepted. 178 #[derive(Debug, Clone, PartialEq, Eq)] 179 pub struct Verified { 180 pub verdict: String, 181 pub digest: String, 182 pub checks: usize, 183 pub required: usize, 184 pub cached: usize, 185 /// The worker's `plan.verdict` member when the bundle carries one (signed 186 /// with the rest). None for a bundle without a plan member. 187 pub plan_verdict: Option, 188 /// The signed `plan.scope`: `full` or `changed` (the default). 189 pub scope: String, 190 } 191 192 impl Verified { 193 /// What a gate may act on: PASS only when the algebra says PASS, at least 194 /// one required check exists (zero required checks is PASS only 195 /// vacuously: nothing vouches for the commit), and the plan member, when 196 /// present, says PASS too (an UNMAPPED or BLOCKED plan is NOT_RUN). 197 pub fn gate_verdict(&self) -> &str { 198 match self.verdict.as_str() { 199 "PASS" if self.required == 0 => "NOT_RUN", 200 "PASS" if self.plan_verdict.as_deref().is_some_and(|p| p != "PASS") => "NOT_RUN", 201 v => v, 202 } 203 } 204 } 205 206 /// What the gate expects the bundle to be about. 207 #[derive(Debug, Clone, PartialEq, Eq)] 208 pub struct Expect { 209 pub repository: String, 210 pub commit: String, 211 pub pubkey_hex: String, 212 /// Gates that must have an entry (the repository's required list). Empty 213 /// means "whatever the bundle marks required", which is weaker; the gate 214 /// should pass its own list. 215 pub required: Vec, 216 /// `--require-full`: refuse (NOT_FULL_SCOPE) unless the signed plan scope 217 /// is `full`. 218 pub require_full: bool, 219 /// `--allow-host-only`: with `--require-full`, accept a full-scope PASS 220 /// that carries no gb10 receipt. For a repository whose own gate manifests 221 /// declare no GPU gate: the caller reads those manifests and passes this 222 /// flag only when none of them requires `gb10`, so a repository that does 223 /// declare one still needs its GPU run. 224 pub allow_host_only: bool, 225 } 226 227 // ---------------------------------------------------------------- hex 228 229 pub fn hex_encode(bytes: &[u8]) -> String { 230 let mut s = String::with_capacity(bytes.len() * 2); 231 for b in bytes { 232 s.push_str(&format!("{b:02x}")); 233 } 234 s 235 } 236 237 pub fn hex_decode(s: &str) -> Option> { 238 let s = s.trim(); 239 if !s.len().is_multiple_of(2) { 240 return None; 241 } 242 let mut out = Vec::with_capacity(s.len() / 2); 243 let b = s.as_bytes(); 244 let mut i = 0; 245 while i < b.len() { 246 let hi = (b[i] as char).to_digit(16)?; 247 let lo = (b[i + 1] as char).to_digit(16)?; 248 out.push((hi * 16 + lo) as u8); 249 i += 2; 250 } 251 Some(out) 252 } 253 254 fn is_hex(s: &str, n: usize) -> bool { 255 s.len() == n && s.bytes().all(|c| matches!(c, b'0'..=b'9' | b'a'..=b'f')) 256 } 257 258 // ---------------------------------------------------------------- keys 259 260 /// Executor id: sha256 over the 32 public-key bytes, hex. 261 pub fn fingerprint(vk: &VerifyingKey) -> String { 262 sha256_hex(vk.as_bytes()) 263 } 264 265 /// Generate a signing key from the kernel's randomness and write its hex seed 266 /// to `path` with mode 0600. Refuses to overwrite. Returns the public key hex. 267 pub fn keygen(path: &Path) -> Result { 268 let mut seed = [0u8; 32]; 269 fs::File::open("/dev/urandom") 270 .and_then(|mut f| f.read_exact(&mut seed)) 271 .map_err(|e| format!("cannot read /dev/urandom: {e}"))?; 272 let sk = SigningKey::from_bytes(&seed); 273 let mut f = fs::OpenOptions::new() 274 .write(true) 275 .create_new(true) 276 .mode(0o600) 277 .open(path) 278 .map_err(|e| format!("cannot create {}: {e}", path.display()))?; 279 f.write_all(hex_encode(&seed).as_bytes()) 280 .and_then(|_| f.write_all(b"\n")) 281 .map_err(|e| format!("cannot write {}: {e}", path.display()))?; 282 Ok(hex_encode(sk.verifying_key().as_bytes())) 283 } 284 285 pub fn load_signing_key(path: &Path) -> Result { 286 let txt = 287 fs::read_to_string(path).map_err(|e| format!("cannot read {}: {e}", path.display()))?; 288 let bytes = hex_decode(&txt).ok_or_else(|| format!("{} is not hex", path.display()))?; 289 let seed: [u8; 32] = bytes 290 .try_into() 291 .map_err(|_| format!("{} is not a 32-byte seed", path.display()))?; 292 Ok(SigningKey::from_bytes(&seed)) 293 } 294 295 /// `--pubkey` takes a file (hex inside) or the hex itself. 296 pub fn load_pubkey_hex(arg: &str) -> Result { 297 let p = Path::new(arg); 298 let txt = if p.is_file() { 299 fs::read_to_string(p).map_err(|e| format!("cannot read {}: {e}", p.display()))? 300 } else { 301 arg.to_string() 302 }; 303 let t = txt.trim().to_string(); 304 if !is_hex(&t, 64) { 305 return Err("public key must be 64 hex characters".to_string()); 306 } 307 Ok(t) 308 } 309 310 fn verifying_key(hex: &str) -> Option { 311 let bytes = hex_decode(hex)?; 312 let arr: [u8; 32] = bytes.try_into().ok()?; 313 VerifyingKey::from_bytes(&arr).ok() 314 } 315 316 // ---------------------------------------------------------------- shape 317 318 fn member<'a>(o: &'a Map, k: &str) -> Result<&'a Value, Reject> { 319 o.get(k) 320 .ok_or_else(|| Reject::Schema(format!("missing {k}"))) 321 } 322 323 fn text<'a>(o: &'a Map, k: &str) -> Result<&'a str, Reject> { 324 member(o, k)? 325 .as_str() 326 .ok_or_else(|| Reject::Schema(format!("{k} must be a string"))) 327 } 328 329 fn hex_member<'a>(o: &'a Map, k: &str, n: usize) -> Result<&'a str, Reject> { 330 let s = text(o, k)?; 331 if !is_hex(s, n) { 332 return Err(Reject::Schema(format!( 333 "{k} must be {n} lower-case hex characters" 334 ))); 335 } 336 Ok(s) 337 } 338 339 fn one_of<'a>(o: &'a Map, k: &str, allowed: &[&str]) -> Result<&'a str, Reject> { 340 let s = text(o, k)?; 341 if !allowed.contains(&s) { 342 return Err(Reject::Schema(format!( 343 "{k} {s:?} is not one of {allowed:?}" 344 ))); 345 } 346 Ok(s) 347 } 348 349 /// Validate one `checks[]` entry and return (gate, required, status, verdict, backend). 350 fn check_entry(v: &Value, i: usize) -> Result<(String, bool, String, String, String), Reject> { 351 let o = v 352 .as_object() 353 .ok_or_else(|| Reject::Schema(format!("checks[{i}] must be an object")))?; 354 let gate = text(o, "gate")?.to_string(); 355 hex_member(o, "check_id", 64)?; 356 let exactness = one_of(o, "exactness", &EXACTNESS)?; 357 let required = member(o, "required")? 358 .as_bool() 359 .ok_or_else(|| Reject::Schema(format!("checks[{i}].required must be a bool")))?; 360 if required && exactness == "ADVISORY" { 361 return Err(Reject::Schema(format!( 362 "checks[{i}] ({gate}): an ADVISORY check cannot be required" 363 ))); 364 } 365 let status = one_of(o, "status", &STATUSES)?.to_string(); 366 let verdict = one_of(o, "verdict", &VERDICTS)?.to_string(); 367 let backend = text(o, "backend")?.to_string(); 368 match status.as_str() { 369 "run" => { 370 hex_member(o, "receipt", 64)?; 371 } 372 "cached" => { 373 let r = member(o, "resolution")?.as_object().ok_or_else(|| { 374 Reject::Schema(format!("checks[{i}].resolution must be an object")) 375 })?; 376 hex_member(r, "resolved_from", 64)?; 377 } 378 _ => { 379 if verdict == "PASS" { 380 return Err(Reject::Schema(format!( 381 "checks[{i}] ({gate}): status {status} cannot carry verdict PASS" 382 ))); 383 } 384 } 385 } 386 Ok((gate, required, status, verdict, backend)) 387 } 388 389 /// The bundle verdict from its entries (Decision 7). Entries are 390 /// `(required, status, verdict)`. 391 pub fn compute_verdict(entries: &[(bool, String, String)]) -> &'static str { 392 let mut any_fail = false; 393 let mut all_pass = true; 394 for (required, status, verdict) in entries { 395 if !required { 396 continue; 397 } 398 let ran = status == "run" || status == "cached"; 399 if verdict == "FAIL" { 400 any_fail = true; 401 } 402 if !(ran && verdict == "PASS") { 403 all_pass = false; 404 } 405 } 406 if any_fail { 407 "FAIL" 408 } else if all_pass { 409 "PASS" 410 } else { 411 "NOT_RUN" 412 } 413 } 414 415 /// (gate, required, status, verdict, backend) per `checks[]` entry. 416 type Entries = Vec<(String, bool, String, String, String)>; 417 418 /// Structural validation of an unsigned or signed bundle. Returns the object 419 /// and the entry summary. Does not look at the signature. 420 fn validate(bundle: &Value) -> Result<(&Map, Entries), Reject> { 421 let o = bundle 422 .as_object() 423 .ok_or_else(|| Reject::Schema("bundle must be an object".to_string()))?; 424 if text(o, "schema")? != SCHEMA { 425 return Err(Reject::Schema(format!("schema must be {SCHEMA}"))); 426 } 427 text(o, "repository")?; 428 hex_member(o, "commit", 40)?; 429 hex_member(o, "tree_digest", 64)?; 430 hex_member(o, "graph_digest", 64)?; 431 one_of(o, "receipt_id_scheme", &RECEIPT_ID_SCHEMES)?; 432 one_of(o, "verdict", &["PASS", "FAIL", "NOT_RUN"])?; 433 text(o, "started_utc")?; 434 text(o, "finished_utc")?; 435 let ex = member(o, "executor")? 436 .as_object() 437 .ok_or_else(|| Reject::Schema("executor must be an object".to_string()))?; 438 hex_member(ex, "id", 64)?; 439 text(ex, "class")?; 440 hex_member(ex, "machine_digest", 64)?; 441 let checks = member(o, "checks")? 442 .as_array() 443 .ok_or_else(|| Reject::Schema("checks must be an array".to_string()))?; 444 let mut out = Vec::with_capacity(checks.len()); 445 for (i, c) in checks.iter().enumerate() { 446 out.push(check_entry(c, i)?); 447 } 448 let mut gates: Vec<&str> = out.iter().map(|e| e.0.as_str()).collect(); 449 gates.sort_unstable(); 450 if gates.windows(2).any(|w| w[0] == w[1]) { 451 return Err(Reject::Schema("checks[] lists a gate twice".to_string())); 452 } 453 // `plan.scope`, when present, is one of the two scopes; anything else is 454 // not a bundle this verifier understands. 455 if let Some(p) = o.get("plan") { 456 let p = p 457 .as_object() 458 .ok_or_else(|| Reject::Schema("plan must be an object".to_string()))?; 459 if p.contains_key("scope") { 460 one_of(p, "scope", &SCOPES)?; 461 } 462 } 463 Ok((o, out)) 464 } 465 466 /// The bundle's `plan.scope`: `full`, or `changed` when the member (or the 467 /// whole `plan`) is absent, as in every bundle written before scopes existed. 468 /// Unvalidated: `verify` refuses an unknown value. 469 pub fn scope_of(bundle: &Value) -> &str { 470 match bundle["plan"]["scope"].as_str() { 471 Some(s) if SCOPES.contains(&s) => s, 472 _ => SCOPE_CHANGED, 473 } 474 } 475 476 // ---------------------------------------------------------------- sign 477 478 /// Canonical bytes of the bundle without its `signature` member: what is 479 /// signed and what is verified. 480 pub fn signed_bytes(bundle: &Value) -> Result, Reject> { 481 let mut o = bundle 482 .as_object() 483 .ok_or_else(|| Reject::Schema("bundle must be an object".to_string()))? 484 .clone(); 485 o.remove("signature"); 486 canonical(&Value::Object(o)) 487 .map_err(|e| Reject::Schema(format!("not canonical-encodable: {e}"))) 488 } 489 490 /// Sign an unsigned bundle. Refuses a bundle that is not well formed, whose 491 /// `executor.id` is not this key's fingerprint, or whose declared verdict is 492 /// not what its entries give: a worker must not be able to sign a lie. 493 pub fn sign(bundle: &Value, key: &SigningKey) -> Result { 494 let (o, entries) = validate(bundle)?; 495 let vk = key.verifying_key(); 496 if o["executor"]["id"].as_str() != Some(fingerprint(&vk).as_str()) { 497 return Err(Reject::UnknownExecutor); 498 } 499 let computed = compute_verdict( 500 &entries 501 .iter() 502 .map(|e| (e.1, e.2.clone(), e.3.clone())) 503 .collect::>(), 504 ); 505 let declared = o["verdict"].as_str().unwrap_or(""); 506 if declared != computed { 507 return Err(Reject::VerdictInconsistent { 508 declared: declared.to_string(), 509 computed: computed.to_string(), 510 }); 511 } 512 let bytes = signed_bytes(bundle)?; 513 let sig: Signature = key.sign(&bytes); 514 let mut out = o.clone(); 515 out.insert( 516 "signature".to_string(), 517 json!({ "alg": SIG_ALG, "pubkey": hex_encode(vk.as_bytes()), "sig": hex_encode(&sig.to_bytes()) }), 518 ); 519 Ok(Value::Object(out)) 520 } 521 522 // ---------------------------------------------------------------- verify 523 524 /// The independent verifier. Order: shape, key known, signature, repository, 525 /// commit, executor, required checks present, verdict algebra. 526 pub fn verify(bundle: &Value, expect: &Expect) -> Result { 527 let (o, entries) = validate(bundle)?; 528 let sig = member(o, "signature")? 529 .as_object() 530 .ok_or_else(|| Reject::Schema("signature must be an object".to_string()))?; 531 if text(sig, "alg")? != SIG_ALG { 532 return Err(Reject::Schema(format!("signature.alg must be {SIG_ALG}"))); 533 } 534 let pubkey = hex_member(sig, "pubkey", 64)?; 535 let sighex = hex_member(sig, "sig", 128)?; 536 if pubkey != expect.pubkey_hex.trim() { 537 return Err(Reject::UnknownKey); 538 } 539 let vk = verifying_key(pubkey).ok_or(Reject::UnknownKey)?; 540 let sig_bytes = hex_decode(sighex).ok_or(Reject::BadSignature)?; 541 let signature = Signature::from_slice(&sig_bytes).map_err(|_| Reject::BadSignature)?; 542 let bytes = signed_bytes(bundle)?; 543 vk.verify_strict(&bytes, &signature) 544 .map_err(|_| Reject::BadSignature)?; 545 let repo = o["repository"].as_str().unwrap_or(""); 546 if repo != expect.repository { 547 return Err(Reject::RepositoryMismatch { 548 bundle: repo.to_string(), 549 expected: expect.repository.clone(), 550 }); 551 } 552 let commit = o["commit"].as_str().unwrap_or(""); 553 if commit != expect.commit { 554 return Err(Reject::CommitMismatch { 555 bundle: commit.to_string(), 556 expected: expect.commit.clone(), 557 }); 558 } 559 if o["executor"]["id"].as_str() != Some(fingerprint(&vk).as_str()) { 560 return Err(Reject::UnknownExecutor); 561 } 562 // The scope is signed: checked only once the signature holds. 563 let scope = scope_of(bundle).to_string(); 564 if expect.require_full && scope != SCOPE_FULL { 565 return Err(Reject::NotFullScope(scope)); 566 } 567 if expect.require_full && !expect.allow_host_only { 568 gpu_receipt(&entries)?; 569 } 570 for g in &expect.required { 571 match entries.iter().find(|e| &e.0 == g) { 572 None => return Err(Reject::MissingRequiredCheck(g.clone())), 573 Some(e) if !e.1 => { 574 return Err(Reject::Schema(format!( 575 "{g} is required by the gate but marked optional in the bundle" 576 ))) 577 } 578 _ => {} 579 } 580 } 581 let computed = compute_verdict( 582 &entries 583 .iter() 584 .map(|e| (e.1, e.2.clone(), e.3.clone())) 585 .collect::>(), 586 ); 587 let declared = o["verdict"].as_str().unwrap_or(""); 588 if declared != computed { 589 return Err(Reject::VerdictInconsistent { 590 declared: declared.to_string(), 591 computed: computed.to_string(), 592 }); 593 } 594 let digest = canonical_digest(bundle).map_err(|e| Reject::Schema(format!("{e}")))?; 595 Ok(Verified { 596 verdict: computed.to_string(), 597 digest, 598 checks: entries.len(), 599 required: entries.iter().filter(|e| e.1).count(), 600 cached: entries.iter().filter(|e| e.2 == "cached").count(), 601 plan_verdict: o 602 .get("plan") 603 .map(|p| p["verdict"].as_str().unwrap_or("NOT_RUN").to_string()), 604 scope, 605 }) 606 } 607 608 /// `--require-full`: at least one required check on backend `gb10` that ran 609 /// (or was resolved from cache: a gb10 result is never reused across heads, 610 /// so the cache entry is this commit's own GPU run). 611 /// 612 /// The verdict of that check is the verdict algebra's job, not this rule's: a 613 /// gb10 check that ran and FAILed makes the bundle FAIL (exit 1), which is a 614 /// truer answer than "no receipt"; a gb10 check that self-not-ran (exit 77, 615 /// e.g. the checkpoint is missing) is not a receipt either. 616 fn gpu_receipt(entries: &Entries) -> Result<(), Reject> { 617 if entries 618 .iter() 619 .any(|e| e.4 == "gb10" && e.1 && (e.2 == "run" || e.2 == "cached")) 620 { 621 return Ok(()); 622 } 623 let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new(); 624 for e in entries { 625 *counts.entry(e.4.as_str()).or_default() += 1; 626 } 627 let backends = if counts.is_empty() { 628 "none".to_string() 629 } else { 630 counts 631 .iter() 632 .map(|(b, n)| format!("{b}={n}")) 633 .collect::>() 634 .join(",") 635 }; 636 let gb10: Vec = entries 637 .iter() 638 .filter(|e| e.4 == "gb10") 639 .map(|e| { 640 format!( 641 "{} {} {}{}", 642 e.0, 643 e.2, 644 e.3, 645 if e.1 { "" } else { " (not required)" } 646 ) 647 }) 648 .collect(); 649 Err(Reject::NoGpuReceipt { 650 backends, 651 gb10: if gb10.is_empty() { 652 "none".to_string() 653 } else { 654 gb10.join(", ") 655 }, 656 }) 657 } 658 659 // ---------------------------------------------------------------- CLI 660 661 pub const USAGE: &str = "usage: 662 aien-test keygen KEY_FILE 663 aien-test bundle-sign BUNDLE.json --key KEY_FILE [--out SIGNED.json] 664 aien-test verify-bundle BUNDLE.json --repo github.com/OWNER/REPO --commit SHA40 --pubkey FILE_OR_HEX [--require GATE[,GATE...]] [--require-full] 665 --require-full: REJECTED unless the signed plan scope is full (an Alpha qualification) 666 and a required gb10 check passed on the GPU (NO_GPU_RECEIPT otherwise) 667 --allow-host-only: with --require-full, accept a full-scope PASS with no gb10 receipt. 668 Only for a repository whose own gate manifests declare no GPU gate; the 669 caller reads them, so a repository that declares one still needs its GPU run 670 exit: 0 PASS, 1 FAIL, 2 NOT_RUN or usage, 3 REJECTED"; 671 672 /// Flags of the bundle commands that take no value. 673 const BOOL_FLAGS: [&str; 2] = ["--require-full", "--allow-host-only"]; 674 675 pub fn is_bundle_command(name: &str) -> bool { 676 matches!(name, "keygen" | "bundle-sign" | "verify-bundle") 677 } 678 679 fn flag(argv: &[String], name: &str) -> Result, String> { 680 let mut it = argv.iter(); 681 while let Some(a) = it.next() { 682 if a == name { 683 return it 684 .next() 685 .cloned() 686 .map(Some) 687 .ok_or_else(|| format!("{name} needs a value")); 688 } 689 } 690 Ok(None) 691 } 692 693 fn read_json(path: &str) -> Result { 694 let txt = fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?; 695 serde_json::from_str(&txt).map_err(|e| format!("{path} is not JSON: {e}")) 696 } 697 698 /// `aien-test keygen|bundle-sign|verify-bundle ...`. Returns the exit code. 699 pub fn cli_main(argv: &[String]) -> i32 { 700 match cli_inner(argv) { 701 Ok(code) => code, 702 Err(e) => { 703 eprintln!("aien-test: {e}"); 704 eprintln!("{USAGE}"); 705 2 706 } 707 } 708 } 709 710 fn cli_inner(argv: &[String]) -> Result { 711 let name = argv.first().map(|s| s.as_str()).unwrap_or(""); 712 let positional: Vec<&String> = argv[1..] 713 .iter() 714 .enumerate() 715 .filter(|(i, a)| { 716 !a.starts_with("--") 717 && (*i == 0 718 || !argv[*i].starts_with("--") 719 || BOOL_FLAGS.contains(&argv[*i].as_str())) 720 }) 721 .map(|(_, a)| a) 722 .collect(); 723 match name { 724 "keygen" => { 725 let path = positional.first().ok_or("keygen needs KEY_FILE")?; 726 let pk = keygen(Path::new(path))?; 727 println!("pubkey {pk}"); 728 println!("key written to {path} (mode 0600); commit the pubkey as .aien/verify.pub, never the key"); 729 Ok(0) 730 } 731 "bundle-sign" => { 732 let path = positional.first().ok_or("bundle-sign needs BUNDLE.json")?; 733 let key_path = flag(&argv[1..], "--key")?.ok_or("bundle-sign needs --key KEY_FILE")?; 734 let out = flag(&argv[1..], "--out")?; 735 let bundle = read_json(path)?; 736 let key = load_signing_key(Path::new(&key_path))?; 737 let signed = sign(&bundle, &key).map_err(|r| format!("refusing to sign: {r}"))?; 738 let bytes = canonical(&signed).map_err(|e| format!("{e}"))?; 739 let digest = sha256_hex(&bytes); 740 let target = out.unwrap_or_else(|| path.to_string()); 741 fs::write(&target, &bytes).map_err(|e| format!("cannot write {target}: {e}"))?; 742 println!("signed {target} digest {digest}"); 743 Ok(0) 744 } 745 "verify-bundle" => { 746 let path = positional 747 .first() 748 .ok_or("verify-bundle needs BUNDLE.json")?; 749 let repository = flag(&argv[1..], "--repo")?.ok_or("verify-bundle needs --repo")?; 750 let commit = flag(&argv[1..], "--commit")?.ok_or("verify-bundle needs --commit")?; 751 let pubkey_arg = flag(&argv[1..], "--pubkey")?.ok_or("verify-bundle needs --pubkey")?; 752 let required = flag(&argv[1..], "--require")? 753 .map(|s| { 754 s.split(',') 755 .filter(|g| !g.is_empty()) 756 .map(|g| g.to_string()) 757 .collect() 758 }) 759 .unwrap_or_default(); 760 let pubkey_hex = load_pubkey_hex(&pubkey_arg)?; 761 let bundle = read_json(path)?; 762 let expect = Expect { 763 repository, 764 commit, 765 pubkey_hex, 766 required, 767 require_full: argv[1..].iter().any(|a| a == "--require-full"), 768 allow_host_only: argv[1..].iter().any(|a| a == "--allow-host-only"), 769 }; 770 match verify(&bundle, &expect) { 771 Ok(v) => { 772 let why = match (v.verdict.as_str(), v.gate_verdict()) { 773 ("PASS", "NOT_RUN") if v.required == 0 => { 774 " (no required checks: PASS only vacuously)".to_string() 775 } 776 ("PASS", "NOT_RUN") => { 777 format!(" (plan {})", v.plan_verdict.as_deref().unwrap_or("?")) 778 } 779 _ => String::new(), 780 }; 781 println!( 782 "AIEN Verification: {}{why} ({} checks, {} required, {} from cache) bundle {}", 783 v.gate_verdict(), v.checks, v.required, v.cached, v.digest 784 ); 785 Ok(match v.gate_verdict() { 786 "PASS" => 0, 787 "FAIL" => 1, 788 _ => 2, 789 }) 790 } 791 Err(r) => { 792 println!("AIEN Verification: REJECTED {}", r); 793 Ok(3) 794 } 795 } 796 } 797 _ => Err(format!("unknown command {name:?}")), 798 } 799 } 800 801 // ---------------------------------------------------------------- tests 802 803 #[cfg(test)] 804 mod tests { 805 use super::*; 806 807 const REPO: &str = "github.com/aien-dev/aien-architecture"; 808 const COMMIT: &str = "`d0f0b95d344b4c6628c3d868346932fd247ce168`"; 809 const H: &str = "`0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef`"; 810 811 fn key(seed: u8) -> SigningKey { 812 SigningKey::from_bytes(&[seed; 32]) 813 } 814 815 fn entry(gate: &str, exactness: &str, required: bool, status: &str, verdict: &str) -> Value { 816 let mut e = json!({ "gate": gate, "check_id": H, "exactness": exactness, "required": required, 817 "status": status, "verdict": verdict, "backend": "spark" }); 818 match status { 819 "run" => { 820 e["receipt"] = json!(H); 821 } 822 "cached" => { 823 e["resolution"] = 824 json!({ "resolved_from": H, "resolved_utc": "2026-10-04T10:00:00Z" }); 825 } 826 _ => {} 827 } 828 e 829 } 830 831 fn unsigned(sk: &SigningKey, checks: Vec, verdict: &str) -> Value { 832 json!({ 833 "schema": SCHEMA, "repository": REPO, "commit": COMMIT, "tree_digest": H, "graph_digest": H, 834 "receipt_id_scheme": "sha256-canonical-json", "checks": checks, "verdict": verdict, 835 "executor": { "id": fingerprint(&sk.verifying_key()), "class": "spark", "machine_digest": H }, 836 "started_utc": "2026-10-04T10:00:00Z", "finished_utc": "2026-10-04T10:05:00Z" 837 }) 838 } 839 840 fn good() -> (SigningKey, Value, Expect) { 841 let sk = key(7); 842 let b = unsigned( 843 &sk, 844 vec![ 845 entry("crumb.verify", "EXACT", true, "run", "PASS"), 846 entry("crypto.native", "EXACT", true, "cached", "PASS"), 847 entry("search.order", "ADVISORY", false, "run", "FAIL"), 848 ], 849 "PASS", 850 ); 851 let signed = sign(&b, &sk).expect("sign"); 852 let expect = Expect { 853 repository: REPO.to_string(), 854 commit: COMMIT.to_string(), 855 pubkey_hex: hex_encode(sk.verifying_key().as_bytes()), 856 required: vec!["crumb.verify".to_string(), "crypto.native".to_string()], 857 require_full: false, 858 allow_host_only: false, 859 }; 860 (sk, signed, expect) 861 } 862 863 #[test] 864 fn good_bundle_verifies_pass_and_advisory_fail_does_not_count() { 865 let (_, b, e) = good(); 866 let v = verify(&b, &e).expect("verifies"); 867 assert_eq!(v.verdict, "PASS"); 868 assert_eq!((v.checks, v.required, v.cached), (3, 2, 1)); 869 } 870 871 #[test] 872 fn key_order_in_the_file_does_not_matter() { 873 let (_, b, e) = good(); 874 // Re-encode with serde_json's own (unsorted, pretty) output: the verifier canonicalizes. 875 let pretty = serde_json::to_string_pretty(&b).unwrap(); 876 let again: Value = serde_json::from_str(&pretty).unwrap(); 877 assert!(verify(&again, &e).is_ok()); 878 } 879 880 #[test] 881 fn t11_tampered_verdict_is_rejected() { 882 let (_, mut b, e) = good(); 883 b["checks"][0]["verdict"] = json!("FAIL"); 884 b["verdict"] = json!("FAIL"); 885 assert_eq!(verify(&b, &e).unwrap_err(), Reject::BadSignature); 886 } 887 888 #[test] 889 fn t11_tampered_single_byte_in_commit_is_rejected() { 890 let (_, mut b, mut e) = good(); 891 let other = format!("e{}", &COMMIT[1..]); 892 b["commit"] = json!(other); 893 e.commit = other; 894 assert_eq!(verify(&b, &e).unwrap_err(), Reject::BadSignature); 895 } 896 897 #[test] 898 fn t12_bundle_from_another_commit_is_rejected() { 899 let (_, b, mut e) = good(); 900 e.commit = format!("e{}", &COMMIT[1..]); 901 assert!(matches!( 902 verify(&b, &e).unwrap_err(), 903 Reject::CommitMismatch { .. } 904 )); 905 } 906 907 #[test] 908 fn t13_bundle_from_another_repository_is_rejected() { 909 let (_, b, mut e) = good(); 910 e.repository = "github.com/aien-dev/omega".to_string(); 911 assert!(matches!( 912 verify(&b, &e).unwrap_err(), 913 Reject::RepositoryMismatch { .. } 914 )); 915 } 916 917 #[test] 918 fn t18_forged_bundle_signed_with_another_key_is_rejected() { 919 let (_, _, e) = good(); 920 let forger = key(9); 921 let b = unsigned( 922 &forger, 923 vec![ 924 entry("crumb.verify", "EXACT", true, "run", "PASS"), 925 entry("crypto.native", "EXACT", true, "run", "PASS"), 926 ], 927 "PASS", 928 ); 929 let forged = sign(&b, &forger).unwrap(); 930 assert_eq!(verify(&forged, &e).unwrap_err(), Reject::UnknownKey); 931 // Even if the forger pastes the real pubkey into the signature block, the signature fails. 932 let mut pasted = forged.clone(); 933 pasted["signature"]["pubkey"] = json!(e.pubkey_hex); 934 assert_eq!(verify(&pasted, &e).unwrap_err(), Reject::BadSignature); 935 } 936 937 #[test] 938 fn t18_executor_id_must_be_the_key_fingerprint() { 939 let sk = key(7); 940 let mut b = unsigned( 941 &sk, 942 vec![entry("crumb.verify", "EXACT", true, "run", "PASS")], 943 "PASS", 944 ); 945 b["executor"]["id"] = json!(H); 946 assert_eq!(sign(&b, &sk).unwrap_err(), Reject::UnknownExecutor); 947 } 948 949 #[test] 950 fn unsigned_bundle_is_rejected() { 951 let (sk, _, e) = good(); 952 let b = unsigned( 953 &sk, 954 vec![ 955 entry("crumb.verify", "EXACT", true, "run", "PASS"), 956 entry("crypto.native", "EXACT", true, "run", "PASS"), 957 ], 958 "PASS", 959 ); 960 assert!(matches!(verify(&b, &e).unwrap_err(), Reject::Schema(_))); 961 } 962 963 #[test] 964 fn t5_missing_required_check_blocks_pass() { 965 let (sk, _, e) = good(); 966 let b = sign( 967 &unsigned( 968 &sk, 969 vec![entry("crumb.verify", "EXACT", true, "run", "PASS")], 970 "PASS", 971 ), 972 &sk, 973 ) 974 .unwrap(); 975 assert_eq!( 976 verify(&b, &e).unwrap_err(), 977 Reject::MissingRequiredCheck("crypto.native".to_string()) 978 ); 979 } 980 981 #[test] 982 fn t6_fail_propagates_to_the_bundle_verdict() { 983 let entries = vec![ 984 (true, "run".to_string(), "PASS".to_string()), 985 (true, "run".to_string(), "FAIL".to_string()), 986 ]; 987 assert_eq!(compute_verdict(&entries), "FAIL"); 988 let (sk, _, _) = good(); 989 let b = unsigned( 990 &sk, 991 vec![ 992 entry("crumb.verify", "EXACT", true, "run", "PASS"), 993 entry("crypto.native", "EXACT", true, "run", "FAIL"), 994 ], 995 "PASS", 996 ); 997 assert!(matches!( 998 sign(&b, &sk).unwrap_err(), 999 Reject::VerdictInconsistent { .. } 1000 )); 1001 } 1002 1003 #[test] 1004 fn t7_not_run_never_becomes_pass() { 1005 let entries = vec![ 1006 (true, "run".to_string(), "PASS".to_string()), 1007 (true, "not_run".to_string(), "NOT_RUN".to_string()), 1008 ]; 1009 assert_eq!(compute_verdict(&entries), "NOT_RUN"); 1010 let blocked = vec![(true, "blocked".to_string(), "BLOCKED_HARDWARE".to_string())]; 1011 assert_eq!(compute_verdict(&blocked), "NOT_RUN"); 1012 // A not_run entry claiming PASS is malformed on its face. 1013 let (sk, _, _) = good(); 1014 let b = unsigned( 1015 &sk, 1016 vec![entry("kernel.qemu", "EXACT", true, "not_run", "PASS")], 1017 "PASS", 1018 ); 1019 assert!(matches!(sign(&b, &sk).unwrap_err(), Reject::Schema(_))); 1020 // And a worker cannot sign PASS over a NOT_RUN graph. 1021 let b = unsigned( 1022 &sk, 1023 vec![entry("kernel.qemu", "EXACT", true, "not_run", "NOT_RUN")], 1024 "PASS", 1025 ); 1026 assert!(matches!( 1027 sign(&b, &sk).unwrap_err(), 1028 Reject::VerdictInconsistent { .. } 1029 )); 1030 } 1031 1032 #[test] 1033 fn advisory_cannot_be_required_and_optional_entries_never_decide() { 1034 let (sk, _, _) = good(); 1035 let b = unsigned( 1036 &sk, 1037 vec![entry("search.order", "ADVISORY", true, "run", "PASS")], 1038 "PASS", 1039 ); 1040 assert!(matches!(sign(&b, &sk).unwrap_err(), Reject::Schema(_))); 1041 assert_eq!( 1042 compute_verdict(&[(false, "run".to_string(), "FAIL".to_string())]), 1043 "PASS" 1044 ); 1045 } 1046 1047 #[test] 1048 fn gate_required_list_overrides_a_bundle_that_marks_it_optional() { 1049 let (sk, _, e) = good(); 1050 let b = sign( 1051 &unsigned( 1052 &sk, 1053 vec![ 1054 entry("crumb.verify", "EXACT", true, "run", "PASS"), 1055 entry("crypto.native", "EXACT", false, "run", "FAIL"), 1056 ], 1057 "PASS", 1058 ), 1059 &sk, 1060 ) 1061 .unwrap(); 1062 assert!(matches!(verify(&b, &e).unwrap_err(), Reject::Schema(_))); 1063 } 1064 1065 #[test] 1066 fn keygen_writes_0600_and_refuses_overwrite() { 1067 use std::os::unix::fs::PermissionsExt; 1068 let dir = std::env::temp_dir().join(format!("aien-test-keygen-{}", std::process::id())); 1069 fs::create_dir_all(&dir).unwrap(); 1070 let p = dir.join("key"); 1071 let pk = keygen(&p).unwrap(); 1072 assert!(is_hex(&pk, 64)); 1073 assert_eq!( 1074 fs::metadata(&p).unwrap().permissions().mode() & 0o777, 1075 0o600 1076 ); 1077 assert!(keygen(&p).is_err()); 1078 let sk = load_signing_key(&p).unwrap(); 1079 assert_eq!(hex_encode(sk.verifying_key().as_bytes()), pk); 1080 fs::remove_dir_all(&dir).unwrap(); 1081 } 1082 1083 #[test] 1084 fn hex_roundtrip_and_rejects_odd_or_bad() { 1085 assert_eq!( 1086 hex_decode(&hex_encode(&[0, 1, 254, 255])).unwrap(), 1087 vec![0, 1, 254, 255] 1088 ); 1089 assert!(hex_decode("abc").is_none()); 1090 assert!(hex_decode("zz").is_none()); 1091 } 1092 1093 #[test] 1094 fn gate_verdict_is_never_a_vacuous_pass() { 1095 let v = |verdict: &str, required: usize, plan: Option<&str>| Verified { 1096 verdict: verdict.to_string(), 1097 digest: String::new(), 1098 checks: required, 1099 required, 1100 cached: 0, 1101 plan_verdict: plan.map(str::to_string), 1102 scope: SCOPE_CHANGED.to_string(), 1103 }; 1104 assert_eq!(v("PASS", 1, None).gate_verdict(), "PASS"); 1105 assert_eq!(v("PASS", 1, Some("PASS")).gate_verdict(), "PASS"); 1106 // Nothing required: PASS only vacuously. 1107 assert_eq!(v("PASS", 0, None).gate_verdict(), "NOT_RUN"); 1108 assert_eq!(v("PASS", 0, Some("PASS")).gate_verdict(), "NOT_RUN"); 1109 // The worker's plan says UNMAPPED or BLOCKED. 1110 assert_eq!(v("PASS", 2, Some("NOT_RUN")).gate_verdict(), "NOT_RUN"); 1111 assert_eq!( 1112 v("PASS", 2, Some("BLOCKED_OPERATOR")).gate_verdict(), 1113 "NOT_RUN" 1114 ); 1115 assert_eq!(v("FAIL", 2, Some("NOT_RUN")).gate_verdict(), "FAIL"); 1116 assert_eq!(v("NOT_RUN", 2, Some("PASS")).gate_verdict(), "NOT_RUN"); 1117 } 1118 1119 /// `good()`'s required checks with a `plan` member of `scope` (None: a 1120 /// plan written before scopes existed). 1121 fn scoped(sk: &SigningKey, scope: Option<&str>) -> Value { 1122 let mut b = unsigned( 1123 sk, 1124 vec![ 1125 entry("crumb.verify", "EXACT", true, "run", "PASS"), 1126 entry("crypto.native", "EXACT", true, "cached", "PASS"), 1127 ], 1128 "PASS", 1129 ); 1130 b["plan"] = json!({ "verdict": "PASS", "reason": "", "unmapped": [], "removed": [], "blocked": null }); 1131 if let Some(s) = scope { 1132 b["plan"]["scope"] = json!(s); 1133 } 1134 sign(&b, sk).expect("sign") 1135 } 1136 1137 /// One `checks[]` entry on backend `gb10`, the only backend that proves a 1138 /// GPU ran for this commit. 1139 fn gpu_check(gate: &str, required: bool, status: &str, verdict: &str) -> Value { 1140 let mut e = entry(gate, "EXACT", required, status, verdict); 1141 e["backend"] = json!("gb10"); 1142 e 1143 } 1144 1145 /// A full-scope bundle: `good()`'s two required host checks plus `extra`, 1146 /// declaring `verdict`. 1147 fn full_scope(sk: &SigningKey, extra: Vec, verdict: &str) -> Value { 1148 let mut checks = vec![ 1149 entry("crumb.verify", "EXACT", true, "run", "PASS"), 1150 entry("crypto.native", "EXACT", true, "cached", "PASS"), 1151 ]; 1152 checks.extend(extra); 1153 let mut b = unsigned(sk, checks, verdict); 1154 b["plan"] = json!({ "verdict": "PASS", "scope": "full" }); 1155 sign(&b, sk).expect("sign") 1156 } 1157 1158 #[test] 1159 fn a_full_scope_bundle_without_a_gpu_check_is_not_an_alpha() { 1160 let (sk, _, e) = good(); 1161 let mut strict = e.clone(); 1162 strict.require_full = true; 1163 out_of_scope_either_way(&sk, &strict); 1164 let r = verify(&full_scope(&sk, vec![], "PASS"), &strict).unwrap_err(); 1165 assert_eq!( 1166 r, 1167 Reject::NoGpuReceipt { 1168 backends: "spark=2".to_string(), 1169 gb10: "none".to_string() 1170 } 1171 ); 1172 assert_eq!(r.code(), "NO_GPU_RECEIPT"); 1173 assert_eq!( 1174 format!("AIEN Verification: REJECTED {r}"), 1175 "AIEN Verification: REJECTED NO_GPU_RECEIPT: an Alpha needs a required check on \ 1176 backend gb10 that ran on the Spark's GPU, and this full-scope bundle has none \ 1177 (checks by backend: spark=2; gb10 checks: none)" 1178 ); 1179 } 1180 1181 /// A repository whose own gate manifests declare no GPU gate can still be 1182 /// an Alpha: the caller reads those manifests and passes --allow-host-only. 1183 /// The same bundle without the flag stays rejected, so the flag is a 1184 /// caller decision about the repository, never a property of the bundle. 1185 #[test] 1186 fn allow_host_only_accepts_a_host_scope_pass_only_when_the_caller_says_so() { 1187 let (sk, _, e) = good(); 1188 let mut strict = e.clone(); 1189 strict.require_full = true; 1190 let b = full_scope(&sk, vec![], "PASS"); 1191 assert_eq!(verify(&b, &strict).unwrap_err().code(), "NO_GPU_RECEIPT"); 1192 let mut host_only = strict.clone(); 1193 host_only.allow_host_only = true; 1194 let v = verify(&b, &host_only).expect("host-only Alpha for a repository with no GPU gate"); 1195 assert_eq!((v.scope.as_str(), v.gate_verdict()), ("full", "PASS")); 1196 // A gb10 check that ran is a receipt whatever its verdict: the bundle is 1197 // then simply FAIL, and the flag never turns a failure into an Alpha. 1198 let failing = full_scope( 1199 &sk, 1200 vec![gpu_check("gpu.serve-chat", true, "run", "FAIL")], 1201 "FAIL", 1202 ); 1203 assert_eq!( 1204 verify(&failing, &host_only) 1205 .expect("a gb10 check ran, so there is a receipt to judge") 1206 .gate_verdict(), 1207 "FAIL" 1208 ); 1209 } 1210 1211 /// The scope is reported first: a `changed` bundle is refused as such, 1212 /// though it could not be an Alpha for the second reason either. The 1213 /// `--require-full` flag never turns either into a PASS. 1214 fn out_of_scope_either_way(sk: &SigningKey, strict: &Expect) { 1215 assert_eq!( 1216 verify(&scoped(sk, Some("changed")), strict).unwrap_err(), 1217 Reject::NotFullScope("changed".to_string()) 1218 ); 1219 assert_eq!( 1220 verify(&full_scope(sk, vec![], "PASS"), strict) 1221 .unwrap_err() 1222 .code(), 1223 "NO_GPU_RECEIPT" 1224 ); 1225 } 1226 1227 #[test] 1228 fn a_required_gb10_check_that_ran_is_the_receipt() { 1229 let (sk, _, e) = good(); 1230 let mut strict = e.clone(); 1231 strict.require_full = true; 1232 // Ran here, or resolved from cache: a gb10 result is never reused 1233 // across heads, so both name this commit's own GPU run. 1234 for status in ["run", "cached"] { 1235 let b = full_scope( 1236 &sk, 1237 vec![gpu_check("gpu.serve-chat", true, status, "PASS")], 1238 "PASS", 1239 ); 1240 let v = verify(&b, &strict).expect("a GPU receipt"); 1241 assert_eq!((v.scope.as_str(), v.gate_verdict()), ("full", "PASS")); 1242 } 1243 // A gb10 check that ran and FAILed is still a receipt: the bundle is 1244 // FAIL (exit 1), which says more than "no GPU run". 1245 let b = full_scope( 1246 &sk, 1247 vec![gpu_check("gpu.serve-chat", true, "run", "FAIL")], 1248 "FAIL", 1249 ); 1250 let v = verify(&b, &strict).expect("a GPU receipt, failed"); 1251 assert_eq!(v.gate_verdict(), "FAIL"); 1252 } 1253 1254 #[test] 1255 fn an_optional_or_self_not_run_gb10_check_is_not_a_receipt() { 1256 let (sk, _, e) = good(); 1257 let mut strict = e.clone(); 1258 strict.require_full = true; 1259 // Optional: the algebra ignores it, so it proves nothing. 1260 let r = verify( 1261 &full_scope( 1262 &sk, 1263 vec![gpu_check("gpu.serve-chat", false, "run", "PASS")], 1264 "PASS", 1265 ), 1266 &strict, 1267 ) 1268 .unwrap_err(); 1269 assert_eq!( 1270 r, 1271 Reject::NoGpuReceipt { 1272 backends: "gb10=1,spark=2".to_string(), 1273 gb10: "gpu.serve-chat run PASS (not required)".to_string() 1274 } 1275 ); 1276 // Self-not-run (exit 77: the checkpoint is missing or the chip is too 1277 // short on memory): the gate did not test the GPU. 1278 let r = verify( 1279 &full_scope( 1280 &sk, 1281 vec![gpu_check("gpu.serve-chat", true, "not_run", "NOT_RUN")], 1282 "NOT_RUN", 1283 ), 1284 &strict, 1285 ) 1286 .unwrap_err(); 1287 assert_eq!( 1288 r, 1289 Reject::NoGpuReceipt { 1290 backends: "gb10=1,spark=2".to_string(), 1291 gb10: "gpu.serve-chat not_run NOT_RUN".to_string() 1292 } 1293 ); 1294 } 1295 1296 #[test] 1297 fn a_bundle_without_a_scope_is_changed_scope() { 1298 let (sk, old, e) = good(); 1299 // No `plan` at all, and a `plan` written before scopes existed. 1300 assert_eq!(scope_of(&old), SCOPE_CHANGED); 1301 assert_eq!(verify(&old, &e).unwrap().scope, "changed"); 1302 let b = scoped(&sk, None); 1303 assert_eq!(scope_of(&b), SCOPE_CHANGED); 1304 let v = verify(&b, &e).unwrap(); 1305 assert_eq!((v.scope.as_str(), v.gate_verdict()), ("changed", "PASS")); 1306 let v = verify(&scoped(&sk, Some("full")), &e).unwrap(); 1307 assert_eq!((v.scope.as_str(), v.gate_verdict()), ("full", "PASS")); 1308 // Any other scope is not a bundle this verifier reads. 1309 let mut bad = unsigned(&sk, vec![], "PASS"); 1310 bad["plan"] = json!({ "verdict": "PASS", "scope": "everything" }); 1311 assert!(matches!(sign(&bad, &sk).unwrap_err(), Reject::Schema(_))); 1312 } 1313 1314 #[test] 1315 fn the_scope_is_signed() { 1316 let (sk, _, e) = good(); 1317 let mut b = scoped(&sk, Some("changed")); 1318 b["plan"]["scope"] = json!("full"); 1319 assert_eq!(verify(&b, &e).unwrap_err(), Reject::BadSignature); 1320 let mut b = scoped(&sk, None); 1321 b["plan"]["scope"] = json!("full"); 1322 assert_eq!(verify(&b, &e).unwrap_err(), Reject::BadSignature); 1323 let mut b = scoped(&sk, Some("full")); 1324 b["plan"]["scope"] = json!("changed"); 1325 assert_eq!(verify(&b, &e).unwrap_err(), Reject::BadSignature); 1326 } 1327 1328 #[test] 1329 fn require_full_rejects_a_changed_scope_pass_with_exit_3() { 1330 let (sk, old, e) = good(); 1331 let dir = crate::testutil::TempDir::new("verify-bundle-full"); 1332 let write = |name: &str, b: &Value| { 1333 let p = dir.path().join(name); 1334 fs::write(&p, canonical(b).unwrap()).unwrap(); 1335 p.display().to_string() 1336 }; 1337 let changed = write("changed.json", &scoped(&sk, Some("changed"))); 1338 let unscoped = write("unscoped.json", &old); 1339 // Full scope and every check PASS, but no gb10 check: not an Alpha. 1340 let host_only = write("host-only.json", &scoped(&sk, Some("full"))); 1341 let full = write( 1342 "full.json", 1343 &full_scope( 1344 &sk, 1345 vec![gpu_check("gpu.serve-chat", true, "run", "PASS")], 1346 "PASS", 1347 ), 1348 ); 1349 let run = |path: &str, require_full: bool| { 1350 let mut argv = vec!["verify-bundle".to_string()]; 1351 // The bool flag before the file must not swallow it. 1352 if require_full { 1353 argv.push("--require-full".to_string()); 1354 } 1355 argv.extend( 1356 [ 1357 path, 1358 "--repo", 1359 REPO, 1360 "--commit", 1361 COMMIT, 1362 "--pubkey", 1363 &e.pubkey_hex, 1364 ] 1365 .map(str::to_string), 1366 ); 1367 cli_main(&argv) 1368 }; 1369 assert_eq!(run(&changed, false), 0); 1370 assert_eq!(run(&changed, true), 3); 1371 assert_eq!(run(&unscoped, true), 3); 1372 assert_eq!(run(&host_only, false), 0); 1373 assert_eq!(run(&host_only, true), 3); 1374 assert_eq!(run(&full, true), 0); 1375 assert_eq!(run(&full, false), 0); 1376 let mut strict = e.clone(); 1377 strict.require_full = true; 1378 let r = verify(&scoped(&sk, Some("changed")), &strict).unwrap_err(); 1379 assert_eq!(r, Reject::NotFullScope("changed".to_string())); 1380 assert_eq!(r.code(), "NOT_FULL_SCOPE"); 1381 assert_eq!( 1382 format!("AIEN Verification: REJECTED {r}"), 1383 "AIEN Verification: REJECTED NOT_FULL_SCOPE: plan scope is changed, not a full-scope (Alpha) qualification" 1384 ); 1385 assert_eq!( 1386 verify( 1387 &full_scope( 1388 &sk, 1389 vec![gpu_check("gpu.serve-chat", true, "run", "PASS")], 1390 "PASS" 1391 ), 1392 &strict 1393 ) 1394 .unwrap() 1395 .scope, 1396 "full" 1397 ); 1398 } 1399 }