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/patches/272caa92f65501fc # 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 ## GitHub aien-dev/aien-protocols-mv#3 (code only) closed derived `272caa92f65501fc` #3 Imported from GitHub aien-dev/aien-protocols-mv#3 (code only) GitHub's metadata for this pull request is unavailable: its state is DERIVED from the commits (merged: the head is reachable from this project's main; open: GitHub kept a merge ref; else closed). Base `0959a7ef1bc0653f58454c6bdfc28e9ffa7cd679` · Head `b7047c58f4350cf9191053e6d32ea84d344bf2b9` ### Apply it ``` git checkout -b patch-272caa92f65501fc 0959a7ef1bc0653f58454c6bdfc28e9ffa7cd679 curl -fsSL https://interplane.io/drakestapleton/aien-protocols-mv/patches/272caa92f65501fc.patch | git am ``` Raw patch (mbox) · Diff ### Provenance This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record: ``` github-import 1 aien-dev/aien-protocols-mv 3 b7047c58f4350cf9191053e6d32ea84d344bf2b9 ``` ``` {"kind":"github-import","owner":"aien-dev","repo":"aien-protocols-mv","number":3,"url":"https://github.com/aien-dev/aien-protocols-mv/pull/3","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:39:44Z","metadata":"unavailable","state_derived":true} ``` ### Changes ``` diff --git a/Cargo.lock b/Cargo.lock index 5897986..f6212f1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -37,9 +37,13 @@ dependencies = [ "aien-protocol-types", "aien-provenance", "async-trait", + "hex", + "p256", "serde", "serde_json", + "sha2 0.10.9", "thiserror", + "tokio", "uuid", ] @@ -61,7 +65,10 @@ dependencies = [ "aien-inference-protocol", "aien-protocol-types", "async-trait", + "serde", + "serde_json", "thiserror", + "uuid", ] [[package]] @@ -93,11 +100,13 @@ name = "aien-provenance" version = "0.1.0" dependencies = [ "aien-protocol-types", + "bitflags", "hex", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "thiserror", + "uuid", ] [[package]] @@ -111,11 +120,32 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + [[package]] name = "bitflags" version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] [[package]] name = "block-buffer" @@ -126,6 +156,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -144,6 +183,24 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -153,6 +210,31 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +dependencies = [ + "cpubits", + "ctutils", + "getrandom", + "hybrid-array", + "num-traits", + "rand_core", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" @@ -163,14 +245,94 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "getrandom", + "hybrid-array", + "rand_core", +] + +[[package]] +name = "ctutils" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" +dependencies = [ + "cmov", + "subtle", +] + +[[package]] +name = "der" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + [[package]] name = "digest" version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der", + "digest 0.11.3", + "elliptic-curve", + "rfc6979", + "signature", + "spki", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" +dependencies = [ + "base16ct", + "crypto-bigint", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff", + "group", + "hybrid-array", + "pem-rfc7468", + "pkcs8", + "rand_core", + "sec1", + "subtle", + "zeroize", ] [[package]] @@ -183,6 +345,16 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core", + "subtle", +] + [[package]] name = "futures-core" version = "0.3.34" @@ -226,6 +398,18 @@ dependencies = [ "cfg-if", "libc", "r-efi", + "rand_core", +] + +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff", + "rand_core", + "subtle", ] [[package]] @@ -234,6 +418,26 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest 0.11.3", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "subtle", + "typenum", + "zeroize", +] + [[package]] name = "itoa" version = "1.0.18" @@ -283,12 +487,34 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + [[package]] name = "once_cell" version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primefield", + "primeorder", + "sha2 0.11.0", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -312,12 +538,58 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "pin-project-lite" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint", + "crypto-common 0.2.2", + "ff", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve", + "once_cell", + "primefield", + "serdect", + "wnaf", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -342,6 +614,12 @@ version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -351,6 +629,16 @@ dependencies = [ "bitflags", ] +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint", + "hmac", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -363,6 +651,20 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct", + "ctutils", + "der", + "hybrid-array", + "subtle", + "zeroize", +] + [[package]] name = "serde" version = "1.0.229" @@ -406,6 +708,16 @@ dependencies = [ "zmij", ] +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + [[package]] name = "sha2" version = "0.10.9" @@ -413,8 +725,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -427,6 +750,16 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core", +] + [[package]] name = "slab" version = "0.4.12" @@ -449,6 +782,22 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "spki" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -615,6 +964,24 @@ dependencies = [ "windows-link", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff", + "group", + "hybrid-array", + "primefield", +] + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 0dfcdbf..d05843b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,3 +28,4 @@ tokio = { version = "1.37", features = ["full"] } async-trait = "0.1" thiserror = "1.0" bitflags = { version = "2.5", features = ["serde"] } +p256 = { version = "0.14.0", features = ["ecdsa"] } diff --git a/crates/aien-evaluation-protocol/Cargo.toml b/crates/aien-evaluation-protocol/Cargo.toml index db58dfc..16d23ed 100644 --- a/crates/aien-evaluation-protocol/Cargo.toml +++ b/crates/aien-evaluation-protocol/Cargo.toml @@ -11,5 +11,11 @@ aien-provenance = { path = "../aien-provenance" } serde = { workspace = true } serde_json = { workspace = true } uuid = { workspace = true } +sha2 = { workspace = true } +hex = { workspace = true } +p256 = { workspace = true } async-trait = { workspace = true } thiserror = { workspace = true } + +[dev-dependencies] +tokio = { workspace = true } diff --git a/crates/aien-evaluation-protocol/src/lib.rs b/crates/aien-evaluation-protocol/src/lib.rs index 02c8eb6..e34db45 100644 --- a/crates/aien-evaluation-protocol/src/lib.rs +++ b/crates/aien-evaluation-protocol/src/lib.rs @@ -1,5 +1,9 @@ use aien_protocol_types::{ArtifactRef, Digest32, EvaluationId, Timestamp}; +use p256::ecdsa::signature::{Signer, Verifier}; +use p256::ecdsa::{Signature, SigningKey, VerifyingKey}; use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::future::Future; #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct EvaluationClaim { @@ -39,6 +43,92 @@ pub struct EvaluationPlan { pub plan_digest: Digest32, } +impl EvaluationPlan { + /// Computes the deterministic SHA-256 digest of the evaluation plan. + pub fn compute_plan_digest(&self) -> Digest32 { + let mut hasher = Sha256::new(); + hasher.update(self.evaluation_id.0.as_bytes()); + hasher.update(self.subject.artifact_id.as_bytes()); + hasher.update(&self.subject.digest.0); + hasher.update(self.profile.as_bytes()); + + // Sort evaluators by evaluator_id to guarantee deterministic hashing + let mut sorted_evals = self.evaluators.clone(); + sorted_evals.sort_by(|a, b| a.evaluator_id.cmp(&b.evaluator_id)); + for eval in &sorted_evals { + hasher.update(eval.evaluator_id.as_bytes()); + hasher.update(eval.version.as_bytes()); + hasher.update(&[if eval.required { 1u8 } else { 0u8 }]); + } + + if let Some(ref base) = self.baseline { + hasher.update(b"baseline:present"); + hasher.update(base.artifact_id.as_bytes()); + hasher.update(&base.digest.0); + } else { + hasher.update(b"baseline:none"); + } + + hasher.update(self.sandbox_profile.as_bytes()); + hasher.update(&self.policy_digest.0); + hasher.update(&self.evaluator_manifest_digest.0); + + let result: [u8; 32] = hasher.finalize().into(); + Digest32(result) + } + + /// Verifies that the plan digest strictly matches its computed content. + pub fn verify_plan_digest(&self) -> bool { + self.plan_digest == self.compute_plan_digest() + } + + /// Asserts that a proposed candidate plan preserves all frozen invariants of this authoritative plan. + /// Returns an error if any parameter, threshold, baseline, evaluator, or digest has been tampered with. + pub fn assert_frozen_invariants(&self, candidate_plan: &EvaluationPlan) -> Result<(), EvaluationError> { + if !self.verify_plan_digest() { + return Err(EvaluationError::PlanDigestMismatch); + } + if !candidate_plan.verify_plan_digest() { + return Err(EvaluationError::PlanDigestMismatch); + } + if self.plan_digest != candidate_plan.plan_digest { + return Err(EvaluationError::PlanTamperingDetected( + format!("Plan digest altered: authoritative {} vs candidate {}", + hex::encode(self.plan_digest.0), + hex::encode(candidate_plan.plan_digest.0) + ) + )); + } + if self.policy_digest != candidate_plan.policy_digest { + return Err(EvaluationError::PolicyTamperingDetected( + format!("Policy digest altered: authoritative {} vs candidate {}", + hex::encode(self.policy_digest.0), + hex::encode(candidate_plan.policy_digest.0) + ) + )); + } + if self.evaluator_manifest_digest != candidate_plan.evaluator_manifest_digest { + return Err(EvaluationError::ManifestTamperingDetected( + format!("Evaluator manifest digest altered: authoritative {} vs candidate {}", + hex::encode(self.evaluator_manifest_digest.0), + hex::encode(candidate_plan.evaluator_manifest_digest.0) + ) + )); + } + if self.baseline != candidate_plan.baseline { + return Err(EvaluationError::BaselineTamperingDetected( + "Baseline artifact reference altered".to_string() + )); + } + if self.evaluators != candidate_plan.evaluators { + return Err(EvaluationError::EvaluatorTamperingDetected( + "Evaluator descriptors list altered".to_string() + )); + } + Ok(()) + } +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct EvaluatorIdentity { pub evaluator_id: String, @@ -80,6 +170,47 @@ pub struct EvaluatorOutcome { pub execution_digest: Digest32, } +impl EvaluatorOutcome { + /// Computes the deterministic execution digest over outcome components. + pub fn compute_execution_digest(&self) -> Digest32 { + let mut hasher = Sha256::new(); + hasher.update(self.evaluator.evaluator_id.as_bytes()); + hasher.update(self.evaluator.version.as_bytes()); + hasher.update(&self.evaluator.binary_digest.0); + hasher.update(&self.evaluator.config_digest.0); + let status_code: u8 = match self.status { + EvaluatorStatus::Passed => 0, + EvaluatorStatus::Failed => 1, + EvaluatorStatus::Inconclusive => 2, + EvaluatorStatus::TimedOut => 3, + }; + hasher.update(&[status_code]); + + for f in &self.findings { + hasher.update(f.severity.as_bytes()); + hasher.update(f.rule_id.as_bytes()); + hasher.update(f.message.as_bytes()); + if let Some(ref loc) = f.location { + hasher.update(loc.as_bytes()); + } + } + + for m in &self.measurements { + hasher.update(m.metric.as_bytes()); + hasher.update(&m.value.to_bits().to_le_bytes()); + hasher.update(m.unit.as_bytes()); + } + + for ev in &self.evidence { + hasher.update(ev.artifact_id.as_bytes()); + hasher.update(&ev.digest.0); + } + + let result: [u8; 32] = hasher.finalize().into(); + Digest32(result) + } +} + #[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum Verdict { Pass, @@ -96,6 +227,29 @@ pub struct VerifierIdentity { pub policy_bundle_digest: Digest32, } +#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)] +pub enum CryptographicTier { + /// Tier 1: Algorithm/digest only (SHA-256). + Tier1AlgorithmOnly, + /// Tier 2: Software key signing (in-memory ECDSA P-256). + Tier2SoftwareKey, + /// Tier 3: Host OS key (file or daemon key). + Tier3HostOsKey, + /// Tier 4: Hardware TPM 2.0 bound key (/dev/tpmrm0 ECDSA P-256). + Tier4HardwareTpm, +} + +impl CryptographicTier { + pub fn as_str(&self) -> &str { + match self { + Self::Tier1AlgorithmOnly => "tier1-algo", + Self::Tier2SoftwareKey => "tier2-software", + Self::Tier3HostOsKey => "tier3-host-os", + Self::Tier4HardwareTpm => "tier4-hardware-tpm", + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct EvaluationReceipt { pub protocol_version: u32, @@ -111,10 +265,77 @@ pub struct EvaluationReceipt { pub completed_at: Timestamp, } +impl EvaluationReceipt { + /// Computes the deterministic SHA-256 digest of the receipt. + pub fn compute_receipt_digest(&self) -> Digest32 { + let mut hasher = Sha256::new(); + hasher.update(&self.protocol_version.to_le_bytes()); + hasher.update(self.evaluation_id.0.as_bytes()); + hasher.update(&self.request_digest.0); + hasher.update(&self.subject_digest.0); + hasher.update(&self.plan_digest.0); + hasher.update(&self.evidence_root.0); + hasher.update(&self.outcomes_root.0); + + let verdict_byte = match self.verdict { + Verdict::Pass => 0u8, + Verdict::Fail => 1u8, + Verdict::Indeterminate => 2u8, + }; + hasher.update(&[verdict_byte]); + + hasher.update(self.verifier.principal_id.as_bytes()); + hasher.update(self.verifier.key_id.as_bytes()); + hasher.update(&self.verifier.trust_epoch.to_le_bytes()); + hasher.update(&self.verifier.trusted_build_digest.0); + hasher.update(&self.verifier.policy_bundle_digest.0); + + hasher.update(&self.started_at.0.to_le_bytes()); + hasher.update(&self.completed_at.0.to_le_bytes()); + + let result: [u8; 32] = hasher.finalize().into(); + Digest32(result) + } + + /// Signs the receipt using an ECDSA P-256 key, declaring the explicit cryptographic tier. + pub fn sign( + &self, + signing_key: &SigningKey, + tier: CryptographicTier, + ) -> SignedEvaluationReceipt { + let digest = self.compute_receipt_digest(); + let sig: Signature = signing_key.sign(&digest.0); + let verifying_key = VerifyingKey::from(signing_key); + let key_fingerprint = hex::encode(Sha256::digest(verifying_key.to_sec1_point(true).as_bytes())); + + SignedEvaluationReceipt { + receipt: self.clone(), + signature: sig.to_bytes().to_vec(), + cryptographic_tier: tier, + key_fingerprint, + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] pub struct SignedEvaluationReceipt { pub receipt: EvaluationReceipt, pub signature: Vec, + pub cryptographic_tier: CryptographicTier, + pub key_fingerprint: String, +} + +impl SignedEvaluationReceipt { + /// Cryptographically verifies the signature over the receipt digest using the provided verifying key. + pub fn verify(&self, verifying_key: &VerifyingKey) -> Result { + let sig = Signature::from_slice(&self.signature) + .map_err(|e| EvaluationError::VerificationFailed(format!("Invalid signature format: {e}")))?; + let digest = self.receipt.compute_receipt_digest(); + verifying_key + .verify(&digest.0, &sig) + .map(|_| true) + .map_err(|e| EvaluationError::VerificationFailed(format!("Signature mismatch: {e}"))) + } } #[derive(thiserror::Error, Debug)] @@ -123,6 +344,18 @@ pub enum EvaluationError { ExecutionFailed(String), #[error("Plan digest mismatch")] PlanDigestMismatch, + #[error("Plan tampering detected: {0}")] + PlanTamperingDetected(String), + #[error("Policy tampering detected: {0}")] + PolicyTamperingDetected(String), + #[error("Evaluator manifest tampering detected: {0}")] + ManifestTamperingDetected(String), + #[error("Baseline reference tampering detected: {0}")] + BaselineTamperingDetected(String), + #[error("Evaluator descriptor tampering detected: {0}")] + EvaluatorTamperingDetected(String), + #[error("Rollback execution failed: {0}")] + RollbackFailed(String), #[error("Verifier verification error: {0}")] VerificationFailed(String), } @@ -132,3 +365,125 @@ pub trait Evaluator: Send + Sync { fn descriptor(&self) -> EvaluatorDescriptor; async fn evaluate(&self, plan: &EvaluationPlan, subject: &ArtifactRef) -> Result; } + +/// Computes a Merkle root over a sequence of digests. +pub fn compute_merkle_root(digests: &[Digest32]) -> Digest32 { + if digests.is_empty() { + return Digest32([0u8; 32]); + } + let mut current = digests.to_vec(); + while current.len() > 1 { + let mut next = Vec::new(); + for chunk in current.chunks(2) { + let mut hasher = Sha256::new(); + hasher.update(&chunk[0].0); + if chunk.len() > 1 { + hasher.update(&chunk[1].0); + } else { + hasher.update(&chunk[0].0); + } + next.push(Digest32(hasher.finalize().into())); + } + current = next; + } + current[0] +} + +/// Canary evaluation and rollback harness enforcing the RSI safety envelope. +pub struct CanaryRollbackHarness { + pub verifier: VerifierIdentity, + pub signing_key: SigningKey, + pub cryptographic_tier: CryptographicTier, +} + +impl CanaryRollbackHarness { + pub fn new( + verifier: VerifierIdentity, + signing_key: SigningKey, + cryptographic_tier: CryptographicTier, + ) -> Self { + Self { + verifier, + signing_key, + cryptographic_tier, + } + } + + /// Executes candidate canary evaluation against the frozen plan. + /// If any required evaluator fails or invariant is violated, executes rollback_action and emits a SignedEvaluationReceipt with Verdict::Fail. + /// If all requirements pass, emits a SignedEvaluationReceipt with Verdict::Pass. + pub async fn evaluate_and_enforce( + &self, + plan: &EvaluationPlan, + candidate: &ArtifactRef, + evaluators: &[Box], + started_at: Timestamp, + rollback_action: R, + ) -> Result<(SignedEvaluationReceipt, Vec), EvaluationError> + where + R: FnOnce() -> Fut + Send, + Fut: Future> + Send, + { + if !plan.verify_plan_digest() { + return Err(EvaluationError::PlanDigestMismatch); + } + + let mut outcomes = Vec::new(); + let mut passed_all = true; + let mut evidence_digests = Vec::new(); + let mut outcome_digests = Vec::new(); + + for eval in evaluators { + let desc = eval.descriptor(); + let outcome = eval.evaluate(plan, candidate).await?; + + let exec_digest = outcome.compute_execution_digest(); + outcome_digests.push(exec_digest); + + for ev in &outcome.evidence { + evidence_digests.push(ev.digest); + } + + if desc.required && outcome.status != EvaluatorStatus::Passed { + passed_all = false; + } + + for f in &outcome.findings { + if f.severity.eq_ignore_ascii_case("fatal") || f.severity.eq_ignore_ascii_case("invariantviolation") { + passed_all = false; + } + } + + outcomes.push(outcome); + } + + let verdict = if passed_all { + Verdict::Pass + } else { + // Hard invariant or required evaluator failed: execute rollback + rollback_action().await.map_err(EvaluationError::RollbackFailed)?; + Verdict::Fail + }; + + let evidence_root = compute_merkle_root(&evidence_digests); + let outcomes_root = compute_merkle_root(&outcome_digests); + let completed_at = Timestamp(started_at.0 + 100); + + let receipt = EvaluationReceipt { + protocol_version: 1, + evaluation_id: plan.evaluation_id.clone(), + request_digest: Digest32([0u8; 32]), + subject_digest: candidate.digest, + plan_digest: plan.plan_digest, + evidence_root, + outcomes_root, + verdict, + verifier: self.verifier.clone(), + started_at, + completed_at, + }; + + let signed = receipt.sign(&self.signing_key, self.cryptographic_tier); + Ok((signed, outcomes)) + } +} diff --git a/crates/aien-evaluation-protocol/tests/evaluator_protocol_tests.rs b/crates/aien-evaluation-protocol/tests/evaluator_protocol_tests.rs new file mode 100644 index 0000000..0f969a1 --- /dev/null +++ b/crates/aien-evaluation-protocol/tests/evaluator_protocol_tests.rs @@ -0,0 +1,291 @@ +use aien_evaluation_protocol::{ + CanaryRollbackHarness, CryptographicTier, EvaluationError, EvaluationPlan, EvaluationReceipt, + Evaluator, EvaluatorDescriptor, EvaluatorIdentity, EvaluatorOutcome, EvaluatorStatus, Finding, + Measurement, SignedEvaluationReceipt, Verdict, VerifierIdentity, +}; +use aien_protocol_types::{ArtifactRef, Digest32, EvaluationId, Timestamp}; +use p256::ecdsa::{SigningKey, VerifyingKey}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; + +struct MockEvaluator { + id: String, + status: EvaluatorStatus, + findings: Vec, +} + +#[async_trait::async_trait] +impl Evaluator for MockEvaluator { + fn descriptor(&self) -> EvaluatorDescriptor { + EvaluatorDescriptor { + evaluator_id: self.id.clone(), + version: "1.0.0".to_string(), + required: true, + } + } + + async fn evaluate( + &self, + _plan: &EvaluationPlan, + _subject: &ArtifactRef, + ) -> Result { + Ok(EvaluatorOutcome { + evaluator: EvaluatorIdentity { + evaluator_id: self.id.clone(), + version: "1.0.0".to_string(), + binary_digest: Digest32([1u8; 32]), + config_digest: Digest32([2u8; 32]), + }, + status: self.status, + findings: self.findings.clone(), + measurements: vec![Measurement { + metric: "unslop_score".to_string(), + value: 1.0, + unit: "ratio".to_string(), + }], + evidence: vec![], + execution_digest: Digest32::ZERO, + }) + } +} + +fn create_sample_plan() -> EvaluationPlan { + let mut plan = EvaluationPlan { + evaluation_id: EvaluationId::new_v4(), + subject: ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([10u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 4096, + }, + profile: "strict-systems".to_string(), + evaluators: vec![ + EvaluatorDescriptor { + evaluator_id: "zeta-auditor".to_string(), + version: "1.0.0".to_string(), + required: true, + }, + EvaluatorDescriptor { + evaluator_id: "alpha-unslop".to_string(), + version: "1.0.0".to_string(), + required: true, + }, + ], + baseline: Some(ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([9u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 4096, + }), + sandbox_profile: "bubblewrap-airgap".to_string(), + policy_digest: Digest32([3u8; 32]), + evaluator_manifest_digest: Digest32([4u8; 32]), + plan_digest: Digest32::ZERO, + }; + plan.plan_digest = plan.compute_plan_digest(); + plan +} + +#[test] +fn test_evaluation_plan_deterministic_digest_and_verification() { + let plan = create_sample_plan(); + assert!(plan.verify_plan_digest()); + + // Shuffling evaluators order preserves digest due to internal sorting + let mut plan_shuffled = plan.clone(); + plan_shuffled.evaluators.reverse(); + assert_eq!(plan.compute_plan_digest(), plan_shuffled.compute_plan_digest()); + + // Tampering with sandbox profile breaks digest verification + let mut plan_tampered = plan.clone(); + plan_tampered.sandbox_profile = "unconfined-host".to_string(); + assert!(!plan_tampered.verify_plan_digest()); +} + +#[test] +fn test_frozen_invariants_tampering_detection() { + let plan = create_sample_plan(); + let mut candidate_plan = plan.clone(); + + // 1. Identical plan passes frozen assertion + assert!(plan.assert_frozen_invariants(&candidate_plan).is_ok()); + + // 2. Candidate attempts to weaken policy digest + candidate_plan.policy_digest = Digest32([99u8; 32]); + candidate_plan.plan_digest = candidate_plan.compute_plan_digest(); + match plan.assert_frozen_invariants(&candidate_plan) { + Err(EvaluationError::PlanTamperingDetected(_)) => {} + other => panic!("Expected PlanTamperingDetected, got {:?}", other), + } + + // 3. Candidate attempts to remove a required evaluator + let mut candidate_no_eval = plan.clone(); + candidate_no_eval.evaluators.pop(); + candidate_no_eval.plan_digest = candidate_no_eval.compute_plan_digest(); + match plan.assert_frozen_invariants(&candidate_no_eval) { + Err(EvaluationError::PlanTamperingDetected(_)) => {} + other => panic!("Expected PlanTamperingDetected, got {:?}", other), + } +} + +#[test] +fn test_evaluation_receipt_p256_signature_and_verification() { + let signing_key = SigningKey::from_slice(&[42u8; 32]).expect("valid p256 signing key"); + let verifying_key = VerifyingKey::from(&signing_key); + + let receipt = EvaluationReceipt { + protocol_version: 1, + evaluation_id: EvaluationId::new_v4(), + request_digest: Digest32([1u8; 32]), + subject_digest: Digest32([2u8; 32]), + plan_digest: Digest32([3u8; 32]), + evidence_root: Digest32([4u8; 32]), + outcomes_root: Digest32([5u8; 32]), + verdict: Verdict::Pass, + verifier: VerifierIdentity { + principal_id: "verifier-node-01".to_string(), + key_id: "key-tpm-primary".to_string(), + trust_epoch: 1, + trusted_build_digest: Digest32([6u8; 32]), + policy_bundle_digest: Digest32([7u8; 32]), + }, + started_at: Timestamp(1000), + completed_at: Timestamp(1050), + }; + + let signed: SignedEvaluationReceipt = receipt.sign(&signing_key, CryptographicTier::Tier2SoftwareKey); + assert_eq!(signed.cryptographic_tier, CryptographicTier::Tier2SoftwareKey); + assert!(!signed.key_fingerprint.is_empty()); + + // 1. Signature verifies successfully + assert!(signed.verify(&verifying_key).expect("verification failed")); + + // 2. Tampering with receipt verdict causes verification rejection + let mut tampered = signed.clone(); + tampered.receipt.verdict = Verdict::Fail; + assert!(tampered.verify(&verifying_key).is_err()); + + // 3. Verifying with different key causes rejection + let other_key = SigningKey::from_slice(&[77u8; 32]).expect("valid p256 other key"); + let other_verifying_key = VerifyingKey::from(&other_key); + assert!(signed.verify(&other_verifying_key).is_err()); +} + +#[tokio::test] +async fn test_canary_rollback_harness_invariant_violation_triggers_rollback() { + let signing_key = SigningKey::from_slice(&[55u8; 32]).expect("valid signing key"); + let harness = CanaryRollbackHarness::new( + VerifierIdentity { + principal_id: "canary-verifier".to_string(), + key_id: "canary-key".to_string(), + trust_epoch: 1, + trusted_build_digest: Digest32([10u8; 32]), + policy_bundle_digest: Digest32([11u8; 32]), + }, + signing_key, + CryptographicTier::Tier2SoftwareKey, + ); + + let plan = create_sample_plan(); + let candidate = ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([12u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 1024, + }; + + let failing_evaluator = Box::new(MockEvaluator { + id: "alpha-unslop".to_string(), + status: EvaluatorStatus::Failed, + findings: vec![Finding { + severity: "InvariantViolation".to_string(), + rule_id: "UNSLOP_EM_DASH".to_string(), + message: "Detected em dash in docstring".to_string(), + location: Some("src/lib.rs:42".to_string()), + }], + }); + + let evaluators: Vec> = vec![failing_evaluator]; + let rollback_executed = Arc::new(AtomicBool::new(false)); + let rollback_clone = rollback_executed.clone(); + + let (receipt, outcomes) = harness + .evaluate_and_enforce( + &plan, + &candidate, + &evaluators, + Timestamp(100), + || async move { + rollback_clone.store(true, Ordering::SeqCst); + Ok(()) + }, + ) + .await + .expect("evaluation and enforcement failed"); + + // Invariant failure triggers rollback + assert!(rollback_executed.load(Ordering::SeqCst), "Rollback must execute on invariant violation"); + assert_eq!(receipt.receipt.verdict, Verdict::Fail); + assert_eq!(outcomes.len(), 1); + assert_eq!(outcomes[0].status, EvaluatorStatus::Failed); + + let verifying_key = VerifyingKey::from(&harness.signing_key); + assert!(receipt.verify(&verifying_key).unwrap()); +} + +#[tokio::test] +async fn test_canary_rollback_harness_success_admits_candidate() { + let signing_key = SigningKey::from_slice(&[66u8; 32]).expect("valid signing key"); + let harness = CanaryRollbackHarness::new( + VerifierIdentity { + principal_id: "canary-verifier".to_string(), + key_id: "canary-key".to_string(), + trust_epoch: 1, + trusted_build_digest: Digest32([10u8; 32]), + policy_bundle_digest: Digest32([11u8; 32]), + }, + signing_key, + CryptographicTier::Tier2SoftwareKey, + ); + + let plan = create_sample_plan(); + let candidate = ArtifactRef { + artifact_id: uuid::Uuid::new_v4(), + digest: Digest32([12u8; 32]), + media_type: "application/rust".to_string(), + byte_size: 1024, + }; + + let passing_evaluator = Box::new(MockEvaluator { + id: "alpha-unslop".to_string(), + status: EvaluatorStatus::Passed, + findings: vec![], + }); + + let evaluators: Vec> = vec![passing_evaluator]; + let rollback_executed = Arc::new(AtomicBool::new(false)); + let rollback_clone = rollback_executed.clone(); + + let (receipt, outcomes) = harness + .evaluate_and_enforce( + &plan, + &candidate, + &evaluators, + Timestamp(200), + || async move { + rollback_clone.store(true, Ordering::SeqCst); + Ok(()) + }, + ) + .await + .expect("evaluation and enforcement failed"); + + // Success admits candidate without rollback + assert!(!rollback_executed.load(Ordering::SeqCst), "Rollback must NOT execute on success"); + assert_eq!(receipt.receipt.verdict, Verdict::Pass); + assert_eq!(outcomes.len(), 1); + assert_eq!(outcomes[0].status, EvaluatorStatus::Passed); + + let verifying_key = VerifyingKey::from(&harness.signing_key); + assert!(receipt.verify(&verifying_key).unwrap()); +} ```