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-protocols-mv/blob/main/crates/aien-evaluation-protocol/src/lib.rs # aien-protocols-mv Canonical specifications, wire protocols, and schemas for the AIEN sovereign ecosystem 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-protocols-mv / crates / aien-evaluation-protocol / src / lib.rs` 894 lines ยท 31475 bytes Raw Blame History 1 use aien_protocol_types::{ArtifactRef, Digest32, EvaluationId, Timestamp}; 2 use p256::ecdsa::signature::{Signer, Verifier}; 3 use p256::ecdsa::{Signature, SigningKey, VerifyingKey}; 4 use serde::{Deserialize, Serialize}; 5 use sha2::{Digest, Sha256}; 6 use std::collections::{HashMap, HashSet}; 7 use std::future::Future; 8 use std::sync::Arc; 9 10 mod adaptive; 11 pub use adaptive::*; 12 13 /// First receipt protocol version using unambiguous, domain-separated digests. 14 pub const FRAMED_RECEIPT_PROTOCOL_VERSION: u32 = 3; 15 16 fn hash_str(hasher: &mut Sha256, value: &str) { 17 hasher.update((value.len() as u64).to_le_bytes()); 18 hasher.update(value.as_bytes()); 19 } 20 21 fn hash_count(hasher: &mut Sha256, count: usize) { 22 hasher.update((count as u64).to_le_bytes()); 23 } 24 25 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 26 pub struct EvaluationClaim { 27 pub claim_type: String, 28 pub statement: String, 29 } 30 31 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 32 pub struct EvaluationRequest { 33 pub protocol_version: u32, 34 pub request_id: EvaluationId, 35 pub proposer: String, 36 pub subject: ArtifactRef, 37 pub parent: Option, 38 pub profile: String, 39 pub claims: Vec, 40 pub nonce: [u8; 32], 41 } 42 43 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 44 pub struct EvaluatorDescriptor { 45 pub evaluator_id: String, 46 pub version: String, 47 pub required: bool, 48 } 49 50 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 51 pub struct EvaluationPlan { 52 pub evaluation_id: EvaluationId, 53 pub subject: ArtifactRef, 54 pub profile: String, 55 pub evaluators: Vec, 56 pub baseline: Option, 57 pub sandbox_profile: String, 58 pub policy_digest: Digest32, 59 pub evaluator_manifest_digest: Digest32, 60 pub plan_digest: Digest32, 61 } 62 63 impl EvaluationPlan { 64 /// Computes the deterministic SHA-256 digest of the evaluation plan. 65 pub fn compute_plan_digest(&self) -> Digest32 { 66 let mut hasher = Sha256::new(); 67 hasher.update(b"AIEN_EVALUATION_PLAN_V2\0"); 68 hasher.update(self.evaluation_id.0.as_bytes()); 69 hasher.update(self.subject.artifact_id.as_bytes()); 70 hasher.update(self.subject.digest.0); 71 hash_str(&mut hasher, &self.profile); 72 73 // The total ordering avoids caller-dependent hashes for equal IDs. 74 let mut sorted_evals: Vec<_> = self.evaluators.iter().collect(); 75 sorted_evals.sort_by(|a, b| { 76 (&a.evaluator_id, &a.version, a.required).cmp(&( 77 &b.evaluator_id, 78 &b.version, 79 b.required, 80 )) 81 }); 82 hash_count(&mut hasher, sorted_evals.len()); 83 for eval in &sorted_evals { 84 hash_str(&mut hasher, &eval.evaluator_id); 85 hash_str(&mut hasher, &eval.version); 86 hasher.update([u8::from(eval.required)]); 87 } 88 89 match &self.baseline { 90 Some(base) => { 91 hasher.update([1]); 92 hasher.update(base.artifact_id.as_bytes()); 93 hasher.update(base.digest.0); 94 } 95 None => hasher.update([0]), 96 } 97 98 hash_str(&mut hasher, &self.sandbox_profile); 99 hasher.update(self.policy_digest.0); 100 hasher.update(self.evaluator_manifest_digest.0); 101 102 let result: [u8; 32] = hasher.finalize().into(); 103 Digest32(result) 104 } 105 106 /// Verifies that the plan digest strictly matches its computed content. 107 pub fn verify_plan_digest(&self) -> bool { 108 self.plan_digest == self.compute_plan_digest() 109 } 110 111 /// Asserts that a proposed candidate plan preserves all frozen invariants of this authoritative plan. 112 pub fn assert_frozen_invariants( 113 &self, 114 candidate_plan: &EvaluationPlan, 115 ) -> Result<(), EvaluationError> { 116 if !self.verify_plan_digest() { 117 return Err(EvaluationError::PlanDigestMismatch); 118 } 119 if !candidate_plan.verify_plan_digest() { 120 return Err(EvaluationError::PlanDigestMismatch); 121 } 122 if self.plan_digest != candidate_plan.plan_digest { 123 return Err(EvaluationError::PlanTamperingDetected(format!( 124 "Plan digest altered: authoritative {} vs candidate {}", 125 hex::encode(self.plan_digest.0), 126 hex::encode(candidate_plan.plan_digest.0) 127 ))); 128 } 129 if self.policy_digest != candidate_plan.policy_digest { 130 return Err(EvaluationError::PolicyTamperingDetected(format!( 131 "Policy digest altered: authoritative {} vs candidate {}", 132 hex::encode(self.policy_digest.0), 133 hex::encode(candidate_plan.policy_digest.0) 134 ))); 135 } 136 if self.evaluator_manifest_digest != candidate_plan.evaluator_manifest_digest { 137 return Err(EvaluationError::ManifestTamperingDetected(format!( 138 "Evaluator manifest digest altered: authoritative {} vs candidate {}", 139 hex::encode(self.evaluator_manifest_digest.0), 140 hex::encode(candidate_plan.evaluator_manifest_digest.0) 141 ))); 142 } 143 if self.baseline != candidate_plan.baseline { 144 return Err(EvaluationError::BaselineTamperingDetected( 145 "Baseline artifact reference altered".to_string(), 146 )); 147 } 148 if self.evaluators != candidate_plan.evaluators { 149 return Err(EvaluationError::EvaluatorTamperingDetected( 150 "Evaluator descriptors list altered".to_string(), 151 )); 152 } 153 Ok(()) 154 } 155 } 156 157 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 158 pub struct EvaluatorIdentity { 159 pub evaluator_id: String, 160 pub version: String, 161 pub binary_digest: Digest32, 162 pub config_digest: Digest32, 163 } 164 165 #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] 166 pub enum EvaluatorStatus { 167 Passed, 168 Failed, 169 Inconclusive, 170 TimedOut, 171 } 172 173 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 174 pub struct Finding { 175 pub severity: String, 176 pub rule_id: String, 177 pub message: String, 178 pub location: Option, 179 } 180 181 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] 182 pub struct Measurement { 183 pub metric: String, 184 pub value: f64, 185 pub unit: String, 186 } 187 188 #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] 189 pub struct EvaluatorOutcome { 190 pub evaluator: EvaluatorIdentity, 191 pub status: EvaluatorStatus, 192 pub findings: Vec, 193 pub measurements: Vec, 194 pub evidence: Vec, 195 pub execution_digest: Digest32, 196 } 197 198 impl EvaluatorOutcome { 199 pub fn compute_execution_digest(&self) -> Digest32 { 200 let mut hasher = Sha256::new(); 201 hasher.update(b"AIEN_EVALUATOR_OUTCOME_V2\0"); 202 hash_str(&mut hasher, &self.evaluator.evaluator_id); 203 hash_str(&mut hasher, &self.evaluator.version); 204 hasher.update(self.evaluator.binary_digest.0); 205 hasher.update(self.evaluator.config_digest.0); 206 let status_code: u8 = match self.status { 207 EvaluatorStatus::Passed => 0, 208 EvaluatorStatus::Failed => 1, 209 EvaluatorStatus::Inconclusive => 2, 210 EvaluatorStatus::TimedOut => 3, 211 }; 212 hasher.update([status_code]); 213 214 hash_count(&mut hasher, self.findings.len()); 215 for f in &self.findings { 216 hash_str(&mut hasher, &f.severity); 217 hash_str(&mut hasher, &f.rule_id); 218 hash_str(&mut hasher, &f.message); 219 match &f.location { 220 Some(loc) => { 221 hasher.update([1]); 222 hash_str(&mut hasher, loc); 223 } 224 None => hasher.update([0]), 225 } 226 } 227 228 hash_count(&mut hasher, self.measurements.len()); 229 for m in &self.measurements { 230 hash_str(&mut hasher, &m.metric); 231 hasher.update(m.value.to_bits().to_le_bytes()); 232 hash_str(&mut hasher, &m.unit); 233 } 234 235 hash_count(&mut hasher, self.evidence.len()); 236 for ev in &self.evidence { 237 hasher.update(ev.artifact_id.as_bytes()); 238 hasher.update(ev.digest.0); 239 } 240 let result: [u8; 32] = hasher.finalize().into(); 241 Digest32(result) 242 } 243 } 244 245 #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] 246 pub enum Verdict { 247 Pass, 248 Fail, 249 Indeterminate, 250 } 251 252 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 253 pub struct VerifierIdentity { 254 pub principal_id: String, 255 pub key_id: String, 256 pub trust_epoch: u64, 257 pub trusted_build_digest: Digest32, 258 pub policy_bundle_digest: Digest32, 259 } 260 261 #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] 262 pub enum CryptographicTier { 263 /// Tier 1: Algorithm/digest only (SHA-256). 264 Tier1AlgorithmOnly, 265 /// Tier 2: Software key signing (in-memory ECDSA P-256). 266 Tier2SoftwareKey, 267 /// Tier 3: Host OS key (file or daemon key). 268 Tier3HostOsKey, 269 /// Tier 4: Hardware TPM 2.0 bound key (/dev/tpmrm0 ECDSA P-256). 270 Tier4HardwareTpm, 271 } 272 273 impl CryptographicTier { 274 pub fn as_str(&self) -> &str { 275 match self { 276 Self::Tier1AlgorithmOnly => "tier1-algo", 277 Self::Tier2SoftwareKey => "tier2-software", 278 Self::Tier3HostOsKey => "tier3-host-os", 279 Self::Tier4HardwareTpm => "tier4-hardware-tpm", 280 } 281 } 282 } 283 284 /// Abstract verifier signing authority whose implementation strictly dictates its own cryptographic tier. 285 pub trait VerifierSigner: Send + Sync { 286 fn cryptographic_tier(&self) -> CryptographicTier; 287 fn key_fingerprint(&self) -> String; 288 fn sign_digest(&self, digest: &[u8; 32]) -> Result, EvaluationError>; 289 fn verifying_key(&self) -> VerifyingKey; 290 } 291 292 /// Software in-memory ECDSA P-256 signer (strictly Tier 2). 293 pub struct SoftwareP256Signer { 294 signing_key: SigningKey, 295 fingerprint: String, 296 } 297 298 impl SoftwareP256Signer { 299 pub fn new(signing_key: SigningKey) -> Self { 300 let verifying_key = VerifyingKey::from(&signing_key); 301 let fingerprint = hex::encode(Sha256::digest(verifying_key.to_sec1_point(true).as_bytes())); 302 Self { 303 signing_key, 304 fingerprint, 305 } 306 } 307 } 308 309 impl VerifierSigner for SoftwareP256Signer { 310 fn cryptographic_tier(&self) -> CryptographicTier { 311 CryptographicTier::Tier2SoftwareKey 312 } 313 314 fn key_fingerprint(&self) -> String { 315 self.fingerprint.clone() 316 } 317 318 fn sign_digest(&self, digest: &[u8; 32]) -> Result, EvaluationError> { 319 let sig: Signature = self.signing_key.sign(digest); 320 Ok(sig.to_bytes().to_vec()) 321 } 322 323 fn verifying_key(&self) -> VerifyingKey { 324 VerifyingKey::from(&self.signing_key) 325 } 326 } 327 328 /// Hardware TPM 2.0 bound key signer (strictly Tier 4). 329 /// The private key resides strictly within the TPM 2.0 hardware microcontroller 330 /// and never touches host memory. Signing executes directly on the physical TPM chip. 331 pub struct TpmP256Signer { 332 device_path: String, 333 key_context_path: std::path::PathBuf, 334 verifying_key: VerifyingKey, 335 fingerprint: String, 336 } 337 338 impl TpmP256Signer { 339 /// Connects to a physical TPM 2.0 device and provisions a hardware-bound ECC key in silicon. 340 pub fn connect(device_path: impl Into) -> Result { 341 let dev = device_path.into(); 342 let tpm_dir = std::env::temp_dir().join(format!("aien-tpm-{}", uuid::Uuid::new_v4())); 343 std::fs::create_dir_all(&tpm_dir).map_err(|e| { 344 EvaluationError::ExecutionFailed(format!("Failed to create TPM work dir: {}", e)) 345 })?; 346 347 let primary_ctx = tpm_dir.join("primary.ctx"); 348 let key_pub = tpm_dir.join("key.pub"); 349 let key_priv = tpm_dir.join("key.priv"); 350 let key_ctx = tpm_dir.join("key.ctx"); 351 let pub_pem = tpm_dir.join("pub.pem"); 352 353 // 1. Create primary key in owner hierarchy 354 let out1 = std::process::Command::new("tpm2_createprimary") 355 .args([ 356 "-C", 357 "o", 358 "-g", 359 "sha256", 360 "-G", 361 "ecc", 362 "-c", 363 primary_ctx.to_str().unwrap(), 364 ]) 365 .output() 366 .map_err(|e| { 367 EvaluationError::ExecutionFailed(format!("TPM createprimary failed: {}", e)) 368 })?; 369 if !out1.status.success() { 370 return Err(EvaluationError::ExecutionFailed(format!( 371 "TPM createprimary error: {}", 372 String::from_utf8_lossy(&out1.stderr) 373 ))); 374 } 375 376 // 2. Create ECC key in silicon 377 let out2 = std::process::Command::new("tpm2_create") 378 .args([ 379 "-C", 380 primary_ctx.to_str().unwrap(), 381 "-g", 382 "sha256", 383 "-G", 384 "ecc256", 385 "-u", 386 key_pub.to_str().unwrap(), 387 "-r", 388 key_priv.to_str().unwrap(), 389 ]) 390 .output() 391 .map_err(|e| { 392 EvaluationError::ExecutionFailed(format!("TPM create key failed: {}", e)) 393 })?; 394 if !out2.status.success() { 395 return Err(EvaluationError::ExecutionFailed(format!( 396 "TPM create key error: {}", 397 String::from_utf8_lossy(&out2.stderr) 398 ))); 399 } 400 401 // 3. Load key into TPM microcontroller 402 let out3 = std::process::Command::new("tpm2_load") 403 .args([ 404 "-C", 405 primary_ctx.to_str().unwrap(), 406 "-u", 407 key_pub.to_str().unwrap(), 408 "-r", 409 key_priv.to_str().unwrap(), 410 "-c", 411 key_ctx.to_str().unwrap(), 412 ]) 413 .output() 414 .map_err(|e| EvaluationError::ExecutionFailed(format!("TPM load failed: {}", e)))?; 415 if !out3.status.success() { 416 return Err(EvaluationError::ExecutionFailed(format!( 417 "TPM load error: {}", 418 String::from_utf8_lossy(&out3.stderr) 419 ))); 420 } 421 422 // 4. Read public key from TPM in PEM format 423 let out4 = std::process::Command::new("tpm2_readpublic") 424 .args([ 425 "-c", 426 key_ctx.to_str().unwrap(), 427 "-o", 428 pub_pem.to_str().unwrap(), 429 "-f", 430 "pem", 431 ]) 432 .output() 433 .map_err(|e| { 434 EvaluationError::ExecutionFailed(format!("TPM readpublic failed: {}", e)) 435 })?; 436 if !out4.status.success() { 437 return Err(EvaluationError::ExecutionFailed(format!( 438 "TPM readpublic error: {}", 439 String::from_utf8_lossy(&out4.stderr) 440 ))); 441 } 442 443 let pem_str = std::fs::read_to_string(&pub_pem).map_err(|e| { 444 EvaluationError::ExecutionFailed(format!("Failed to read TPM pubkey PEM: {}", e)) 445 })?; 446 447 use p256::pkcs8::DecodePublicKey; 448 let verifying_key = VerifyingKey::from_public_key_pem(&pem_str).map_err(|e| { 449 EvaluationError::ExecutionFailed(format!("Failed to parse TPM pubkey: {}", e)) 450 })?; 451 452 let fingerprint = hex::encode(Sha256::digest(verifying_key.to_sec1_point(true).as_bytes())); 453 454 Ok(Self { 455 device_path: dev, 456 key_context_path: key_ctx, 457 verifying_key, 458 fingerprint, 459 }) 460 } 461 462 pub fn from_existing_context( 463 device_path: impl Into, 464 key_context_path: std::path::PathBuf, 465 verifying_key: VerifyingKey, 466 ) -> Self { 467 let fingerprint = hex::encode(Sha256::digest(verifying_key.to_sec1_point(true).as_bytes())); 468 Self { 469 device_path: device_path.into(), 470 key_context_path, 471 verifying_key, 472 fingerprint, 473 } 474 } 475 476 pub fn device_path(&self) -> &str { 477 &self.device_path 478 } 479 } 480 481 impl VerifierSigner for TpmP256Signer { 482 fn cryptographic_tier(&self) -> CryptographicTier { 483 CryptographicTier::Tier4HardwareTpm 484 } 485 486 fn key_fingerprint(&self) -> String { 487 self.fingerprint.clone() 488 } 489 490 fn sign_digest(&self, digest: &[u8; 32]) -> Result, EvaluationError> { 491 let digest_tmp = std::env::temp_dir().join(format!("tpm-in-{}.bin", uuid::Uuid::new_v4())); 492 let sig_tmp = std::env::temp_dir().join(format!("tpm-out-{}.bin", uuid::Uuid::new_v4())); 493 494 std::fs::write(&digest_tmp, digest).map_err(|e| { 495 EvaluationError::ExecutionFailed(format!("Failed to write digest: {}", e)) 496 })?; 497 498 let out = std::process::Command::new("tpm2_sign") 499 .args([ 500 "-c", 501 self.key_context_path.to_str().unwrap(), 502 "-g", 503 "sha256", 504 "-o", 505 sig_tmp.to_str().unwrap(), 506 "-f", 507 "plain", 508 digest_tmp.to_str().unwrap(), 509 ]) 510 .output() 511 .map_err(|e| EvaluationError::ExecutionFailed(format!("TPM sign failed: {}", e)))?; 512 513 let _ = std::fs::remove_file(&digest_tmp); 514 515 if !out.status.success() { 516 let _ = std::fs::remove_file(&sig_tmp); 517 return Err(EvaluationError::ExecutionFailed(format!( 518 "TPM sign command failed: {}", 519 String::from_utf8_lossy(&out.stderr) 520 ))); 521 } 522 523 let der_sig = std::fs::read(&sig_tmp).map_err(|e| { 524 EvaluationError::ExecutionFailed(format!("Failed to read TPM signature: {}", e)) 525 })?; 526 let _ = std::fs::remove_file(&sig_tmp); 527 528 let signature = Signature::from_der(&der_sig).map_err(|e| { 529 EvaluationError::ExecutionFailed(format!("Failed to parse TPM DER signature: {}", e)) 530 })?; 531 532 Ok(signature.to_bytes().to_vec()) 533 } 534 535 fn verifying_key(&self) -> VerifyingKey { 536 self.verifying_key 537 } 538 } 539 540 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 541 pub struct EvaluationReceipt { 542 pub protocol_version: u32, 543 pub evaluation_id: EvaluationId, 544 pub request_digest: Digest32, 545 pub subject_digest: Digest32, 546 pub plan_digest: Digest32, 547 pub evidence_root: Digest32, 548 pub outcomes_root: Digest32, 549 pub verdict: Verdict, 550 pub verifier: VerifierIdentity, 551 pub started_at: Timestamp, 552 pub completed_at: Timestamp, 553 } 554 555 impl EvaluationReceipt { 556 pub fn compute_receipt_digest(&self) -> Digest32 { 557 let mut hasher = Sha256::new(); 558 hasher.update(b"AIEN_EVALUATION_RECEIPT_V3\0"); 559 hasher.update(self.protocol_version.to_le_bytes()); 560 hasher.update(self.evaluation_id.0.as_bytes()); 561 hasher.update(self.request_digest.0); 562 hasher.update(self.subject_digest.0); 563 hasher.update(self.plan_digest.0); 564 hasher.update(self.evidence_root.0); 565 hasher.update(self.outcomes_root.0); 566 567 let verdict_byte = match self.verdict { 568 Verdict::Pass => 0u8, 569 Verdict::Fail => 1u8, 570 Verdict::Indeterminate => 2u8, 571 }; 572 hasher.update([verdict_byte]); 573 574 hash_str(&mut hasher, &self.verifier.principal_id); 575 hash_str(&mut hasher, &self.verifier.key_id); 576 hasher.update(self.verifier.trust_epoch.to_le_bytes()); 577 hasher.update(self.verifier.trusted_build_digest.0); 578 hasher.update(self.verifier.policy_bundle_digest.0); 579 580 hasher.update(self.started_at.0.to_le_bytes()); 581 hasher.update(self.completed_at.0.to_le_bytes()); 582 583 let result: [u8; 32] = hasher.finalize().into(); 584 Digest32(result) 585 } 586 587 /// Signs the receipt using an authoritative VerifierSigner. 588 /// Cryptographic tier and key fingerprint are strictly governed by the signer implementation. 589 pub fn sign_with_signer( 590 &self, 591 signer: &dyn VerifierSigner, 592 ) -> Result { 593 if self.protocol_version != FRAMED_RECEIPT_PROTOCOL_VERSION { 594 return Err(EvaluationError::UnsupportedProtocolVersion( 595 self.protocol_version, 596 )); 597 } 598 let fingerprint = signer.key_fingerprint(); 599 if self.verifier.key_id != fingerprint { 600 return Err(EvaluationError::KeyIdentityMismatch { 601 expected: self.verifier.key_id.clone(), 602 actual: fingerprint, 603 }); 604 } 605 606 let digest = self.compute_receipt_digest(); 607 let sig_bytes = signer.sign_digest(&digest.0)?; 608 let tier = signer.cryptographic_tier(); 609 610 Ok(SignedEvaluationReceipt { 611 receipt: self.clone(), 612 signature: sig_bytes, 613 cryptographic_tier: tier, 614 key_fingerprint: fingerprint, 615 }) 616 } 617 } 618 619 #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] 620 pub struct SignedEvaluationReceipt { 621 pub receipt: EvaluationReceipt, 622 pub signature: Vec, 623 pub cryptographic_tier: CryptographicTier, 624 pub key_fingerprint: String, 625 } 626 627 /// Fingerprint of a P-256 verifying key: hex SHA-256 of the compressed SEC1 point. 628 /// Same derivation the signers use (SoftwareP256Signer::new, lib.rs:270). 629 pub fn verifying_key_fingerprint(verifying_key: &VerifyingKey) -> String { 630 hex::encode(Sha256::digest(verifying_key.to_sec1_point(true).as_bytes())) 631 } 632 633 impl SignedEvaluationReceipt { 634 /// Checks the signature, that the stored `key_fingerprint` is the fingerprint of 635 /// `verifying_key`, and that `receipt.verifier.key_id` equals it. It cannot check the 636 /// signing tier because the tier is not derivable from a key. 637 #[deprecated(note = "use `verify_with`, which also pins the expected cryptographic tier")] 638 pub fn verify(&self, verifying_key: &VerifyingKey) -> Result { 639 if self.receipt.protocol_version != FRAMED_RECEIPT_PROTOCOL_VERSION { 640 return Err(EvaluationError::UnsupportedProtocolVersion( 641 self.receipt.protocol_version, 642 )); 643 } 644 let fingerprint = verifying_key_fingerprint(verifying_key); 645 if self.key_fingerprint != fingerprint { 646 return Err(EvaluationError::KeyIdentityMismatch { 647 expected: self.key_fingerprint.clone(), 648 actual: fingerprint, 649 }); 650 } 651 if self.receipt.verifier.key_id != fingerprint { 652 return Err(EvaluationError::KeyIdentityMismatch { 653 expected: self.receipt.verifier.key_id.clone(), 654 actual: fingerprint, 655 }); 656 } 657 let sig = Signature::from_slice(&self.signature).map_err(|e| { 658 EvaluationError::VerificationFailed(format!("Invalid signature format: {e}")) 659 })?; 660 let digest = self.receipt.compute_receipt_digest(); 661 verifying_key 662 .verify(&digest.0, &sig) 663 .map(|_| true) 664 .map_err(|e| EvaluationError::VerificationFailed(format!("Signature mismatch: {e}"))) 665 } 666 667 /// Strict verification against an operator-supplied key and expected tier (AEI1 2.2 steps 1 to 3). 668 pub fn verify_with( 669 &self, 670 verifying_key: &VerifyingKey, 671 expected_tier: CryptographicTier, 672 ) -> Result { 673 if self.cryptographic_tier != expected_tier { 674 return Err(EvaluationError::TierMismatch { 675 expected: expected_tier, 676 actual: self.cryptographic_tier, 677 }); 678 } 679 #[allow(deprecated)] 680 self.verify(verifying_key) 681 } 682 } 683 684 #[derive(thiserror::Error, Debug)] 685 pub enum EvaluationError { 686 #[error("Unsupported evaluation receipt digest protocol version {0}")] 687 UnsupportedProtocolVersion(u32), 688 #[error("Evaluator execution failed: {0}")] 689 ExecutionFailed(String), 690 #[error("Plan digest mismatch")] 691 PlanDigestMismatch, 692 #[error("Plan tampering detected: {0}")] 693 PlanTamperingDetected(String), 694 #[error("Policy tampering detected: {0}")] 695 PolicyTamperingDetected(String), 696 #[error("Evaluator manifest tampering detected: {0}")] 697 ManifestTamperingDetected(String), 698 #[error("Baseline reference tampering detected: {0}")] 699 BaselineTamperingDetected(String), 700 #[error("Evaluator descriptor tampering detected: {0}")] 701 EvaluatorTamperingDetected(String), 702 #[error("Missing required evaluator: {0}")] 703 MissingRequiredEvaluator(String), 704 #[error("Unexpected evaluator not present in plan: {0}")] 705 UnexpectedEvaluator(String), 706 #[error("Duplicate evaluator provided: {0}")] 707 DuplicateEvaluator(String), 708 #[error("Evaluator version mismatch for {evaluator_id}: expected {expected}, actual {actual}")] 709 EvaluatorVersionMismatch { 710 evaluator_id: String, 711 expected: String, 712 actual: String, 713 }, 714 #[error( 715 "Verifier key identity mismatch: receipt key_id {expected} vs signer fingerprint {actual}" 716 )] 717 KeyIdentityMismatch { expected: String, actual: String }, 718 #[error("Cryptographic tier mismatch: expected {expected:?}, receipt claims {actual:?}")] 719 TierMismatch { 720 expected: CryptographicTier, 721 actual: CryptographicTier, 722 }, 723 #[error("Rollback execution failed: {0}")] 724 RollbackFailed(String), 725 #[error("Verifier verification error: {0}")] 726 VerificationFailed(String), 727 } 728 729 #[async_trait::async_trait] 730 pub trait Evaluator: Send + Sync { 731 fn descriptor(&self) -> EvaluatorDescriptor; 732 async fn evaluate( 733 &self, 734 plan: &EvaluationPlan, 735 subject: &ArtifactRef, 736 ) -> Result; 737 } 738 739 pub fn compute_merkle_root(digests: &[Digest32]) -> Digest32 { 740 if digests.is_empty() { 741 return Digest32([0u8; 32]); 742 } 743 let mut current = digests.to_vec(); 744 while current.len() > 1 { 745 let mut next = Vec::new(); 746 for chunk in current.chunks(2) { 747 let mut hasher = Sha256::new(); 748 hasher.update(chunk[0].0); 749 if chunk.len() > 1 { 750 hasher.update(chunk[1].0); 751 } else { 752 hasher.update(chunk[0].0); 753 } 754 next.push(Digest32(hasher.finalize().into())); 755 } 756 current = next; 757 } 758 current[0] 759 } 760 761 /// Canary evaluation and rollback harness enforcing the RSI safety envelope. 762 pub struct CanaryRollbackHarness { 763 pub verifier: VerifierIdentity, 764 pub signer: Arc, 765 } 766 767 impl CanaryRollbackHarness { 768 pub fn new(verifier: VerifierIdentity, signer: Arc) -> Self { 769 Self { verifier, signer } 770 } 771 772 /// Executes candidate canary evaluation against the frozen plan. 773 /// Strictly verifies that all required evaluators specified in the plan are present and version-matched. 774 /// If any required evaluator fails, is missing, or violates an invariant, executes rollback_action and emits a SignedEvaluationReceipt with Verdict::Fail. 775 pub async fn evaluate_and_enforce( 776 &self, 777 plan: &EvaluationPlan, 778 candidate: &ArtifactRef, 779 evaluators: &[Box], 780 started_at: Timestamp, 781 rollback_action: R, 782 ) -> Result<(SignedEvaluationReceipt, Vec), EvaluationError> 783 where 784 R: FnOnce() -> Fut + Send, 785 Fut: Future> + Send, 786 { 787 // 1. Verify frozen plan integrity 788 if !plan.verify_plan_digest() { 789 return Err(EvaluationError::PlanDigestMismatch); 790 } 791 792 // 2. Validate descriptor coverage between frozen plan and supplied evaluators 793 let mut provided_map: HashMap> = HashMap::new(); 794 for eval in evaluators { 795 let id = eval.descriptor().evaluator_id; 796 if provided_map.contains_key(&id) { 797 return Err(EvaluationError::DuplicateEvaluator(id)); 798 } 799 provided_map.insert(id, eval); 800 } 801 802 let plan_ids: HashSet = plan 803 .evaluators 804 .iter() 805 .map(|d| d.evaluator_id.clone()) 806 .collect(); 807 for provided_id in provided_map.keys() { 808 if !plan_ids.contains(provided_id) { 809 return Err(EvaluationError::UnexpectedEvaluator(provided_id.clone())); 810 } 811 } 812 813 // Check that every required plan evaluator is present and version-matched 814 for expected in &plan.evaluators { 815 if let Some(eval) = provided_map.get(&expected.evaluator_id) { 816 let actual_desc = eval.descriptor(); 817 if actual_desc.version != expected.version { 818 return Err(EvaluationError::EvaluatorVersionMismatch { 819 evaluator_id: expected.evaluator_id.clone(), 820 expected: expected.version.clone(), 821 actual: actual_desc.version, 822 }); 823 } 824 } else if expected.required { 825 return Err(EvaluationError::MissingRequiredEvaluator( 826 expected.evaluator_id.clone(), 827 )); 828 } 829 } 830 831 // 3. Execute evaluation 832 let mut outcomes = Vec::new(); 833 let mut passed_all = true; 834 let mut evidence_digests = Vec::new(); 835 let mut outcome_digests = Vec::new(); 836 837 for eval in evaluators { 838 let desc = eval.descriptor(); 839 let outcome = eval.evaluate(plan, candidate).await?; 840 841 let exec_digest = outcome.compute_execution_digest(); 842 outcome_digests.push(exec_digest); 843 844 for ev in &outcome.evidence { 845 evidence_digests.push(ev.digest); 846 } 847 848 if desc.required && outcome.status != EvaluatorStatus::Passed { 849 passed_all = false; 850 } 851 852 for f in &outcome.findings { 853 if f.severity.eq_ignore_ascii_case("fatal") 854 || f.severity.eq_ignore_ascii_case("invariantviolation") 855 { 856 passed_all = false; 857 } 858 } 859 860 outcomes.push(outcome); 861 } 862 863 let verdict = if passed_all { 864 Verdict::Pass 865 } else { 866 // Hard invariant or required evaluator failed: execute rollback 867 rollback_action() 868 .await 869 .map_err(EvaluationError::RollbackFailed)?; 870 Verdict::Fail 871 }; 872 873 let evidence_root = compute_merkle_root(&evidence_digests); 874 let outcomes_root = compute_merkle_root(&outcome_digests); 875 let completed_at = Timestamp(started_at.0 + 100); 876 877 let receipt = EvaluationReceipt { 878 protocol_version: FRAMED_RECEIPT_PROTOCOL_VERSION, 879 evaluation_id: plan.evaluation_id, 880 request_digest: Digest32([0u8; 32]), 881 subject_digest: candidate.digest, 882 plan_digest: plan.plan_digest, 883 evidence_root, 884 outcomes_root, 885 verdict, 886 verifier: self.verifier.clone(), 887 started_at, 888 completed_at, 889 }; 890 891 let signed = receipt.sign_with_signer(&*self.signer)?; 892 Ok((signed, outcomes)) 893 } 894 }