From ae61dc158e842f9c65afdc152709c5577e6ec875 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 23:37:27 +0000 Subject: [PATCH 1/3] fix(integrity): an Uninitialized report fails the dispatch gate Owner decision D9 (2026-11-30): the gate accepts Verified only. An Uninitialized report comes from a placeholder manifest hash, which pins nothing, so it no longer passes. The test uninitialized_entry_fails was red against the old gate and is green now. No production path changes today: all 17 entries in the shipped manifest are placeholders, and nothing in src/ attaches an IntegrityChecker. A prover missing from the manifest, and no checker, still pass. Each is closed by its own change. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019a95kk88TZ1iegsBK3kox3 --- docs/PROOF-STATUS.adoc | 13 ++++++++----- src/rust/integrity/solver_integrity.rs | 25 ++++++++++++++----------- 2 files changed, 22 insertions(+), 16 deletions(-) diff --git a/docs/PROOF-STATUS.adoc b/docs/PROOF-STATUS.adoc index d36fd97d..6c61f7dc 100644 --- a/docs/PROOF-STATUS.adoc +++ b/docs/PROOF-STATUS.adoc @@ -190,11 +190,14 @@ now call one `+integrity_gate+` (`+src/rust/integrity/solver_integrity.rs+`). It parses each key into a `+ProverKind+`, and it fails when any matching report is bad, whatever order the reports come in. Tests: `+gate_tests+` in that file. A test also checks that every key in the shipped manifest names a -prover. Tested only, not proved. Three of the four paths above are unchanged -until the owner decides which statuses the gate accepts (D9 in the placement -ledger, `+docs/PROOF-PLACEMENT.adoc+`): `+Uninitialized+`, a prover missing -from the manifest, and no checker. The fourth path is unreachable: -`+verify_all()+` has no error path. +prover. Tested only, not proved. The owner ruled on 2026-11-30 (D9 in the +placement ledger, `+docs/PROOF-PLACEMENT.adoc+`) that the gate accepts +`+Verified+` only. `+Uninitialized+` now fails the gate (test +`+uninitialized_entry_fails+`). A prover missing from the manifest, and no +checker, still pass; each is closed by its own change. The fourth path is +unreachable: `+verify_all()+` has no error path. All 17 entries in the +shipped manifest are placeholders, and no code in `+src/+` attaches a checker, +so no production path reaches the gate with reports today. Row stays `+open+` until a Creusot or Verus run on shipped code yields a receipt with a commit hash. diff --git a/src/rust/integrity/solver_integrity.rs b/src/rust/integrity/solver_integrity.rs index ba68b060..f25140be 100644 --- a/src/rust/integrity/solver_integrity.rs +++ b/src/rust/integrity/solver_integrity.rs @@ -402,12 +402,12 @@ pub fn manifest_key_prover(key: &str) -> Option { /// A report counts for `prover` when its manifest key parses to that /// `ProverKind` (so `lean4` counts for `Lean` and `hol_light` for /// `HOLLight`, and `mizar` does not count for `MizAR`). The gate fails when -/// any counting report is not `Verified` or `Uninitialized`, whatever order -/// the reports come in. +/// any counting report is not `Verified`, whatever order the reports come +/// in. `Uninitialized` (a placeholder manifest hash) fails: it pins nothing +/// (owner decision D9, 2026-11-30). /// -/// Unchanged from the code this replaces, pending owner decision D9: with -/// no checker (`reports` is `None`) or no counting report the gate passes, -/// and `Uninitialized` passes. +/// Still passing, each to be closed by its own change under D9: no checker +/// (`reports` is `None`) and no counting report. pub fn integrity_gate( reports: Option<&[SolverIntegrityReport]>, prover: crate::provers::ProverKind, @@ -418,12 +418,7 @@ pub fn integrity_gate( reports .iter() .filter(|r| manifest_key_prover(&r.name) == Some(prover)) - .all(|r| { - matches!( - r.status, - IntegrityStatus::Verified | IntegrityStatus::Uninitialized - ) - }) + .all(|r| r.status == IntegrityStatus::Verified) } #[cfg(test)] mod tests { @@ -596,6 +591,14 @@ mod gate_tests { } } + /// D9 (owner, 2026-11-30): a placeholder manifest hash pins nothing, so an + /// Uninitialized report does not pass the gate. + #[test] + fn uninitialized_entry_fails() { + let reports = vec![report("lean4", IntegrityStatus::Uninitialized)]; + assert!(!integrity_gate(Some(&reports), ProverKind::Lean)); + } + #[test] fn verified_entry_passes() { let reports = vec![report("lean4", IntegrityStatus::Verified)]; From f5352e2acf9863eb6d818161f812bf829cdd1996 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 30 Nov 2026 23:39:04 +0000 Subject: [PATCH 2/3] fix(integrity): with a checker attached, an unlisted prover fails the gate Owner decision D9 (2026-11-30): the gate accepts Verified only. With a checker attached, a prover that no manifest key names has no pinned binary, so the gate now fails instead of assuming ok. The test unlisted_prover_fails was red against the previous gate and is green now. The shipped manifest lists 17 solvers. Once a checker is attached, every other prover gets solver_integrity_ok = false (Level1) until it is listed. No production path attaches a checker today. The no-checker path still passes, pending a further owner decision. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019a95kk88TZ1iegsBK3kox3 --- docs/PROOF-STATUS.adoc | 5 +++-- src/rust/integrity/solver_integrity.rs | 21 +++++++++++++++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/docs/PROOF-STATUS.adoc b/docs/PROOF-STATUS.adoc index 6c61f7dc..3a7f6c08 100644 --- a/docs/PROOF-STATUS.adoc +++ b/docs/PROOF-STATUS.adoc @@ -193,8 +193,9 @@ that file. A test also checks that every key in the shipped manifest names a prover. Tested only, not proved. The owner ruled on 2026-11-30 (D9 in the placement ledger, `+docs/PROOF-PLACEMENT.adoc+`) that the gate accepts `+Verified+` only. `+Uninitialized+` now fails the gate (test -`+uninitialized_entry_fails+`). A prover missing from the manifest, and no -checker, still pass; each is closed by its own change. The fourth path is +`+uninitialized_entry_fails+`). With a checker attached, a prover missing from +the manifest now fails too (test `+unlisted_prover_fails+`). No checker still +passes, pending a further owner decision. The fourth path is unreachable: `+verify_all()+` has no error path. All 17 entries in the shipped manifest are placeholders, and no code in `+src/+` attaches a checker, so no production path reaches the gate with reports today. diff --git a/src/rust/integrity/solver_integrity.rs b/src/rust/integrity/solver_integrity.rs index f25140be..2c0aeb21 100644 --- a/src/rust/integrity/solver_integrity.rs +++ b/src/rust/integrity/solver_integrity.rs @@ -406,8 +406,11 @@ pub fn manifest_key_prover(key: &str) -> Option { /// in. `Uninitialized` (a placeholder manifest hash) fails: it pins nothing /// (owner decision D9, 2026-11-30). /// -/// Still passing, each to be closed by its own change under D9: no checker -/// (`reports` is `None`) and no counting report. +/// With a checker attached, a prover with no counting report fails: no +/// binary is pinned for it (D9). +/// +/// Still passing, pending a further owner decision: no checker +/// (`reports` is `None`). pub fn integrity_gate( reports: Option<&[SolverIntegrityReport]>, prover: crate::provers::ProverKind, @@ -415,10 +418,11 @@ pub fn integrity_gate( let Some(reports) = reports else { return true; }; - reports + let mut counting = reports .iter() .filter(|r| manifest_key_prover(&r.name) == Some(prover)) - .all(|r| r.status == IntegrityStatus::Verified) + .peekable(); + counting.peek().is_some() && counting.all(|r| r.status == IntegrityStatus::Verified) } #[cfg(test)] mod tests { @@ -599,6 +603,15 @@ mod gate_tests { assert!(!integrity_gate(Some(&reports), ProverKind::Lean)); } + /// D9 (owner, 2026-11-30): with a checker attached, a prover that has no + /// manifest entry has no pinned binary, so it does not pass the gate. + #[test] + fn unlisted_prover_fails() { + let reports = vec![report("z3", IntegrityStatus::Verified)]; + assert!(!integrity_gate(Some(&reports), ProverKind::Lean)); + assert!(!integrity_gate(Some(&[]), ProverKind::Lean)); + } + #[test] fn verified_entry_passes() { let reports = vec![report("lean4", IntegrityStatus::Verified)]; From de383a6bafd890a11621b893772252ca36f373d1 Mon Sep 17 00:00:00 2001 From: "Jonathan D.A. Jewell" <6759885+hyperpolymath@users.noreply.github.com> Date: Tue, 1 Dec 2026 20:11:54 +0000 Subject: [PATCH 3/3] feat(integrity): `echidna integrity pin` and `check` for the solver manifest (#539) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Stacked on #538 (← #537 ← #536). This is step 1 of three for the last fail-open path in the dispatch integrity gate, "no checker configured". On 2026-11-30 the owner chose to wire a checker in before closing that path. A checker is useless today: all 17 entries in `config/solver-manifest.toml` hold `PLACEHOLDER_COMPUTE_ON_FIRST_RUN`, and nothing ever computes a hash. Under D9 an unpinned binary fails the gate, so a pinning step must exist first. This PR adds it. ## Changes - `echidna integrity pin [--manifest PATH] [--solver NAME]... [--force] [--dry-run]`. An explicit operator step; dispatch never pins, so there is no trust on first use. - It replaces a placeholder with the SHAKE3-512 of the binary found now. - It refuses, writing nothing, when a real hash differs from the binary, which may mean tampering. `--force` overrides. - It refuses when a binary cannot be read, or when a solver named with `--solver` is not found. - It rewrites the file through `toml_edit`, so comments, order and every other field are kept. - `echidna integrity check [--manifest PATH]` prints each binary's status and exits non-zero on `Tampered`. - `src/rust/integrity/solver_integrity.rs` gains: - `PinOutcome` and `IntegrityChecker::pin_entries`, which computes and writes nothing. - `apply_pins`, which rejects an unknown solver. - `default_manifest_path` (`$ECHIDNA_SOLVER_MANIFEST`, else `config/solver-manifest.toml`). - `PLACEHOLDER_PREFIX`. - `docs/ENV-VARS.adoc` documents `ECHIDNA_SOLVER_MANIFEST`. - `toml_edit = "0.25"` becomes a direct dependency; it was already in `Cargo.lock`. Next in the stack: load the manifest at startup and attach the checker (failing loudly when it is unreadable), then close the no-checker path. ## RSR Quality Checklist ### Required - [x] Tests pass (`cargo test --lib`: 1348 passed, 0 failed, 3 ignored) - [x] Code is formatted (`cargo fmt --check`) - [x] Linter is clean (`cargo clippy --all-targets -- -D warnings`: exit 0) - [x] No banned language patterns - [x] No `unsafe` blocks - [x] No banned functions - [x] SPDX license headers present (new `src/rust/cli/integrity.rs`: MPL-2.0) - [x] No secrets ### As Applicable - [x] Documentation updated (`docs/ENV-VARS.adoc`) - [x] New dependencies reviewed for licence compatibility (`toml_edit`: MIT OR Apache-2.0) ## Testing `pin_tests` (8 tests) cover: - a placeholder is pinned; - a matching hash is left unchanged; - a differing hash is refused without `--force` and replaced with it; - an absent binary is reported as not found; - an unknown `--solver` is an error; - only the named solvers are pinned; - `apply_pins` keeps the rest of the file byte for byte and rejects an unknown solver. The last test caught a real bug: `toml_edit`'s `Item::get_mut` creates a missing table, so an unknown solver was silently added. I also ran the built binary end to end against a scratch manifest (a copy of `/bin/true` as `z3`, plus an absent `cvc5`): | Step | Result | |---|---| | `pin --dry-run` | reports `z3: pinned`, writes nothing, exit 0 | | `pin` | writes the hash; comments kept; exit 0 | | `check` | `z3: Verified`, `cvc5: Missing`, exit 0 | | append a byte to the binary, `check` | `z3: Tampered`, exit 1 | | `pin` | `REFUSED`, manifest byte-identical, exit 1 | | `pin --solver cvc5` | `no binary found`, exit 1 | | `pin --force` | `REPINNED`, exit 0 | CI note: Rust CI ends in `startup_failure` on `main` too (#533 is investigating), so `CI/gate` will not report until that is fixed. The results above are local runs on this commit. --- _Generated by [Claude Code](https://claude.ai/code)_ --------- Co-authored-by: Claude --- Cargo.lock | 2 + Cargo.toml | 1 + docs/ENV-VARS.adoc | 8 + src/rust/cli/args.rs | 34 +++ src/rust/cli/integrity.rs | 148 +++++++++++++ src/rust/cli/mod.rs | 2 + src/rust/integrity/solver_integrity.rs | 276 ++++++++++++++++++++++++- src/rust/main.rs | 4 + 8 files changed, 474 insertions(+), 1 deletion(-) create mode 100644 src/rust/cli/integrity.rs diff --git a/Cargo.lock b/Cargo.lock index 5f8b6c37..6f729290 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1062,6 +1062,7 @@ dependencies = [ "tokio", "tokio-test", "toml", + "toml_edit", "tower", "tower-http 0.7.0", "tracing", @@ -3591,6 +3592,7 @@ dependencies = [ "indexmap", "toml_datetime", "toml_parser", + "toml_writer", "winnow", ] diff --git a/Cargo.toml b/Cargo.toml index b4c1f0e5..95c284ef 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ futures = "0.3" serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "1.1" +toml_edit = "0.25" # Error handling anyhow = "1" diff --git a/docs/ENV-VARS.adoc b/docs/ENV-VARS.adoc index 8b069026..3e4872c2 100644 --- a/docs/ENV-VARS.adoc +++ b/docs/ENV-VARS.adoc @@ -64,6 +64,14 @@ environment override for this one. |`+APP_PORT+` / `+APP_HOST+` |host:port |`+[::]` / `+8081+` |`+container/entrypoint.sh+` |Read by the container entrypoint and passed to `+echidna server+` as flags. The binary itself does not read them. + +|`+ECHIDNA_SOLVER_MANIFEST+` |path |`+config/solver-manifest.toml+` +(relative to the working directory) |`+src/rust/integrity/solver_integrity.rs+` +(`+default_manifest_path+`), `+echidna integrity pin+` and +`+echidna integrity check+` |The solver binary manifest. An empty value +means the default. `+echidna integrity pin+` replaces placeholder hashes +with the SHAKE3-512 of the binaries found now; it refuses to change a real +hash that differs unless given `+--force+`. |=== === Training & evaluation (Julia) diff --git a/src/rust/cli/args.rs b/src/rust/cli/args.rs index 384622df..8611c315 100644 --- a/src/rust/cli/args.rs +++ b/src/rust/cli/args.rs @@ -192,6 +192,12 @@ pub(crate) enum Commands { op: DesignOp, }, + /// Pin solver binary hashes into the manifest, or check binaries against it + Integrity { + #[command(subcommand)] + op: IntegrityOp, + }, + /// Suggest tactic variants that close a failing lemma Suggest { /// Target in `:` form, e.g. `Foo.thy:bar` @@ -436,3 +442,31 @@ pub(crate) enum DesignOp { adopt_threshold: i64, }, } + +#[derive(Subcommand)] +pub(crate) enum IntegrityOp { + /// Replace placeholder hashes with the SHAKE3-512 of the binaries found + /// now. A real hash that differs is refused unless `--force` is given. + Pin { + /// Manifest path (default: $ECHIDNA_SOLVER_MANIFEST, else + /// config/solver-manifest.toml) + #[arg(long)] + manifest: Option, + /// Pin only these solvers (manifest keys); repeatable + #[arg(long)] + solver: Vec, + /// Replace a real hash that differs from the binary + #[arg(long)] + force: bool, + /// Report what would change without writing the manifest + #[arg(long)] + dry_run: bool, + }, + /// Hash every listed binary and print its status. Fails on `Tampered`. + Check { + /// Manifest path (default: $ECHIDNA_SOLVER_MANIFEST, else + /// config/solver-manifest.toml) + #[arg(long)] + manifest: Option, + }, +} diff --git a/src/rust/cli/integrity.rs b/src/rust/cli/integrity.rs new file mode 100644 index 00000000..f6265def --- /dev/null +++ b/src/rust/cli/integrity.rs @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: MPL-2.0 +// SPDX-FileCopyrightText: 2026 Jonathan D.A. Jewell + +//! `echidna integrity`: pin solver binary hashes into the manifest, and +//! check the installed binaries against it. + +use super::IntegrityOp; +use anyhow::{Context, Result}; +use echidna::integrity::solver_integrity::{ + apply_pins, default_manifest_path, IntegrityChecker, IntegrityStatus, PinOutcome, +}; +use std::path::PathBuf; + +/// Integrity command. +/// +/// # Errors +/// +/// `pin` fails when the manifest cannot be read, parsed or written, when a +/// named solver is not in the manifest or not found, when a binary cannot be +/// read, or when a real hash differs from the binary and `--force` was not +/// given. It writes nothing in the last case. `check` fails when the +/// manifest cannot be read or when any binary is `Tampered`. +pub(crate) async fn integrity_command(op: IntegrityOp) -> Result<()> { + match op { + IntegrityOp::Pin { + manifest, + solver, + force, + dry_run, + } => pin( + manifest.unwrap_or_else(default_manifest_path), + &solver, + force, + dry_run, + ), + IntegrityOp::Check { manifest } => { + check(manifest.unwrap_or_else(default_manifest_path)).await + }, + } +} + +fn pin(path: PathBuf, solver: &[String], force: bool, dry_run: bool) -> Result<()> { + let checker = IntegrityChecker::from_manifest_file(&path)?; + let outcomes = checker.pin_entries(solver, force)?; + + let mut pins = std::collections::BTreeMap::new(); + let mut failures = Vec::new(); + for (name, outcome) in &outcomes { + match outcome { + PinOutcome::Pinned { hash, path } => { + println!("{name}: pinned {} ({})", short(hash), path.display()); + }, + PinOutcome::Unchanged { path } => { + println!("{name}: unchanged ({})", path.display()); + }, + PinOutcome::Repinned { old, hash, path } => { + println!( + "{name}: REPINNED {} -> {} ({}, --force)", + short(old), + short(hash), + path.display() + ); + }, + PinOutcome::Refused { + old, + computed, + path, + } => { + println!( + "{name}: REFUSED: manifest {} but binary {} ({})", + short(old), + short(computed), + path.display() + ); + failures.push(format!( + "{name}: the binary differs from its pinned hash (possible tampering); \ + re-pin with --force only if the change is expected" + )); + }, + PinOutcome::NotFound => { + println!("{name}: not found, left as is"); + if solver.contains(name) { + failures.push(format!("{name}: no binary found")); + } + }, + PinOutcome::Unreadable { path, error } => { + println!("{name}: UNREADABLE ({}): {error}", path.display()); + failures.push(format!("{name}: binary cannot be read")); + }, + } + if let Some(hash) = outcome.new_hash() { + pins.insert(name.clone(), hash.to_string()); + } + } + + if !failures.is_empty() { + anyhow::bail!( + "integrity pin wrote nothing to {}:\n {}", + path.display(), + failures.join("\n ") + ); + } + if pins.is_empty() { + println!("nothing to pin in {}", path.display()); + return Ok(()); + } + if dry_run { + println!( + "dry run: {} hash(es) not written to {}", + pins.len(), + path.display() + ); + return Ok(()); + } + let text = std::fs::read_to_string(&path) + .with_context(|| format!("Failed to read solver manifest: {}", path.display()))?; + let updated = apply_pins(&text, &pins)?; + std::fs::write(&path, updated) + .with_context(|| format!("Failed to write solver manifest: {}", path.display()))?; + println!("wrote {} hash(es) to {}", pins.len(), path.display()); + Ok(()) +} + +async fn check(path: PathBuf) -> Result<()> { + let checker = IntegrityChecker::from_manifest_file(&path)?; + let mut reports = checker.verify_all().await?; + reports.sort_by(|a, b| a.name.cmp(&b.name)); + let mut tampered = Vec::new(); + for r in &reports { + let at = r + .actual_path + .as_ref() + .map(|p| format!(" ({})", p.display())) + .unwrap_or_default(); + println!("{}: {:?}{at}", r.name, r.status); + if r.status == IntegrityStatus::Tampered { + tampered.push(r.name.clone()); + } + } + if !tampered.is_empty() { + anyhow::bail!("tampered solver binaries: {}", tampered.join(", ")); + } + Ok(()) +} + +fn short(hash: &str) -> &str { + hash.get(..16).unwrap_or(hash) +} diff --git a/src/rust/cli/mod.rs b/src/rust/cli/mod.rs index ecb5cc5e..ff7d26f8 100644 --- a/src/rust/cli/mod.rs +++ b/src/rust/cli/mod.rs @@ -8,6 +8,7 @@ mod args; mod corpus; mod design; +mod integrity; mod lexicon; mod prove; mod provers; @@ -19,6 +20,7 @@ mod verify; pub(crate) use args::*; pub(crate) use corpus::*; pub(crate) use design::*; +pub(crate) use integrity::*; pub(crate) use lexicon::*; pub(crate) use prove::*; pub(crate) use provers::*; diff --git a/src/rust/integrity/solver_integrity.rs b/src/rust/integrity/solver_integrity.rs index 2c0aeb21..6f549241 100644 --- a/src/rust/integrity/solver_integrity.rs +++ b/src/rust/integrity/solver_integrity.rs @@ -237,7 +237,7 @@ impl IntegrityChecker { }; // Check if manifest hash is a placeholder - if entry.shake3_512.starts_with("PLACEHOLDER") { + if entry.shake3_512.starts_with(PLACEHOLDER_PREFIX) { info!( "Solver {} has placeholder hash, computing initial hash", name @@ -424,6 +424,134 @@ pub fn integrity_gate( .peekable(); counting.peek().is_some() && counting.all(|r| r.status == IntegrityStatus::Verified) } + +/// A manifest hash that starts with this is a placeholder: it pins nothing. +pub const PLACEHOLDER_PREFIX: &str = "PLACEHOLDER"; + +/// The environment variable that names the solver manifest. +pub const SOLVER_MANIFEST_ENV: &str = "ECHIDNA_SOLVER_MANIFEST"; + +/// The solver manifest path: `$ECHIDNA_SOLVER_MANIFEST` when set and not +/// empty, otherwise `config/solver-manifest.toml` relative to the working +/// directory. +pub fn default_manifest_path() -> PathBuf { + match std::env::var_os(SOLVER_MANIFEST_ENV) { + Some(p) if !p.is_empty() => PathBuf::from(p), + _ => PathBuf::from("config/solver-manifest.toml"), + } +} + +/// What `IntegrityChecker::pin_entries` found for one manifest entry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PinOutcome { + /// The placeholder is to be replaced by the computed hash. + Pinned { hash: String, path: PathBuf }, + /// The manifest already holds the computed hash. + Unchanged { path: PathBuf }, + /// A real manifest hash differs from the binary and `force` was given: + /// the computed hash replaces it. + Repinned { + old: String, + hash: String, + path: PathBuf, + }, + /// A real manifest hash differs from the binary and `force` was not + /// given: the manifest is left as it is. This can mean tampering. + Refused { + old: String, + computed: String, + path: PathBuf, + }, + /// No binary was found; the manifest entry is left as it is. + NotFound, + /// A binary was found but could not be read. + Unreadable { path: PathBuf, error: String }, +} + +impl PinOutcome { + /// The hash to write into the manifest, if any. + pub fn new_hash(&self) -> Option<&str> { + match self { + PinOutcome::Pinned { hash, .. } | PinOutcome::Repinned { hash, .. } => Some(hash), + _ => None, + } + } +} + +impl IntegrityChecker { + /// Compute what pinning would do for each manifest entry, or for the + /// entries named in `only` when it is not empty. Writes nothing. + /// + /// A placeholder is pinned to the SHAKE3-512 of the binary found now. + /// A real hash that differs is replaced only with `force`. This is an + /// explicit operator step; dispatch never pins. + pub fn pin_entries( + &self, + only: &[String], + force: bool, + ) -> Result> { + for name in only { + if !self.manifest.solvers.contains_key(name) { + anyhow::bail!("solver {name:?} is not in the manifest"); + } + } + let mut out = std::collections::BTreeMap::new(); + for (name, entry) in &self.manifest.solvers { + if !only.is_empty() && !only.contains(name) { + continue; + } + let outcome = match Self::find_solver_binary(entry) { + None => PinOutcome::NotFound, + Some(path) => match Self::compute_shake3_512(&path) { + Err(e) => PinOutcome::Unreadable { + path, + error: format!("{e:#}"), + }, + Ok(hash) if entry.shake3_512.starts_with(PLACEHOLDER_PREFIX) => { + PinOutcome::Pinned { hash, path } + }, + Ok(hash) if hash == entry.shake3_512 => PinOutcome::Unchanged { path }, + Ok(hash) if force => PinOutcome::Repinned { + old: entry.shake3_512.clone(), + hash, + path, + }, + Ok(computed) => PinOutcome::Refused { + old: entry.shake3_512.clone(), + computed, + path, + }, + }, + }; + out.insert(name.clone(), outcome); + } + Ok(out) + } +} + +/// Rewrite the `shake3_512` value of each solver named in `pins`, keeping +/// every comment, every other field and the order of the file. Fails when a +/// named solver has no `[solvers.]` table in `text`. +pub fn apply_pins(text: &str, pins: &std::collections::BTreeMap) -> Result { + let mut doc: toml_edit::DocumentMut = text + .parse() + .context("Failed to parse solver manifest TOML")?; + for (name, hash) in pins { + let item = doc + .get_mut("solvers") + .and_then(|s| s.as_table_like_mut()) + .and_then(|s| s.get_mut(name)) + .and_then(|e| e.as_table_like_mut()) + .and_then(|e| e.get_mut("shake3_512")) + .with_context(|| format!("solver {name:?} has no shake3_512 in the manifest"))?; + let decor = item.as_value().map(|v| v.decor().clone()); + *item = toml_edit::value(hash.as_str()); + if let (Some(decor), Some(v)) = (decor, item.as_value_mut()) { + *v.decor_mut() = decor; + } + } + Ok(doc.to_string()) +} #[cfg(test)] mod tests { use super::*; @@ -634,3 +762,149 @@ mod gate_tests { } } } + +#[cfg(test)] +mod pin_tests { + use super::*; + use std::io::Write; + use tempfile::NamedTempFile; + + fn entry(path: &Path, hash: &str) -> SolverManifestEntry { + SolverManifestEntry { + version: "1".to_string(), + shake3_512: hash.to_string(), + path: path.display().to_string(), + fallback_paths: vec![], + } + } + + fn binary(bytes: &[u8]) -> NamedTempFile { + let mut f = NamedTempFile::new().expect("temp file"); + f.write_all(bytes).expect("write"); + f + } + + fn checker(entries: Vec<(&str, SolverManifestEntry)>) -> IntegrityChecker { + IntegrityChecker::new(SolverManifest { + solvers: entries + .into_iter() + .map(|(k, e)| (k.to_string(), e)) + .collect(), + }) + } + + #[test] + fn placeholder_is_pinned_to_the_computed_hash() { + let bin = binary(b"solver one"); + let want = IntegrityChecker::compute_shake3_512(bin.path()).unwrap(); + let c = checker(vec![("z3", entry(bin.path(), PLACEHOLDER_PREFIX))]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!( + out["z3"], + PinOutcome::Pinned { + hash: want, + path: bin.path().to_path_buf() + } + ); + } + + #[test] + fn matching_real_hash_is_unchanged() { + let bin = binary(b"solver two"); + let h = IntegrityChecker::compute_shake3_512(bin.path()).unwrap(); + let c = checker(vec![("z3", entry(bin.path(), &h))]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!( + out["z3"], + PinOutcome::Unchanged { + path: bin.path().to_path_buf() + } + ); + } + + /// A real hash that no longer matches is a possible tamper: never + /// overwritten silently. + #[test] + fn differing_real_hash_is_refused_without_force() { + let bin = binary(b"solver three"); + let h = IntegrityChecker::compute_shake3_512(bin.path()).unwrap(); + let c = checker(vec![("z3", entry(bin.path(), "00"))]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!( + out["z3"], + PinOutcome::Refused { + old: "00".to_string(), + computed: h.clone(), + path: bin.path().to_path_buf() + } + ); + let forced = c.pin_entries(&[], true).unwrap(); + assert_eq!( + forced["z3"], + PinOutcome::Repinned { + old: "00".to_string(), + hash: h, + path: bin.path().to_path_buf() + } + ); + } + + #[test] + fn absent_binary_is_not_found() { + let c = checker(vec![( + "z3", + entry( + Path::new("/nonexistent/echidna-pin-test-z3"), + PLACEHOLDER_PREFIX, + ), + )]); + let out = c.pin_entries(&[], false).unwrap(); + assert_eq!(out["z3"], PinOutcome::NotFound); + } + + #[test] + fn unknown_solver_name_is_an_error() { + let c = checker(vec![]); + assert!(c.pin_entries(&["nosuch".to_string()], false).is_err()); + } + + #[test] + fn only_named_solvers_are_pinned() { + let a = binary(b"a"); + let b = binary(b"b"); + let c = checker(vec![ + ("z3", entry(a.path(), PLACEHOLDER_PREFIX)), + ("cvc5", entry(b.path(), PLACEHOLDER_PREFIX)), + ]); + let out = c.pin_entries(&["cvc5".to_string()], false).unwrap(); + assert_eq!(out.len(), 1); + assert!(out.contains_key("cvc5")); + } + + /// apply_pins rewrites only the hashes it is given, and keeps comments, + /// order and every other field. + #[test] + fn apply_pins_keeps_the_rest_of_the_file() { + let text = "# header comment\n\n[solvers.z3]\nversion = \"4\"\nshake3_512 = \"PLACEHOLDER_COMPUTE_ON_FIRST_RUN\"\npath = \"/usr/bin/z3\"\n\n# cvc5 note\n[solvers.cvc5]\nversion = \"1\"\nshake3_512 = \"PLACEHOLDER_COMPUTE_ON_FIRST_RUN\"\npath = \"/usr/bin/cvc5\"\n"; + let mut pins = std::collections::BTreeMap::new(); + pins.insert("z3".to_string(), "abcd".to_string()); + let out = apply_pins(text, &pins).unwrap(); + assert_eq!( + out, + text.replacen("PLACEHOLDER_COMPUTE_ON_FIRST_RUN", "abcd", 1) + ); + let parsed: SolverManifest = toml::from_str(&out).unwrap(); + assert_eq!(parsed.solvers["z3"].shake3_512, "abcd"); + assert!(parsed.solvers["cvc5"] + .shake3_512 + .starts_with(PLACEHOLDER_PREFIX)); + } + + #[test] + fn apply_pins_rejects_an_unknown_solver() { + let text = "[solvers.z3]\nversion = \"4\"\nshake3_512 = \"x\"\npath = \"/usr/bin/z3\"\n"; + let mut pins = std::collections::BTreeMap::new(); + pins.insert("cvc5".to_string(), "abcd".to_string()); + assert!(apply_pins(text, &pins).is_err()); + } +} diff --git a/src/rust/main.rs b/src/rust/main.rs index 7508555c..b38e648c 100644 --- a/src/rust/main.rs +++ b/src/rust/main.rs @@ -155,6 +155,10 @@ async fn main() -> Result<()> { design_command(op, &formatter).await?; }, + Commands::Integrity { op } => { + integrity_command(op).await?; + }, + Commands::Suggest { target, prover,