From bd753cb70e96f5a6590e5f44b313bb8efabf765f Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 01:52:58 +0000 Subject: [PATCH 1/3] feat(integrity): `echidna integrity pin` and `check` for the solver manifest Every entry in config/solver-manifest.toml holds PLACEHOLDER_COMPUTE_ON_FIRST_RUN, and nothing computed a hash. Owner decision D9 makes an unpinned binary fail the dispatch gate, so a pinning step has to exist before a checker is attached at startup. `echidna integrity pin` is an explicit operator step. Dispatch never pins (no trust on first use). It replaces a placeholder with the SHAKE3-512 of the binary found now. It refuses, and writes nothing, when a real hash differs from the binary, which may be tampering, unless --force is given. It also refuses when a binary cannot be read, or when a solver named with --solver is not found. --dry-run reports without writing. The rewrite goes through toml_edit, so comments and field order survive. `echidna integrity check` hashes every listed binary, prints its status and fails on Tampered. The manifest path is $ECHIDNA_SOLVER_MANIFEST, or else config/solver-manifest.toml (docs/ENV-VARS.adoc). toml_edit 0.25 becomes a direct dependency; it was already in Cargo.lock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019a95kk88TZ1iegsBK3kox3 --- 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..fc7aa1ce --- /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::*; +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, From ddbfd037fae5dc8cd6bcec38aec4611a0cdd19e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 01:58:56 +0000 Subject: [PATCH 2/3] feat(integrity): the server loads the solver manifest and attaches the checker Owner ruling 2026-11-30: wire a checker in before closing the no-checker path of the dispatch integrity gate. - echidna server loads the manifest from $ECHIDNA_SOLVER_MANIFEST, or else config/solver-manifest.toml, through build_dispatcher. It attaches the IntegrityChecker to the shared dispatcher, and it refuses to start when the manifest cannot be read. The error names the path, the variable and `echidna integrity pin`. - /api/verify_parallel used a fresh ProverDispatcher::new() per request, with no checker. It now uses the shared dispatcher in AppState. - Each dispatch hashes only the dispatching prover's binaries (IntegrityChecker::verify_for), not all 17 listed binaries (verify_all). - All six Containerfiles (nine runtime stages) copy the manifest to /app/config/ and set ECHIDNA_SOLVER_MANIFEST. - ARCHITECTURE, ENV-VARS and PROOF-STATUS R1 say what now runs. They also record that /api/verify does not go through the dispatcher. Tests: verify_for_checks_only_the_named_prover, a_missing_manifest_stops_the_server, the_shipped_manifest_loads. cargo test: 40 test binaries, 1897 passed, 0 failed. Clippy --all-targets with -D warnings is clean. Container images were not built (no podman here). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019a95kk88TZ1iegsBK3kox3 --- .containerization/Containerfile | 4 ++ .containerization/Containerfile.full | 4 ++ .containerization/Containerfile.mcp | 4 ++ .containerization/Containerfile.wave3 | 36 ++++++++++++++ Containerfile | 4 ++ container/Containerfile | 4 ++ docs/ARCHITECTURE.adoc | 16 +++--- docs/ENV-VARS.adoc | 7 +-- docs/PROOF-STATUS.adoc | 15 ++++-- src/rust/dispatch.rs | 6 +-- src/rust/integrity/solver_integrity.rs | 69 ++++++++++++++++++++++++++ src/rust/server/mod.rs | 48 +++++++++++++++++- src/rust/server/verify.rs | 9 ++-- 13 files changed, 204 insertions(+), 22 deletions(-) diff --git a/.containerization/Containerfile b/.containerization/Containerfile index 9122c3c6..99d2162a 100644 --- a/.containerization/Containerfile +++ b/.containerization/Containerfile @@ -108,6 +108,10 @@ WORKDIR /app # Copy echidna binary COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Copy Idris2 runtime if available (optional) COPY --from=idris2-builder /opt/idris2 /opt/idris2/ diff --git a/.containerization/Containerfile.full b/.containerization/Containerfile.full index 3bfb8abc..42f11bc8 100644 --- a/.containerization/Containerfile.full +++ b/.containerization/Containerfile.full @@ -208,6 +208,10 @@ WORKDIR /app # Copy echidna binary COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Copy Idris2 runtime (optional — may be empty if pack install failed) COPY --from=idris2-builder /opt/idris2 /opt/idris2/ diff --git a/.containerization/Containerfile.mcp b/.containerization/Containerfile.mcp index ef69531e..b6e840c8 100644 --- a/.containerization/Containerfile.mcp +++ b/.containerization/Containerfile.mcp @@ -136,6 +136,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml COPY --from=rust-builder /build/target/release/echidna-mcp /app/bin/echidna-mcp COPY --from=lean-installer /root/.elan /opt/elan COPY --from=isabelle-installer /opt/Isabelle2025-2 /opt/Isabelle2025-2 diff --git a/.containerization/Containerfile.wave3 b/.containerization/Containerfile.wave3 index 3dd3a6f6..ec5ce50c 100644 --- a/.containerization/Containerfile.wave3 +++ b/.containerization/Containerfile.wave3 @@ -157,6 +157,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Deterministic export tree (real binary if the GitHub download + smoke-test # succeeded, a one-file stub otherwise). A directory COPY never hard-fails. COPY --from=tamarin-installer /opt/tamarin-export/ /opt/tamarin/ @@ -269,6 +273,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml COPY --from=proverif-builder /opt/proverif-export/bin/proverif /usr/local/bin/proverif ENV PATH="/app/bin:/usr/local/bin:${PATH}" @@ -355,6 +363,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Copy the deterministic export tree (always exists: the real self-contained # bundle if the GitHub download succeeded, a one-file stub otherwise). A @@ -455,6 +467,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Copy OR-Tools libs/headers from the deterministic export tree (always # present — real content if the tarball downloaded, just .keep otherwise; @@ -573,6 +589,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Copy Poly/ML runtime (HOL4 loads ML code via poly at runtime) COPY --from=polyml-builder /opt/polyml /opt/polyml @@ -659,6 +679,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Copy ACL2 saved image and source tree (ACL2 loads books from its source tree) # Built in-place at /opt/acl2 → the saved_acl2 wrapper's baked core path and @@ -747,6 +771,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # Copy the Twelf installation (src tree + compiled heap + wrapper scripts) # Built in-place at /opt/twelf → the baked absolute heap path in @@ -874,6 +902,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml # The metamath-exe CLI verifier. The Rust backend execs bare `metamath` # (provers/mod.rs default_executable), resolved via PATH; /usr/local/bin is @@ -960,6 +992,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ WORKDIR /app COPY --from=rust-builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml COPY --from=imandra-installer /usr/local/bin/imandra /usr/local/bin/imandra ENV PATH="/app/bin:/usr/local/bin:${PATH}" diff --git a/Containerfile b/Containerfile index 5cf199d5..4461f861 100644 --- a/Containerfile +++ b/Containerfile @@ -100,6 +100,10 @@ RUN apk add --no-cache \ WORKDIR /app COPY --from=rust-builder /out/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml COPY --from=prover-installer /opt/z3/bin/z3 /app/bin/z3 COPY --from=prover-installer /opt/elan /opt/elan diff --git a/container/Containerfile b/container/Containerfile index bdb5a808..d078d2f6 100644 --- a/container/Containerfile +++ b/container/Containerfile @@ -58,6 +58,10 @@ RUN addgroup -S appuser && adduser -S appuser -G appuser WORKDIR /app COPY --from=builder /build/target/release/echidna /app/bin/echidna +# Solver integrity manifest: `echidna server` refuses to start without it. +# Pin installed binaries with `echidna integrity pin` (docs/ENV-VARS.adoc). +COPY config/solver-manifest.toml /app/config/solver-manifest.toml +ENV ECHIDNA_SOLVER_MANIFEST=/app/config/solver-manifest.toml COPY container/entrypoint.sh /app/entrypoint.sh RUN chmod +x /app/entrypoint.sh diff --git a/docs/ARCHITECTURE.adoc b/docs/ARCHITECTURE.adoc index 75b9dcaf..ce364577 100644 --- a/docs/ARCHITECTURE.adoc +++ b/docs/ARCHITECTURE.adoc @@ -112,12 +112,16 @@ link:handover/TODO.adoc[`+handover/TODO.adoc+`] for current state): [arabic] . *Integrity* (`+integrity/+`) — solver binary SHAKE3-512 + BLAKE3 -against `+config/solver-manifest.toml+`. *Caveat, 2026-11-01*: this step -runs only when a checker is attached, and nothing in the tree calls -`+with_integrity_checker+`; unconfigured, the pipeline treats integrity as -passing (`+dispatch.rs:632+`). The manifest also still holds -`+PLACEHOLDER_COMPUTE_ON_FIRST_RUN+` for every solver. Treat this step as -*not executed* until it is wired; see +against `+config/solver-manifest.toml+`. *Status, 2026-12-01*: `+echidna server+` loads the manifest at start-up +(`+$ECHIDNA_SOLVER_MANIFEST+`, else `+config/solver-manifest.toml+`) and refuses +to start without it. It attaches the checker to the shared dispatcher used by +`+/api/verify_parallel+` and, under `+verisim+`, `+/api/prove+`. Each dispatch +hashes only the dispatching prover's binaries (`+IntegrityChecker::verify_for+`). +The gate (`+integrity_gate+`) accepts `+Verified+` only (owner decision D9). +`+/api/verify+`, the REPL and the CLI do not go through the dispatcher, so +no integrity step runs for them. The shipped manifest still holds +`+PLACEHOLDER_COMPUTE_ON_FIRST_RUN+` for every solver until an operator runs +`+echidna integrity pin+`. Background: link:reports/2026-11-01-routing-and-rule-engine-recon.adoc[`+docs/reports/2026-11-01-routing-and-rule-engine-recon.adoc+`] §6 RD5. . *Dispatch* (`+dispatch.rs+`) — `+ProverDispatcher::select_prover+` diff --git a/docs/ENV-VARS.adoc b/docs/ENV-VARS.adoc index 3e4872c2..a151598f 100644 --- a/docs/ENV-VARS.adoc +++ b/docs/ENV-VARS.adoc @@ -67,9 +67,10 @@ environment override for this one. |`+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 +(`+default_manifest_path+`): `+echidna server+`, `+echidna integrity pin+` +and `+echidna integrity check+` |The solver binary manifest. An empty value +means the default. `+echidna server+` refuses to start when it cannot read +it. The images set it to `+/app/config/solver-manifest.toml+`. `+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+`. |=== diff --git a/docs/PROOF-STATUS.adoc b/docs/PROOF-STATUS.adoc index 3a7f6c08..3bb0d139 100644 --- a/docs/PROOF-STATUS.adoc +++ b/docs/PROOF-STATUS.adoc @@ -194,11 +194,16 @@ 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+`). 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. +the manifest now fails too (test `+unlisted_prover_fails+`). The fourth path is unreachable: `+verify_all()+` has no error path. +Since 2026-12-01 `+echidna server+` attaches a checker from the manifest at +start-up and refuses to start without one (owner ruling 2026-11-30: wire a +checker in before closing the no-checker path). Each dispatch hashes only +the dispatching prover's binaries (`+verify_for+`). A dispatcher built with +no checker still passes the gate, and closing that is the next step. All 17 +shipped manifest entries remain placeholders until `+echidna integrity pin+` +is run, so under D9 a server dispatch fails the gate for every prover until +its binary is pinned. `+/api/verify+` does not go through the dispatcher and +runs no integrity step. Row stays `+open+` until a Creusot or Verus run on shipped code yields a receipt with a commit hash. diff --git a/src/rust/dispatch.rs b/src/rust/dispatch.rs index ebe77212..67be4ee9 100644 --- a/src/rust/dispatch.rs +++ b/src/rust/dispatch.rs @@ -647,7 +647,7 @@ impl ProverDispatcher { // Step 6: Check solver integrity (if checker configured) let solver_integrity_ok = match self.integrity_checker { Some(ref checker) => { - let reports = checker.verify_all().await.unwrap_or_default(); + let reports = checker.verify_for(prover_kind).await; integrity_gate(Some(&reports), prover_kind) }, None => integrity_gate(None, prover_kind), @@ -850,7 +850,7 @@ impl ProverDispatcher { // Check solver integrity for cross-checked path let solver_integrity_ok = match self.integrity_checker { Some(ref checker) => { - let reports = checker.verify_all().await.unwrap_or_default(); + let reports = checker.verify_for(primary_prover).await; integrity_gate(Some(&reports), primary_prover) }, None => integrity_gate(None, primary_prover), @@ -994,7 +994,7 @@ impl ProverDispatcher { let solver_integrity_ok = match self.integrity_checker { Some(ref checker) => { - let reports = checker.verify_all().await.unwrap_or_default(); + let reports = checker.verify_for(winning_kind).await; integrity_gate(Some(&reports), winning_kind) }, None => integrity_gate(None, winning_kind), diff --git a/src/rust/integrity/solver_integrity.rs b/src/rust/integrity/solver_integrity.rs index 6f549241..81dd01a6 100644 --- a/src/rust/integrity/solver_integrity.rs +++ b/src/rust/integrity/solver_integrity.rs @@ -552,6 +552,30 @@ pub fn apply_pins(text: &str, pins: &std::collections::BTreeMap) } Ok(doc.to_string()) } + +impl IntegrityChecker { + /// Verify only the manifest entries whose key names `prover` (through + /// `manifest_key_prover`), and cache their reports. This is what the + /// dispatch gate needs: hashing every listed binary on each dispatch + /// costs a full read of each one. The result is empty when no entry + /// names the prover, which the gate treats as a failure (D9). + pub async fn verify_for( + &self, + prover: crate::provers::ProverKind, + ) -> Vec { + let mut results = Vec::new(); + for (name, entry) in &self.manifest.solvers { + if manifest_key_prover(name) == Some(prover) { + results.push(self.verify_solver(name, entry).await); + } + } + let mut reports = self.reports.write().await; + for report in &results { + reports.insert(report.name.clone(), report.clone()); + } + results + } +} #[cfg(test)] mod tests { use super::*; @@ -908,3 +932,48 @@ mod pin_tests { assert!(apply_pins(text, &pins).is_err()); } } + +#[cfg(test)] +mod verify_for_tests { + use super::*; + use crate::provers::ProverKind; + use std::io::Write; + use tempfile::NamedTempFile; + + /// Per dispatch only the dispatching prover's binaries are hashed: + /// verify_for returns reports for the entries that name that prover and + /// for no other. + #[tokio::test] + async fn verify_for_checks_only_the_named_prover() { + let mut bin = NamedTempFile::new().unwrap(); + bin.write_all(b"z3 binary").unwrap(); + let hash = IntegrityChecker::compute_shake3_512(bin.path()).unwrap(); + let entry = |path: &str, hash: &str| SolverManifestEntry { + version: "1".into(), + shake3_512: hash.into(), + path: path.into(), + fallback_paths: vec![], + }; + let checker = IntegrityChecker::new(SolverManifest { + solvers: [ + ( + "z3".to_string(), + entry(&bin.path().display().to_string(), &hash), + ), + ("cvc5".to_string(), entry("/nonexistent/echidna-cvc5", "00")), + ] + .into_iter() + .collect(), + }); + + let z3 = checker.verify_for(ProverKind::Z3).await; + assert_eq!(z3.len(), 1); + assert_eq!(z3[0].name, "z3"); + assert_eq!(z3[0].status, IntegrityStatus::Verified); + assert!(integrity_gate(Some(&z3), ProverKind::Z3)); + + let lean = checker.verify_for(ProverKind::Lean).await; + assert!(lean.is_empty()); + assert!(!integrity_gate(Some(&lean), ProverKind::Lean)); + } +} diff --git a/src/rust/server/mod.rs b/src/rust/server/mod.rs index aea3be82..e24daa20 100644 --- a/src/rust/server/mod.rs +++ b/src/rust/server/mod.rs @@ -16,6 +16,7 @@ use colored::Colorize; use echidna::agent::meta_controller::MetaController; use echidna::core::{ProofState, Tactic}; use echidna::dispatch::ProverDispatcher; +use echidna::integrity::solver_integrity::{default_manifest_path, IntegrityChecker}; use echidna::verification::StatisticsTracker; use echidna::{ProverBackend, ProverKind}; use reqwest::Client; @@ -111,7 +112,7 @@ pub async fn start_server(port: u16, host: String, enable_cors: bool) -> Result< // loop. The writer runs fire-and-forget; a VeriSimDB outage never blocks // or alters a dispatch result. let dispatcher = { - let d = ProverDispatcher::new(); + let d = build_dispatcher(&default_manifest_path())?; #[cfg(feature = "verisim")] let d = { let url = std::env::var("VERISIM_URL") @@ -346,3 +347,48 @@ impl IntoResponse for AppError { (status, body).into_response() } } + +/// The dispatcher the server shares across requests, with the solver +/// integrity checker attached from the manifest at `manifest`. +/// +/// # Errors +/// +/// When the manifest cannot be read or parsed. The server then refuses to +/// start rather than run with no integrity check. +fn build_dispatcher(manifest: &std::path::Path) -> Result { + use anyhow::Context; + let checker = IntegrityChecker::from_manifest_file(manifest).with_context(|| { + format!( + "solver integrity manifest {} is required: set ECHIDNA_SOLVER_MANIFEST to its \ + path, then pin installed binaries with `echidna integrity pin`", + manifest.display() + ) + })?; + info!( + "✓ Solver integrity manifest loaded from {}", + manifest.display() + ); + Ok(ProverDispatcher::new().with_integrity_checker(checker)) +} + +#[cfg(test)] +mod build_dispatcher_tests { + use super::build_dispatcher; + use std::path::Path; + + #[test] + fn a_missing_manifest_stops_the_server() { + let err = build_dispatcher(Path::new("/nonexistent/echidna-solver-manifest.toml")) + .err() + .expect("a missing manifest must be an error"); + let msg = format!("{err:#}"); + assert!(msg.contains("ECHIDNA_SOLVER_MANIFEST"), "{msg}"); + assert!(msg.contains("echidna integrity pin"), "{msg}"); + } + + #[test] + fn the_shipped_manifest_loads() { + let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("config/solver-manifest.toml"); + assert!(build_dispatcher(&path).is_ok()); + } +} diff --git a/src/rust/server/verify.rs b/src/rust/server/verify.rs index 89322375..7298f428 100644 --- a/src/rust/server/verify.rs +++ b/src/rust/server/verify.rs @@ -3,10 +3,10 @@ //! Verification routes: `/api/verify`, `/api/verify_parallel`, `/api/verify_raw` and the SMT passthrough helpers. -use super::{is_empty_state, AppError}; +use super::{is_empty_state, AppError, AppState}; use anyhow::Result; +use axum::extract::State; use axum::Json; -use echidna::dispatch::ProverDispatcher; use echidna::{ProverConfig, ProverKind}; use serde::{Deserialize, Serialize}; use tracing::{info, instrument}; @@ -105,6 +105,7 @@ pub(super) async fn verify_handler( /// Falls back to sequential `select_prover` heuristic when Chapel is /// unavailable. Callers that want a specific prover should use `/api/verify`. pub(super) async fn verify_parallel_handler( + State(app_state): State, Json(req): Json, ) -> Result, AppError> { let content = req @@ -114,8 +115,8 @@ pub(super) async fn verify_parallel_handler( info!("verify_parallel request ({} bytes)", content.len()); - let dispatcher = ProverDispatcher::new(); - let result = dispatcher + let result = app_state + .dispatcher .verify_proof_parallel(content) .await .map_err(|e| AppError::VerificationError(e.to_string()))?; From 81cb5b5c5ca37d1cad5de6293045a764079b4e06 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 1 Dec 2026 01:59:30 +0000 Subject: [PATCH 3/3] refactor(cli): import IntegrityOp by name in the integrity command SonarCloud rust:S2208 on #539: the module glob-imported its parent. It uses only IntegrityOp from it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_019a95kk88TZ1iegsBK3kox3 --- src/rust/cli/integrity.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/rust/cli/integrity.rs b/src/rust/cli/integrity.rs index fc7aa1ce..f6265def 100644 --- a/src/rust/cli/integrity.rs +++ b/src/rust/cli/integrity.rs @@ -4,7 +4,7 @@ //! `echidna integrity`: pin solver binary hashes into the manifest, and //! check the installed binaries against it. -use super::*; +use super::IntegrityOp; use anyhow::{Context, Result}; use echidna::integrity::solver_integrity::{ apply_pins, default_manifest_path, IntegrityChecker, IntegrityStatus, PinOutcome,