interplane-mv
INTERPLANE: open interoperability protocol between AI models and agent runtimes. Models express intent. Runtimes retain authority.
Brought by drakestapleton
interplane-mv / provenance / src / evaluation.rs
| 1 | //! `rsi-eval/2`: the independent judge's signed evaluation of the exact change the daemon wrote. |
| 2 | //! Specification: provenance/BINDING.md ("Evaluation") and spark-rsi docs/RECEIPT-V2.md. |
| 3 | //! |
| 4 | //! The invariant: no change may be promoted unless its exact identity matches the identity covered |
| 5 | //! by a valid, independently signed evaluation. This module recomputes the judge receipt's |
| 6 | //! version 2 digest, checks its P-256 signature under a judge key supplied by the operator out of |
| 7 | //! band (never read from the bundle), and requires the evaluated subject to be the bytes the |
| 8 | //! daemon granted and read back from disk. It reads and compares; it authorizes nothing. |
| 9 | |
| 10 | use super::{fail, s, Archive, Fail}; |
| 11 | use crate::ledger; |
| 12 | use p256::ecdsa::signature::Verifier; |
| 13 | use p256::ecdsa::Signature; |
| 14 | pub use p256::ecdsa::VerifyingKey; |
| 15 | use serde_json::Value; |
| 16 | use sha2::{Digest, Sha256}; |
| 17 | |
| 18 | pub const BINDING: &str = "rsi-eval/2"; |
| 19 | const RECEIPT_DOMAIN: &str = "spark-rsi.evaluation-receipt.v2"; |
| 20 | const RECEIPT_RECORD: &str = "evaluation_receipt"; |
| 21 | const POLICY_RECORD: &str = "evaluation_policy"; |
| 22 | |
| 23 | /// Parses the operator's judge key file contents: the SEC1 public key in hex. |
| 24 | pub fn parse_judge_key(text: &str) -> Result<VerifyingKey, String> { |
| 25 | let bytes = hex::decode(text.trim()).map_err(|e| format!("judge key is not hex: {e}"))?; |
| 26 | VerifyingKey::from_sec1_bytes(&bytes) |
| 27 | .map_err(|e| format!("judge key is not a P-256 point: {e}")) |
| 28 | } |
| 29 | |
| 30 | fn is_hex64(x: &str) -> bool { |
| 31 | x.len() == 64 && x.bytes().all(|b| b.is_ascii_hexdigit()) |
| 32 | } |
| 33 | |
| 34 | /// True when the bundle carries the records of a judge evaluation. |
| 35 | pub(crate) fn claims_evaluation(a: &Archive, m: &Value) -> bool { |
| 36 | m.get("evaluation").is_some_and(|v| !v.is_null()) |
| 37 | || [RECEIPT_RECORD, POLICY_RECORD].iter().any(|n| a.has(n)) |
| 38 | } |
| 39 | |
| 40 | fn put(h: &mut Sha256, bytes: &[u8]) { |
| 41 | h.update((bytes.len() as u64).to_le_bytes()); |
| 42 | h.update(bytes); |
| 43 | } |
| 44 | |
| 45 | /// Field readers that refuse rather than default: a missing field is a malformed receipt. |
| 46 | struct R<'a>(&'a Value); |
| 47 | |
| 48 | impl R<'_> { |
| 49 | fn str(&self, path: &[&str]) -> Result<&str, Fail> { |
| 50 | s(self.0, path).map_or_else( |
| 51 | || { |
| 52 | fail( |
| 53 | "evaluation_malformed", |
| 54 | format!("receipt.{}", path.join(".")), |
| 55 | ) |
| 56 | }, |
| 57 | Ok, |
| 58 | ) |
| 59 | } |
| 60 | fn bool(&self, path: &[&str]) -> Result<bool, Fail> { |
| 61 | let mut v = self.0; |
| 62 | for k in path { |
| 63 | v = match v.get(k) { |
| 64 | Some(x) => x, |
| 65 | None => { |
| 66 | return fail( |
| 67 | "evaluation_malformed", |
| 68 | format!("receipt.{}", path.join(".")), |
| 69 | ) |
| 70 | } |
| 71 | }; |
| 72 | } |
| 73 | v.as_bool().map_or_else( |
| 74 | || { |
| 75 | fail( |
| 76 | "evaluation_malformed", |
| 77 | format!("receipt.{}", path.join(".")), |
| 78 | ) |
| 79 | }, |
| 80 | Ok, |
| 81 | ) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | fn num_u64(v: &Value, what: &str) -> Result<u64, Fail> { |
| 86 | v.as_u64() |
| 87 | .map_or_else(|| fail("evaluation_malformed", what), Ok) |
| 88 | } |
| 89 | |
| 90 | fn num_f64(v: &Value, what: &str) -> Result<f64, Fail> { |
| 91 | v.as_f64() |
| 92 | .map_or_else(|| fail("evaluation_malformed", what), Ok) |
| 93 | } |
| 94 | |
| 95 | /// Recomputes the version 2 receipt digest (RECEIPT-V2.md "Digest") from the parsed receipt. |
| 96 | pub fn receipt_digest_v2(r: &Value) -> Result<String, Fail> { |
| 97 | let g = R(r); |
| 98 | let mut h = Sha256::new(); |
| 99 | put(&mut h, RECEIPT_DOMAIN.as_bytes()); |
| 100 | for k in [ |
| 101 | "cycle_id", |
| 102 | "candidate_id", |
| 103 | "parent_id", |
| 104 | "evaluated_at", |
| 105 | "evaluator_version", |
| 106 | ] { |
| 107 | put(&mut h, g.str(&[k])?.as_bytes()); |
| 108 | } |
| 109 | for k in [ |
| 110 | "evaluator_binary_sha256", |
| 111 | "subject_path", |
| 112 | "subject_sha256", |
| 113 | "holdout_set_sha256", |
| 114 | "policy_sha256", |
| 115 | ] { |
| 116 | put(&mut h, g.str(&["binding", k])?.as_bytes()); |
| 117 | } |
| 118 | let b = r.get("binding").unwrap_or(&Value::Null); |
| 119 | for k in ["holdouts_total", "holdouts_passed"] { |
| 120 | let n = num_u64(b.get(k).unwrap_or(&Value::Null), k)?; |
| 121 | put(&mut h, &n.to_le_bytes()); |
| 122 | } |
| 123 | for k in [ |
| 124 | "admitted", |
| 125 | "passed_all_hard_invariants", |
| 126 | "passed_statistical_gates", |
| 127 | ] { |
| 128 | put(&mut h, &[g.bool(&[k])? as u8]); |
| 129 | } |
| 130 | let Some(layers) = r.get("layer_results").and_then(Value::as_array) else { |
| 131 | return fail("evaluation_malformed", "receipt.layer_results"); |
| 132 | }; |
| 133 | put(&mut h, &(layers.len() as u64).to_le_bytes()); |
| 134 | for l in layers { |
| 135 | let lg = R(l); |
| 136 | put(&mut h, lg.str(&["layer_name"])?.as_bytes()); |
| 137 | put(&mut h, &[lg.bool(&["is_hard_invariant"])? as u8]); |
| 138 | put(&mut h, &[lg.bool(&["passed"])? as u8]); |
| 139 | let score = num_f64(l.get("score").unwrap_or(&Value::Null), "layer.score")?; |
| 140 | put(&mut h, &score.to_bits().to_le_bytes()); |
| 141 | put(&mut h, lg.str(&["summary"])?.as_bytes()); |
| 142 | let Some(vs) = l.get("violations").and_then(Value::as_array) else { |
| 143 | return fail("evaluation_malformed", "layer.violations"); |
| 144 | }; |
| 145 | put(&mut h, &(vs.len() as u64).to_le_bytes()); |
| 146 | for v in vs { |
| 147 | let Some(v) = v.as_str() else { |
| 148 | return fail("evaluation_malformed", "layer.violations[]"); |
| 149 | }; |
| 150 | put(&mut h, v.as_bytes()); |
| 151 | } |
| 152 | } |
| 153 | match r.get("metrics_summary") { |
| 154 | None | Some(Value::Null) => put(&mut h, &[0u8]), |
| 155 | Some(m) => { |
| 156 | put(&mut h, &[1u8]); |
| 157 | for k in [ |
| 158 | "latency_delta_pct", |
| 159 | "p_value", |
| 160 | "p95_ci_upper_degradation_pct", |
| 161 | "p99_ci_upper_degradation_pct", |
| 162 | "rss_growth_pct", |
| 163 | ] { |
| 164 | let x = num_f64(m.get(k).unwrap_or(&Value::Null), k)?; |
| 165 | put(&mut h, &x.to_bits().to_le_bytes()); |
| 166 | } |
| 167 | let mb = num_u64( |
| 168 | m.get("candidate_resident_mb").unwrap_or(&Value::Null), |
| 169 | "candidate_resident_mb", |
| 170 | )?; |
| 171 | put(&mut h, &mb.to_le_bytes()); |
| 172 | } |
| 173 | } |
| 174 | Ok(hex::encode(h.finalize())) |
| 175 | } |
| 176 | |
| 177 | fn verify_signature(r: &Value, digest_hex: &str, key: &VerifyingKey) -> Result<(), Fail> { |
| 178 | let bad = |w: &str| fail("evaluation_signature_bad", w); |
| 179 | let Some(sig) = s(r, &["signature"]) else { |
| 180 | return bad("receipt.signature absent"); |
| 181 | }; |
| 182 | let raw = sig.strip_prefix("tpm2-p256:").unwrap_or(sig); |
| 183 | let Ok(sig_bytes) = hex::decode(raw) else { |
| 184 | return bad("signature is not hex"); |
| 185 | }; |
| 186 | let Ok(sig) = Signature::from_slice(&sig_bytes) else { |
| 187 | return bad("signature is not a P-256 signature"); |
| 188 | }; |
| 189 | let Ok(digest) = hex::decode(digest_hex) else { |
| 190 | return bad("digest"); |
| 191 | }; |
| 192 | // The judge signs the 32 raw digest bytes as its message (ECDSA with SHA-256 over them). |
| 193 | if key.verify(&digest, &sig).is_err() { |
| 194 | return bad("signature does not verify under the operator-supplied judge key"); |
| 195 | } |
| 196 | Ok(()) |
| 197 | } |
| 198 | |
| 199 | /// Checks the `evaluation` section. `judge_key` comes from the operator, never from the bundle. |
| 200 | /// `ledger_checked` is true when the effect link was the strong ledger binding. |
| 201 | pub(crate) fn check( |
| 202 | a: &Archive, |
| 203 | m: &Value, |
| 204 | ledger_checked: bool, |
| 205 | opts: &crate::Options, |
| 206 | ) -> Result<(), Fail> { |
| 207 | let judge_key = opts.judge_key.as_ref(); |
| 208 | let Some(sec) = m.get("evaluation").filter(|v| !v.is_null()) else { |
| 209 | if claims_evaluation(a, m) { |
| 210 | return fail( |
| 211 | "evaluation_missing", |
| 212 | "evaluation records present but no evaluation section", |
| 213 | ); |
| 214 | } |
| 215 | if judge_key.is_some() { |
| 216 | return fail( |
| 217 | "evaluation_missing", |
| 218 | "a judge key was supplied but the bundle carries no evaluation", |
| 219 | ); |
| 220 | } |
| 221 | return Ok(()); |
| 222 | }; |
| 223 | if !ledger_checked { |
| 224 | return fail( |
| 225 | "malformed_companion", |
| 226 | "evaluation requires effect.binding aien-ledger-slice/1", |
| 227 | ); |
| 228 | } |
| 229 | match s(sec, &["binding"]) { |
| 230 | Some(BINDING) => {} |
| 231 | other => { |
| 232 | return fail( |
| 233 | "unsupported_evaluation", |
| 234 | format!("evaluation.binding={}", other.unwrap_or("absent")), |
| 235 | ) |
| 236 | } |
| 237 | } |
| 238 | let load = |name: &str| -> Result<Value, Fail> { |
| 239 | if !a.has(name) { |
| 240 | return fail("evaluation_missing", format!("record {name} absent")); |
| 241 | } |
| 242 | match a.json(name)? { |
| 243 | Some(v) => Ok(v), |
| 244 | None => fail("evaluation_missing", format!("record {name} not retained")), |
| 245 | } |
| 246 | }; |
| 247 | let r = load(RECEIPT_RECORD)?; |
| 248 | // The policy the judge ran under must be retained byte for byte. |
| 249 | if !a.has(POLICY_RECORD) || a.bytes(POLICY_RECORD)?.is_none() { |
| 250 | return fail( |
| 251 | "evaluation_missing", |
| 252 | "record evaluation_policy absent or not retained", |
| 253 | ); |
| 254 | } |
| 255 | let policy_sha = a.sha(POLICY_RECORD)?.to_string(); |
| 256 | let policy = load(POLICY_RECORD)?; |
| 257 | // The evaluated subject is the change the daemon granted and read back, judged from the |
| 258 | // commit the task's source pin names. |
| 259 | let facts = ledger::facts(a)?; |
| 260 | let pin = if a.has("source_pin") { |
| 261 | a.json("source_pin")? |
| 262 | } else { |
| 263 | None |
| 264 | }; |
| 265 | let Some(parent) = pin.as_ref().and_then(|p| s(p, &["commit"])) else { |
| 266 | return fail( |
| 267 | "evaluation_parent_mismatch", |
| 268 | "no retained source_pin commit to bind the judged parent to", |
| 269 | ); |
| 270 | }; |
| 271 | core( |
| 272 | &r, |
| 273 | &policy_sha, |
| 274 | &policy, |
| 275 | judge_key, |
| 276 | &Want { |
| 277 | path: &facts.path, |
| 278 | content_sha256: &facts.content_sha256, |
| 279 | disk_sha256: &facts.disk_sha256, |
| 280 | parent_commit: parent, |
| 281 | pinned_policy_sha256: opts.policy_sha256.as_deref(), |
| 282 | }, |
| 283 | ) |
| 284 | } |
| 285 | |
| 286 | /// What the harness is about to propose: the file, its whole new bytes, the commit the workspace |
| 287 | /// is at (the judged parent), and the operator's pinned policy digest when it has one. |
| 288 | pub struct Expect<'a> { |
| 289 | pub path: &'a str, |
| 290 | pub content: &'a [u8], |
| 291 | pub parent_commit: &'a str, |
| 292 | pub policy_sha256: Option<&'a str>, |
| 293 | } |
| 294 | |
| 295 | /// What a receipt must match, from the audit (ledger facts) or from the harness (before a write). |
| 296 | struct Want<'a> { |
| 297 | path: &'a str, |
| 298 | content_sha256: &'a str, |
| 299 | disk_sha256: &'a str, |
| 300 | parent_commit: &'a str, |
| 301 | pinned_policy_sha256: Option<&'a str>, |
| 302 | } |
| 303 | |
| 304 | /// The harness gate before the write: the same checks as the audit, run on the judge's receipt |
| 305 | /// and policy bytes against exactly what is about to be proposed. Returns the refusal line on |
| 306 | /// failure. Nothing reaches the daemon unless this passes. |
| 307 | pub fn precheck( |
| 308 | receipt: &[u8], |
| 309 | policy: &[u8], |
| 310 | judge_key: &VerifyingKey, |
| 311 | want: &Expect, |
| 312 | ) -> Result<(), String> { |
| 313 | let r = crate::strict::parse(receipt) |
| 314 | .ok_or("FAIL evaluation_malformed: receipt is not strict JSON")?; |
| 315 | let p = crate::strict::parse(policy) |
| 316 | .ok_or("FAIL evaluation_malformed: policy is not strict JSON")?; |
| 317 | let content = hex::encode(Sha256::digest(want.content)); |
| 318 | core( |
| 319 | &r, |
| 320 | &hex::encode(Sha256::digest(policy)), |
| 321 | &p, |
| 322 | Some(judge_key), |
| 323 | &Want { |
| 324 | path: want.path, |
| 325 | content_sha256: &content, |
| 326 | disk_sha256: &content, |
| 327 | parent_commit: want.parent_commit, |
| 328 | pinned_policy_sha256: want.policy_sha256, |
| 329 | }, |
| 330 | ) |
| 331 | .map_err(|Fail(line)| line) |
| 332 | } |
| 333 | |
| 334 | /// Every check on a parsed receipt and policy. `w.content_sha256` is what the change carries and |
| 335 | /// `w.disk_sha256` what was read back after the write (the same value before the write). |
| 336 | fn core( |
| 337 | r: &Value, |
| 338 | policy_sha256: &str, |
| 339 | policy: &Value, |
| 340 | judge_key: Option<&VerifyingKey>, |
| 341 | w: &Want, |
| 342 | ) -> Result<(), Fail> { |
| 343 | let (path, content_sha256, disk_sha256) = (w.path, w.content_sha256, w.disk_sha256); |
| 344 | match r.get("format_version").and_then(Value::as_u64) { |
| 345 | None | Some(1) => { |
| 346 | return fail( |
| 347 | "evaluation_v1_insufficient", |
| 348 | "a version 1 receipt does not bind the evaluated change", |
| 349 | ) |
| 350 | } |
| 351 | Some(2) => {} |
| 352 | Some(v) => return fail("unsupported_evaluation", format!("format_version={v}")), |
| 353 | } |
| 354 | let digest = receipt_digest_v2(r)?; |
| 355 | if s(r, &["receipt_digest"]) != Some(digest.as_str()) { |
| 356 | return fail( |
| 357 | "evaluation_signature_bad", |
| 358 | "receipt_digest does not match the receipt's fields", |
| 359 | ); |
| 360 | } |
| 361 | let Some(key) = judge_key else { |
| 362 | return fail( |
| 363 | "evaluation_untrusted", |
| 364 | "no judge public key supplied; a receipt never carries the key that verifies it", |
| 365 | ); |
| 366 | }; |
| 367 | verify_signature(r, &digest, key)?; |
| 368 | |
| 369 | let g = R(r); |
| 370 | let subject_path = g.str(&["binding", "subject_path"])?; |
| 371 | if subject_path != path { |
| 372 | return fail( |
| 373 | "evaluation_subject_mismatch", |
| 374 | format!("binding.subject_path={subject_path} vs ledger_grant.path={path}"), |
| 375 | ); |
| 376 | } |
| 377 | let subject = g.str(&["binding", "subject_sha256"])?; |
| 378 | if !is_hex64(subject) || subject != content_sha256 || subject != disk_sha256 { |
| 379 | return fail( |
| 380 | "evaluation_subject_mismatch", |
| 381 | "binding.subject_sha256 vs ledger_grant.content_sha256 and ledger_ack.disk_sha256", |
| 382 | ); |
| 383 | } |
| 384 | // The tree the judge compared against is the commit the change was made from. |
| 385 | let parent = g.str(&["parent_id"])?; |
| 386 | if parent != w.parent_commit { |
| 387 | return fail( |
| 388 | "evaluation_parent_mismatch", |
| 389 | format!( |
| 390 | "parent_id={parent} vs source_pin.commit={}", |
| 391 | w.parent_commit |
| 392 | ), |
| 393 | ); |
| 394 | } |
| 395 | |
| 396 | // The policy the judge ran under is the retained policy, and it pins the holdout set. |
| 397 | if policy_sha256 != g.str(&["binding", "policy_sha256"])? { |
| 398 | return fail( |
| 399 | "evaluation_policy_mismatch", |
| 400 | "binding.policy_sha256 vs retained evaluation_policy", |
| 401 | ); |
| 402 | } |
| 403 | // When the operator pins a policy, the judge must have run under exactly that one. |
| 404 | if let Some(pinned) = w.pinned_policy_sha256 { |
| 405 | if policy_sha256 != pinned { |
| 406 | return fail( |
| 407 | "evaluation_policy_mismatch", |
| 408 | "retained evaluation_policy is not the operator's pinned policy", |
| 409 | ); |
| 410 | } |
| 411 | } |
| 412 | let protected = policy |
| 413 | .get("protected_paths") |
| 414 | .and_then(Value::as_array) |
| 415 | .into_iter() |
| 416 | .flatten() |
| 417 | .filter_map(Value::as_str) |
| 418 | .find(|p| { |
| 419 | let p = p.trim_end_matches('/'); |
| 420 | path == p || path.starts_with(&format!("{p}/")) |
| 421 | }); |
| 422 | if let Some(p) = protected { |
| 423 | return fail( |
| 424 | "evaluation_policy_mismatch", |
| 425 | format!("{path} is under protected path {p} in evaluation_policy"), |
| 426 | ); |
| 427 | } |
| 428 | let allowed = policy |
| 429 | .get("allowed_targets") |
| 430 | .and_then(Value::as_array) |
| 431 | .is_some_and(|t| t.iter().any(|x| x.as_str() == Some(path))); |
| 432 | if !allowed { |
| 433 | return fail( |
| 434 | "evaluation_policy_mismatch", |
| 435 | format!("{path} is not an allowed target in evaluation_policy"), |
| 436 | ); |
| 437 | } |
| 438 | if policy.get("require_admitted") != Some(&Value::Bool(true)) { |
| 439 | return fail( |
| 440 | "evaluation_policy_mismatch", |
| 441 | "evaluation_policy.require_admitted must be true", |
| 442 | ); |
| 443 | } |
| 444 | let Some(ratio) = policy |
| 445 | .get("min_holdout_pass_ratio") |
| 446 | .and_then(Value::as_f64) |
| 447 | .filter(|x| *x > 0.0 && *x <= 1.0) |
| 448 | else { |
| 449 | return fail( |
| 450 | "evaluation_policy_mismatch", |
| 451 | "evaluation_policy.min_holdout_pass_ratio", |
| 452 | ); |
| 453 | }; |
| 454 | if s(policy, &["holdout_set_sha256"]) != Some(g.str(&["binding", "holdout_set_sha256"])?) { |
| 455 | return fail( |
| 456 | "evaluation_holdout_mismatch", |
| 457 | "binding.holdout_set_sha256 vs evaluation_policy.holdout_set_sha256", |
| 458 | ); |
| 459 | } |
| 460 | let b = r.get("binding").unwrap_or(&Value::Null); |
| 461 | let total = num_u64( |
| 462 | b.get("holdouts_total").unwrap_or(&Value::Null), |
| 463 | "holdouts_total", |
| 464 | )?; |
| 465 | let passed = num_u64( |
| 466 | b.get("holdouts_passed").unwrap_or(&Value::Null), |
| 467 | "holdouts_passed", |
| 468 | )?; |
| 469 | if !g.bool(&["admitted"])? { |
| 470 | return fail( |
| 471 | "evaluation_below_threshold", |
| 472 | "the judge did not admit the change", |
| 473 | ); |
| 474 | } |
| 475 | if total == 0 || passed > total || (passed as f64) < ratio * (total as f64) { |
| 476 | return fail( |
| 477 | "evaluation_below_threshold", |
| 478 | format!("holdouts passed {passed}/{total} below policy ratio {ratio}"), |
| 479 | ); |
| 480 | } |
| 481 | Ok(()) |
| 482 | } |